-
Notifications
You must be signed in to change notification settings - Fork 108
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Teach #from_hash to raise TypeError when argument is not a Hash #203
base: master
Are you sure you want to change the base?
Conversation
Signed-off-by: Alex Coles <[email protected]>
Signed-off-by: Alex Coles <[email protected]>
@@ -26,6 +26,7 @@ def collection_representer_class | |||
|
|||
def from_hash(data, options={}, binding_builder=Binding) | |||
data = filter_wrap(data, options) | |||
raise TypeError, "Expected Hash, got #{data.class}." unless ::Hash === data |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@apotonick could rely on duck typing here (unless data.respond_to?(:has_key?)
, but I think this approach is probably safer.
band.from_hash({"name"=>"Social Distortion"}, wrap: false).name.must_equal "Social Distortion" | ||
band.from_hash({band: {"name"=>"Social Distortion"}}, wrap: :band).name.must_equal "Social Distortion" | ||
band.from_hash({"name"=>"Bad Religion"}, wrap: false).name.must_equal "Bad Religion" | ||
band.from_hash({"band"=>{"name"=>"Pennywise"}}, wrap: :band).name.must_equal "Pennywise" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@apotonick as long as filter_wrap_for
calls #to_s
on wrap
(and we don't mix in AllowSymbols
), this is necessary.
Signed-off-by: Alex Coles <[email protected]>
4f8c9e2
to
8239003
Compare
@@ -19,6 +19,14 @@ def items(options={}, &block) | |||
|
|||
# TODO: revise lonely collection and build separate pipeline where we just use Serialize, etc. | |||
|
|||
def from_hash(data, options={}, binding_builder=Binding) | |||
data = filter_wrap(data, options) | |||
data = [data] if ::Hash === data |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@apotonick this makes #from_hash
more lenient - accepting a single Hash for a collection. I'm not sure if this is desirable.
@apotonick An alternative would be for
#from_hash
to fail silently (i.e.data = {} unless ::Hash === data
). However, I think raising aTypeError
makes more sense in a web application context. it allows theOperation
or web framework Controller to rescueTypeError
and return a400
to the client.