Skip to content

Commit aa6efc7

Browse files
author
David Heinemeier Hansson
committed
Merge pull request #52 from aantix/master
Added support for hashes for the extract! method.
2 parents 6f65e2c + e85cf94 commit aa6efc7

File tree

2 files changed

+27
-4
lines changed

2 files changed

+27
-4
lines changed

lib/jbuilder.rb

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -138,10 +138,16 @@ def array!(collection)
138138
end
139139
end
140140

141-
# Extracts the mentioned attributes from the passed object and turns them into attributes of the JSON.
141+
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
142142
#
143143
# Example:
144144
#
145+
# @person = Struct.new(:name, :age).new("David", 32)
146+
#
147+
# or you can utilize a Hash
148+
#
149+
# @person = {:name => "David", :age => 32}
150+
#
145151
# json.extract! @person, :name, :age
146152
#
147153
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
@@ -150,9 +156,13 @@ def array!(collection)
150156
#
151157
# json.(@person, :name, :age)
152158
def extract!(object, *attributes)
153-
attributes.each do |attribute|
154-
__send__ attribute, object.send(attribute)
159+
p = if object.is_a?(Hash)
160+
lambda{|attribute| __send__ attribute, object.send(:fetch, attribute)}
161+
else
162+
lambda{|attribute| __send__ attribute, object.send(attribute)}
155163
end
164+
165+
attributes.each{|attribute| p.call(attribute)}
156166
end
157167

158168
if RUBY_VERSION > '1.9'

test/jbuilder_test.rb

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,20 @@ class JbuilderTest < ActiveSupport::TestCase
6767
assert_equal 32, parsed["age"]
6868
end
6969
end
70-
70+
71+
test "extracting from hash" do
72+
person = {:name => "Jim", :age => 34}
73+
74+
json = Jbuilder.encode do |json|
75+
json.extract! person, :name, :age
76+
end
77+
78+
JSON.parse(json).tap do |parsed|
79+
assert_equal "Jim", parsed["name"]
80+
assert_equal 34, parsed["age"]
81+
end
82+
end
83+
7184
test "nesting single child with block" do
7285
json = Jbuilder.encode do |json|
7386
json.author do |json|

0 commit comments

Comments
 (0)