Skip to content

Commit a1de0e2

Browse files
committed
Grape::Entity#serializable_hash should call #serializable_hash if the data returned from #value_for responds to that method so that nested Grape::Entity presentation works correctly.
1 parent eb49952 commit a1de0e2

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/grape/entity.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,10 @@ def serializable_hash(runtime_options = {})
232232
return nil if object.nil?
233233
opts = options.merge(runtime_options || {})
234234
exposures.inject({}) do |output, (attribute, exposure_options)|
235-
output[key_for(attribute)] = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
235+
partial_output = value_for(attribute, opts) if conditions_met?(exposure_options, opts)
236+
partial_output = partial_output.serializable_hash(runtime_options) if partial_output.respond_to? :serializable_hash
237+
output[key_for(attribute)] = partial_output
238+
236239
output
237240
end
238241
end

spec/grape/entity_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,28 @@
257257
fresh_class.expose :name
258258
expect{ fresh_class.new(nil).serializable_hash }.not_to raise_error
259259
end
260+
261+
it 'should serialize embedded objects which respond to #serializable_hash' do
262+
class EmbeddedExample
263+
def serializable_hash(opts = {})
264+
{:abc => 'def'}
265+
end
266+
end
267+
268+
class SimpleExample
269+
def name
270+
"abc"
271+
end
272+
273+
def embedded
274+
EmbeddedExample.new
275+
end
276+
end
277+
278+
fresh_class.expose :name, :embedded
279+
presenter = fresh_class.new(SimpleExample.new)
280+
presenter.serializable_hash.should == {:name => "abc", :embedded => {:abc => "def"}}
281+
end
260282
end
261283

262284
describe '#value_for' do

0 commit comments

Comments
 (0)