Skip to content

Commit 2543bf2

Browse files
committed
Make json.extract! accept objects with internal hash implementation
1 parent a0dc0bd commit 2543bf2

File tree

2 files changed

+26
-10
lines changed

2 files changed

+26
-10
lines changed

lib/jbuilder.rb

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,8 @@ def array!(collection = [], *attributes)
213213
#
214214
# json.(@person, :name, :age)
215215
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)
220218
end
221219
end
222220

@@ -252,12 +250,8 @@ def target!
252250

253251
private
254252

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)
261255
end
262256

263257
def _merge_block(key)

test/jbuilder_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,17 @@ def initialize(name, age)
3535
end
3636
end
3737

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+
3849
class RelationMock
3950
include Enumerable
4051

@@ -121,6 +132,17 @@ class JbuilderTest < ActiveSupport::TestCase
121132
assert_equal 34, result['age']
122133
end
123134

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+
124146
test 'nesting single child with block' do
125147
result = jbuild do |json|
126148
json.author do

0 commit comments

Comments
 (0)