Skip to content

Commit 5272c00

Browse files
committed
Create lookup for attribute names
- Avoid using the to_s, split, last, to_sym chain. Improves performance another ~10%.
1 parent bd12f1f commit 5272c00

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

lib/grape_entity/entity.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,9 @@ def self.expose(*args, &block)
139139

140140
args.each do |attribute|
141141
unless @nested_attributes.empty?
142+
orig_attribute = attribute.to_sym
142143
attribute = "#{@nested_attributes.last}__#{attribute}"
144+
nested_attribute_names_hash[attribute.to_sym] = orig_attribute
143145
options[:nested] = true
144146
nested_exposures_hash[@nested_attributes.last.to_sym] ||= {}
145147
nested_exposures_hash[@nested_attributes.last.to_sym][attribute.to_sym] = options
@@ -187,12 +189,29 @@ def self.exposures
187189
end
188190

189191
class << self
192+
attr_accessor :_nested_attribute_names_hash
190193
attr_accessor :_nested_exposures_hash
191194

195+
def nested_attribute_names_hash
196+
self._nested_attribute_names_hash ||= {}
197+
end
198+
192199
def nested_exposures_hash
193200
self._nested_exposures_hash ||= {}
194201
end
195202

203+
def nested_attribute_names
204+
return @nested_attribute_names unless @nested_attribute_names.nil?
205+
206+
@nested_attribute_names = {}.merge(nested_attribute_names_hash)
207+
208+
if superclass.respond_to? :nested_attribute_names
209+
@nested_attribute_names = superclass.nested_attribute_names.deep_merge(@nested_attribute_names)
210+
end
211+
212+
@nested_attribute_names
213+
end
214+
196215
def nested_exposures
197216
return @nested_exposures unless @nested_exposures.nil?
198217

@@ -408,7 +427,8 @@ def to_xml(options = {})
408427
protected
409428

410429
def self.name_for(attribute)
411-
attribute.to_s.split('__').last.to_sym
430+
attribute = attribute.to_sym
431+
nested_attribute_names[attribute] || attribute
412432
end
413433

414434
def self.key_for(attribute)

0 commit comments

Comments
 (0)