Skip to content

Commit

Permalink
Use 1.9 call style for multi assignment instead of brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
dhh committed Nov 27, 2011
1 parent f0fe555 commit e84ea27
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
12 changes: 7 additions & 5 deletions lib/jbuilder.rb
Expand Up @@ -38,18 +38,20 @@ def child!
#
# Example:
#
# json.people @people, :name, :age
# json.extract! @person, :name, :age
#
# { "people": [ { "David", 32 }, { "Jamie", 31 } ] }
# { "David", 32 }, { "Jamie", 31 }
#
# If you are using Ruby 1.9+, you can use the call syntax instead of an explicit extract! call:
#
# json.(@person, :name, :age)
def extract!(object, *attributes)
attributes.each do |attribute|
__send__ attribute, object.send(attribute)
end
end

def []=(*attributes, object)
extract!(object, *attributes)
end
alias :call :extract! if RUBY_VERSION > '1.9'

# Returns the attributes of the current builder.
def attributes!
Expand Down
4 changes: 2 additions & 2 deletions test/jbuilder_test.rb
Expand Up @@ -37,11 +37,11 @@ class JbuilderTest < ActiveSupport::TestCase
end
end

test "extracting from object using bracket style" do
test "extracting from object using call style for 1.9" do
person = Struct.new(:name, :age).new("David", 32)

json = Jbuilder.encode do |json|
json[:name, :age] = person
json.(person, :name, :age)
end

JSON.parse(json).tap do |parsed|
Expand Down

0 comments on commit e84ea27

Please sign in to comment.