Skip to content

Commit 409225e

Browse files
committed
Merge pull request #27 from clintonb/serialize-hashes
Properly serializing hashes
2 parents 7e35665 + 0a42ebe commit 409225e

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ Next Release
55
* [#18](https://github.com/intridea/grape-entity/pull/18): Add `safe` option to `expose`, will not raise error for a missing attribute - [@fixme](https://github.com/fixme).
66
* [#16](https://github.com/intridea/grape-entity/pull/16): Add `using` option to `expose SYMBOL BLOCK` - [@fahchen](https://github.com/fahchen).
77
* [#24](https://github.com/intridea/grape-entity/pull/24): Return documentation with `as` param considered - [@drakula2k](https://github.com/drakula2k).
8+
* [#27](https://github.com/intridea/grape-entity/pull/27): Properly serializing hashes - [@clintonb](https://github.com/clintonb).
89
* Your contribution here.
910

1011
0.3.0 (2013-03-29)

lib/grape_entity/entity.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,10 @@ def serializable_hash(runtime_options = {})
344344
partial_output.serializable_hash(runtime_options)
345345
elsif partial_output.kind_of?(Array) && !partial_output.map {|o| o.respond_to? :serializable_hash}.include?(false)
346346
partial_output.map {|o| o.serializable_hash}
347+
elsif partial_output.kind_of?(Hash)
348+
partial_output.each do |key, value|
349+
partial_output[key] = value.serializable_hash if value.respond_to? :serializable_hash
350+
end
347351
else
348352
partial_output
349353
end

spec/grape_entity/entity_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,14 @@ def serializable_hash(opts = {})
387387
{ :abc => 'def' }
388388
end
389389
end
390+
class EmbeddedExampleWithHash
391+
def name
392+
"abc"
393+
end
394+
def embedded
395+
{ :a => nil, :b => EmbeddedExample.new }
396+
end
397+
end
390398
class EmbeddedExampleWithMany
391399
def name
392400
"abc"
@@ -417,6 +425,12 @@ def embedded
417425
presenter.serializable_hash.should == {:name => "abc", :embedded => [{:abc => "def"}, {:abc => "def"}]}
418426
end
419427

428+
it 'serializes embedded hashes of objects which respond to #serializable_hash' do
429+
fresh_class.expose :name, :embedded
430+
presenter = fresh_class.new(EntitySpec::EmbeddedExampleWithHash.new)
431+
presenter.serializable_hash.should == {:name => "abc", :embedded => {:a => nil, :b => {:abc => "def"}}}
432+
end
433+
420434
end
421435

422436
end

0 commit comments

Comments
 (0)