diff --git a/CHANGELOG.markdown b/CHANGELOG.markdown index e29db74b89..5507ef8e31 100644 --- a/CHANGELOG.markdown +++ b/CHANGELOG.markdown @@ -14,6 +14,7 @@ * [#133](https://github.com/intridea/grape/issues/133): Fix: header-based versioning with use of `prefix` - [@seanmoon](https://github.com/seanmoon), [@dblock](https://github.com/dblock). * [#133](https://github.com/intridea/grape/issues/133): The value of `env['PATH_INFO']` is no longer altered with `path` versioning - [@dblock](https://github.com/dblock). * [#280](https://github.com/intridea/grape/issues/280): Fix: grouped parameters mangled in `route_params` hash - [@marcusg](https://github.com/marcusg), [@dblock](https://github.com/dblock). +* [#304](https://github.com/intridea/grape/issues/304): Fix: `present x, :with => Entity` returns class references with `format :json` - [@dblock](https://github.com/dblock). * Your contribution here. diff --git a/lib/grape/entity.rb b/lib/grape/entity.rb index ce7785f5cb..0fbf332dce 100644 --- a/lib/grape/entity.rb +++ b/lib/grape/entity.rb @@ -330,6 +330,11 @@ def serializable_hash(runtime_options = {}) alias :as_json :serializable_hash + def to_json(options = {}) + options = options.to_h if options && options.respond_to?(:to_h) + MultiJson.dump(serializable_hash(options)) + end + protected def key_for(attribute) diff --git a/spec/grape/endpoint_spec.rb b/spec/grape/endpoint_spec.rb index 7fb5e65cef..596f7d83d1 100644 --- a/spec/grape/endpoint_spec.rb +++ b/spec/grape/endpoint_spec.rb @@ -472,6 +472,53 @@ def memoized end get '/example' end + + [ :json, :serializable_hash ].each do |format| + + it 'presents with #{format}' do + entity = Class.new(Grape::Entity) + entity.root "examples", "example" + entity.expose :id + + subject.format format + subject.get '/example' do + c = Class.new do + attr_reader :id + def initialize(id) + @id = id + end + end + present c.new(1), :with => entity + end + + get '/example' + last_response.status.should == 200 + last_response.body.should == '{"example":{"id":1}}' + end + + it 'presents with #{format} collection' do + entity = Class.new(Grape::Entity) + entity.root "examples", "example" + entity.expose :id + + subject.format format + subject.get '/examples' do + c = Class.new do + attr_reader :id + def initialize(id) + @id = id + end + end + examples = [ c.new(1), c.new(2) ] + present examples, :with => entity + end + + get '/examples' + last_response.status.should == 200 + last_response.body.should == '{"examples":[{"id":1},{"id":2}]}' + end + + end end context 'filters' do