Permalink
Browse files

Add inline extraction macro

  • Loading branch information...
1 parent 7a422c7 commit 83735964e40a2d741560059b311a2580b2b5f082 @dhh dhh committed Nov 27, 2011
Showing with 26 additions and 1 deletion.
  1. +7 −1 lib/jbuilder.rb
  2. +19 −0 test/jbuilder_test.rb
View
@@ -65,8 +65,10 @@ def method_missing(method, *args, &block)
_assign method, args.first
when args.empty? && block_given?
_yield_nesting method, block
- when args.many?
+ when args.many? && args.first.is_a?(Enumerable)
_inline_nesting method, args.first, args.from(1)
+ when args.many?
+ _inline_extract method, args.first, args.from(1)
end
end
@@ -91,4 +93,8 @@ def _inline_nesting(container, collection, attributes)
end
end
end
+
+ def _inline_extract(container, record, attributes)
+ __send__(container) { |parent| parent.extract! record, *attributes }
+ end
end
View
@@ -65,6 +65,25 @@ class JbuilderTest < ActiveSupport::TestCase
end
end
+ test "extract from non-enumerable" do
+ person = Class.new do
+ attr_reader :name, :age
+
+ def initialize(name, age)
+ @name, @age = name, age
+ end
+ end.new("David", 32)
+
+ json = Jbuilder.encode do |json|
+ json.author person, :name, :age
+ end
+
+ JSON.parse(json).tap do |parsed|
+ assert_equal "David", parsed["author"]["name"]
+ assert_equal 32, parsed["author"]["age"]
+ end
+ end
+
test "nesting multiple children from array" do
comments = [ Struct.new(:content).new("hello"), Struct.new(:content).new("world") ]

0 comments on commit 8373596

Please sign in to comment.