Skip to content

Fix json serialization of nested hash when using root elements with a Grape::Entity presenter #181

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

Merged
merged 8 commits into from
Jul 17, 2012
1 change: 1 addition & 0 deletions CHANGELOG.markdown
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
Next Release
============

* [#181](https://github.com/intridea/grape/pull/181): Fix: Corrected JSON serialization of nested hashes containing `Grape::Entity` instances - [@benrosenblum](https://github.com/benrosenblum).
* [#64](https://github.com/intridea/grape/issues/64), [#180](https://github.com/intridea/grape/pull/180): Added support to get request bodies as parameters - [@bobbytables](https://github.com/bobbytables).
* [#175](https://github.com/intridea/grape/pull/175): Added support for API versioning based on a request parameter - [@jackcasey](https://github.com/jackcasey).
* [#168](https://github.com/intridea/grape/pull/168): Fix: Formatter can parse symbol keys in the headers hash - [@netmask](https://github.com/netmask).
Expand Down
5 changes: 4 additions & 1 deletion lib/grape/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,10 @@ def serializable_hash(runtime_options = {})
return nil if object.nil?
opts = options.merge(runtime_options || {})
exposures.inject({}) do |output, (attribute, exposure_options)|
output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
partial_output = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
partial_output = partial_output.serializable_hash(runtime_options) if partial_output.respond_to? :serializable_hash
output[key_for(attribute)] = partial_output

output
end
end
Expand Down
21 changes: 15 additions & 6 deletions lib/grape/middleware/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -110,17 +110,26 @@ def decode_json(object)
MultiJson.load(object)
end

def serialize_recurse(object)
if object.respond_to? :serializable_hash
object.serializable_hash
elsif object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false)
object.map {|o| o.serializable_hash }
elsif object.kind_of?(Hash)
object.inject({}) { |h,(k,v)| h[k] = serialize_recurse(v); h }
else
object
end
end

def encode_json(object)
return object if object.is_a?(String)

if object.respond_to? :serializable_hash
MultiJson.dump(object.serializable_hash)
elsif object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false)
MultiJson.dump(object.map {|o| o.serializable_hash })
elsif object.respond_to? :to_json
serialized_hash = serialize_recurse(object)
if (object == serialized_hash) && (object.respond_to? :to_json)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you explain the comparison here? I am also afraid that seriazlie_recurse, which is quite hefty for large JSONs, is going to run for every JSON output, then get thrown out.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The idea is that if the objects supports serializable_hash, or is an array or hash of those objects, then we need to build a new array or hash of the results of the serializable_hash calls. Otherwise, we want the results of to_json as our final output. The comparison checks if the unmodified object has been returned, and is an equivalent to the final condition in the previous code. You're right that this is unclear, and I'll refactor it to have everything inside a single serialize_object method or similar.

It is hefty for deeply nested hashes, but how else can we ensure they are properly serialized?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think my biggest problem with this is that we call serialize_recurse every time, then compare the object to the result of the serialization. So I am not arguing the purpose, but the implementation has to be unwrapped into something that looks less obscure. Maybe something in this genre?

def serializable?(object)
   object.respond_to? :serializable_hash
     || object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false)
     || object.kind_of?(Hash)
end

def serialize(object)
 # just like now
end

def encode_json(object)
 return object if object.is_a?(String)
 return MultiJson.dump(serialize(object)) if  serializable?(object)
 ...
end

I can take a stab at this if you don't find anything workable.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, I agree. Your implementation is much cleaner :) I'll try to find some time in the next day or two to tidy this up.

object.to_json
else
MultiJson.dump(object)
MultiJson.dump(serialized_hash)
end
end

Expand Down
22 changes: 22 additions & 0 deletions spec/grape/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,28 @@
fresh_class.expose :name
expect{ fresh_class.new(nil).serializable_hash }.not_to raise_error
end

it 'should serialize embedded objects which respond to #serializable_hash' do
class EmbeddedExample
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should know that these definitions become global in Ruby, and notably pollute other tests. Either use subject that gets cleared every time or move the classes into spec/support with a better defined name.

def serializable_hash(opts = {})
{:abc => 'def'}
end
end

class SimpleExample
def name
"abc"
end

def embedded
EmbeddedExample.new
end
end

fresh_class.expose :name, :embedded
presenter = fresh_class.new(SimpleExample.new)
presenter.serializable_hash.should == {:name => "abc", :embedded => {:abc => "def"}}
end
end

describe '#value_for' do
Expand Down
12 changes: 12 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,18 @@ def serializable_hash
subject.call({'PATH_INFO' => '/somewhere', 'HTTP_ACCEPT' => 'application/json'}).last.each{|b| b.should == '{"abc":"def"}'}
end

it 'should serialize objects that respond to #serializable_hash if there is a root element' do
class SimpleExample
def serializable_hash
{:abc => 'def'}
end
end

@body = {"root" => SimpleExample.new}

subject.call({'PATH_INFO' => '/somewhere', 'HTTP_ACCEPT' => 'application/json'}).last.each{|b| b.should == '{"root":{"abc":"def"}}'}
end

it 'should call #to_xml if the content type is xml' do
@body = "string"
@body.instance_eval do
Expand Down