Skip to content

Commit

Permalink
Adds :serializable option to .represent. Closes #7
Browse files Browse the repository at this point in the history
  • Loading branch information
mbleigh committed Mar 29, 2013
1 parent 00c3a0b commit 97beee5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 3 deletions.
8 changes: 5 additions & 3 deletions lib/grape_entity/entity.rb
Original file line number Diff line number Diff line change
Expand Up @@ -288,10 +288,12 @@ def self.root(plural, singular=nil)
#  entity. Pass nil or false to represent the object or objects with no
# root name even if one is defined for the entity.
def self.represent(objects, options = {})
inner = if objects.respond_to?(:to_ary)
objects.to_ary().map{|o| self.new(o, {:collection => true}.merge(options))}
if objects.respond_to?(:to_ary)
inner = objects.to_ary().map{|o| self.new(o, {:collection => true}.merge(options))}
inner = inner.map(&:serializable_hash) if options[:serializable]
else
self.new(objects, options)
inner = self.new(objects, options)
inner = inner.serializable_hash if options[:serializable]
end

root_element = if options.has_key?(:root)
Expand Down
12 changes: 12 additions & 0 deletions spec/grape_entity/entity_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,18 @@
representation = subject.represent(4.times.map{Object.new})
representation.each{|r| r.options[:collection].should be_true}
end

it 'returns a serialized hash of a single object if :serializable => true' do
subject.expose(:awesome){ true }
representation = subject.represent(Object.new, :serializable => true)
representation.should == {awesome: true}
end

it 'returns a serialized array of hashes of multiple objects if :serializable => true' do
subject.expose(:awesome){ true }
representation = subject.represent(2.times.map{ Object.new }, :serializable => true)
representation.should == [{awesome: true},{awesome: true}]
end
end

describe '.root' do
Expand Down

0 comments on commit 97beee5

Please sign in to comment.