Skip to content

Commit

Permalink
Merge pull request #52 from aantix/master
Browse files Browse the repository at this point in the history
Added support for hashes for the extract! method.
  • Loading branch information
dhh committed Aug 28, 2012
2 parents 6f65e2c + e85cf94 commit aa6efc7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
16 changes: 13 additions & 3 deletions lib/jbuilder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -138,10 +138,16 @@ def array!(collection)
end
end

# Extracts the mentioned attributes from the passed object and turns them into attributes of the JSON.
# Extracts the mentioned attributes or hash elements from the passed object and turns them into attributes of the JSON.
#
# Example:
#
# @person = Struct.new(:name, :age).new("David", 32)
#
# or you can utilize a Hash
#
# @person = {:name => "David", :age => 32}
#
# json.extract! @person, :name, :age
#
# { "name": David", "age": 32 }, { "name": Jamie", "age": 31 }
Expand All @@ -150,9 +156,13 @@ def array!(collection)
#
# json.(@person, :name, :age)
def extract!(object, *attributes)
attributes.each do |attribute|
__send__ attribute, object.send(attribute)
p = if object.is_a?(Hash)
lambda{|attribute| __send__ attribute, object.send(:fetch, attribute)}
else
lambda{|attribute| __send__ attribute, object.send(attribute)}
end

attributes.each{|attribute| p.call(attribute)}
end

if RUBY_VERSION > '1.9'
Expand Down
15 changes: 14 additions & 1 deletion test/jbuilder_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,20 @@ class JbuilderTest < ActiveSupport::TestCase
assert_equal 32, parsed["age"]
end
end


test "extracting from hash" do
person = {:name => "Jim", :age => 34}

json = Jbuilder.encode do |json|
json.extract! person, :name, :age
end

JSON.parse(json).tap do |parsed|
assert_equal "Jim", parsed["name"]
assert_equal 34, parsed["age"]
end
end

test "nesting single child with block" do
json = Jbuilder.encode do |json|
json.author do |json|
Expand Down

0 comments on commit aa6efc7

Please sign in to comment.