-
Notifications
You must be signed in to change notification settings - Fork 439
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
Make extract! accept objects with internal hash implementation #440
base: main
Are you sure you want to change the base?
Conversation
Thanks for the pull request, and welcome! The Rails team is excited to review your changes, and you should hear from @pixeltrix (or someone else) soon. If any changes to this PR are deemed necessary, please add them as extra commits. This ensures that the reviewer can see what has changed since they last reviewed the code. Due to the way GitHub handles out-of-date commits, this should also make it reasonably obvious what issues have or haven't been addressed. Large or tricky changes may require several passes of review and changes. Please see the contribution instructions for more information. |
a486397
to
2543bf2
Compare
lib/jbuilder.rb
Outdated
def _extract_method_values(object, attributes) | ||
attributes.each{ |key| _set_value key, object.public_send(key) } | ||
def _extract_value(object, attribute) | ||
object.respond_to?(attribute) ? object.public_send(attribute) : object.fetch(attribute) |
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.
The risk is pretty low but still, it should rather be:
object.respond_to?(:fetch) ? object.fetch(attribute) : object.public_send(attribute)
Otherwise, if a hash or hash-like object has a :object_id
, :hash
or any of its method as a key, the wrong value may be returned.
Could you fix this and add a test to ensure that a Hash
with such key would be properly handled please ?
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.
Sorry @robin850 I just saw your comment now. Sure I'll change it 😊
@robin850 I changed the implementation the way you suggested, however I changed respond_to?(:fetch) to respond_to?(:[]) to avoid problems when an object have a custom fetch method for other purposes. |
In a recent project I've experienced an odd situation of having an object that implements some
Hash
behavior and, even though it has methods such as[]
andfetch
,jbuilder.extract!
did not work with it. So I just created this little PR with some tests to makejbuilder
more agnostic.Here's an example (also used in the tests) of the object I'm trying to pass to jbuilder: