Skip to content
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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

myabc
Copy link

@myabc myabc commented Nov 16, 2016

@apotonick An alternative would be for #from_hash to fail silently (i.e. data = {} unless ::Hash === data). However, I think raising a TypeError makes more sense in a web application context. it allows the Operation or web framework Controller to rescue TypeError and return a 400 to the client.

@@ -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
Copy link
Author

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"
Copy link
Author

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.

@@ -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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant