Skip to content

Commit cb1db4f

Browse files
author
Jon Evans
committed
Allow entity root key to be overridden
When calling represent, pass the :root => 'name' option to use 'name' as the root key. Pass :root => nil (or false) to represent with no root key.
1 parent 6494f59 commit cb1db4f

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

lib/grape/entity.rb

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,14 +138,22 @@ def self.root(plural, singular=nil)
138138
# @param objects [Object or Array] One or more objects to be represented.
139139
# @param options [Hash] Options that will be passed through to each entity
140140
# representation.
141+
#
142+
# @option options :root [String] override the default root name set for the
143+
#  entity. Pass nil or false to represent the object or objects with no
144+
# root name even if one is defined for the entity.
141145
def self.represent(objects, options = {})
142146
inner = if objects.is_a?(Array)
143147
objects.map{|o| self.new(o, {:collection => true}.merge(options))}
144148
else
145149
self.new(objects, options)
146150
end
147151

148-
root_element = objects.is_a?(Array) ? @collection_root : @root
152+
root_element = if options.has_key?(:root)
153+
options[:root]
154+
else
155+
objects.is_a?(Array) ? @collection_root : @root
156+
end
149157
root_element ? { root_element => inner } : inner
150158
end
151159

spec/grape/entity_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,23 @@
8484
representation['things'].reject{|r| r.kind_of?(subject)}.should be_empty
8585
end
8686
end
87+
88+
context 'it can be overridden' do
89+
it 'can be disabled' do
90+
representation = subject.represent(4.times.map{Object.new}, :root=>false)
91+
representation.should be_kind_of(Array)
92+
representation.size.should == 4
93+
representation.reject{|r| r.kind_of?(subject)}.should be_empty
94+
end
95+
it 'can use a different name' do
96+
representation = subject.represent(4.times.map{Object.new}, :root=>'others')
97+
representation.should be_kind_of(Hash)
98+
representation.should have_key('others')
99+
representation['others'].should be_kind_of(Array)
100+
representation['others'].size.should == 4
101+
representation['others'].reject{|r| r.kind_of?(subject)}.should be_empty
102+
end
103+
end
87104
end
88105

89106
context 'with singular root key' do

0 commit comments

Comments
 (0)