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

Prefer custom #to_json implementations over #serializable_hash #273

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/grape/middleware/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,11 @@ def decode_json(object)
MultiJson.load(object)
end

def defines_own_to_json?(object)
return false unless object.respond_to?(:to_json)
object.method(:to_json).owner.name =~ /^JSON::Ext::Generator::GeneratorMethods/ ? false : true
end

def serializable?(object)
object.respond_to?(:serializable_hash) ||
object.kind_of?(Array) && !object.map {|o| o.respond_to? :serializable_hash }.include?(false) ||
Expand All @@ -131,6 +136,7 @@ def serialize(object)

def encode_json(object)
return object if object.is_a?(String)
return object.to_json if defines_own_to_json?(object)
return MultiJson.dump(serialize(object)) if serializable?(object)
return object.to_json if object.respond_to?(:to_json)

Expand Down
16 changes: 16 additions & 0 deletions spec/grape/middleware/formatter_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,22 @@ def to_json
subject.call({'PATH_INFO' => '/somewhere', 'HTTP_ACCEPT' => 'application/json'}).last.each{|b| b.should == '"bar"'}
end

it 'should call #to_json if custom defined instead of #serializable_hash' do
class SimpleJsonExample
def serializable_hash
{:abc => 'def'}
end

def to_json
'{"123":"456"}'
end
end

@body = SimpleJsonExample.new

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

it 'should serialize the #serializable_hash if that is available' do
class SimpleExample
def serializable_hash
Expand Down