File tree 2 files changed +26
-10
lines changed 2 files changed +26
-10
lines changed Original file line number Diff line number Diff line change @@ -213,10 +213,8 @@ def array!(collection = [], *attributes)
213
213
#
214
214
# json.(@person, :name, :age)
215
215
def extract! ( object , *attributes )
216
- if ::Hash === object
217
- _extract_hash_values ( object , attributes )
218
- else
219
- _extract_method_values ( object , attributes )
216
+ attributes . each do |key |
217
+ _set_value key , _extract_value ( object , key )
220
218
end
221
219
end
222
220
@@ -252,12 +250,8 @@ def target!
252
250
253
251
private
254
252
255
- def _extract_hash_values ( object , attributes )
256
- attributes . each { |key | _set_value key , object . fetch ( key ) }
257
- end
258
-
259
- def _extract_method_values ( object , attributes )
260
- attributes . each { |key | _set_value key , object . public_send ( key ) }
253
+ def _extract_value ( object , attribute )
254
+ object . respond_to? ( attribute ) ? object . public_send ( attribute ) : object . fetch ( attribute )
261
255
end
262
256
263
257
def _merge_block ( key )
Original file line number Diff line number Diff line change @@ -35,6 +35,17 @@ def initialize(name, age)
35
35
end
36
36
end
37
37
38
+ class PersonWithHash
39
+ attr_reader :name , :collection
40
+
41
+ def initialize ( name , age )
42
+ @collection = { age : age }
43
+ @name = name
44
+ end
45
+
46
+ delegate :[] , :fetch , to : :@collection
47
+ end
48
+
38
49
class RelationMock
39
50
include Enumerable
40
51
@@ -121,6 +132,17 @@ class JbuilderTest < ActiveSupport::TestCase
121
132
assert_equal 34 , result [ 'age' ]
122
133
end
123
134
135
+ test 'extracting from object with internal hash' do
136
+ person = PersonWithHash . new ( 'David' , 32 )
137
+
138
+ result = jbuild do |json |
139
+ json . extract! person , :name , :age
140
+ end
141
+
142
+ assert_equal 'David' , result [ 'name' ]
143
+ assert_equal 32 , result [ 'age' ]
144
+ end
145
+
124
146
test 'nesting single child with block' do
125
147
result = jbuild do |json |
126
148
json . author do
You can’t perform that action at this time.
0 commit comments