Permalink
Browse files

Name supplied to code method is now optional. Useful to added partial…

…s or calculated attributes on collection templates.
  • Loading branch information...
1 parent bffe252 commit b2bd8a0dd3c2bf64044f97f68ec1dac5052bd90a Brent Murphy committed Oct 19, 2011
Showing with 24 additions and 6 deletions.
  1. +9 −3 lib/rabl/builder.rb
  2. +3 −3 lib/rabl/engine.rb
  3. +12 −0 test/engine_test.rb
View
@@ -25,8 +25,8 @@ def to_hash(options={})
attribute(attribute, :as => name)
end if @options.has_key?(:attributes)
# Code
- @options[:code].each_pair do |name, settings|
- code(name, settings[:options], &settings[:block])
+ @options[:code].each do |settings|
+ code(settings[:name], settings[:options], &settings[:block])
end if @options.has_key?(:code)
# Children
@options[:child].each do |settings|
@@ -61,7 +61,13 @@ def attribute(*args)
# code(:foo) { "bar" }
# code(:foo, :if => lambda { |m| m.foo.present? }) { "bar" }
def code(name, options={}, &block)
- @_result[name] = block.call(@_object) if resolve_condition(options)
+ return unless resolve_condition(options)
+ result = block.call(@_object)
+ if name.present?
+ @_result[name] = result
+ else
+ @_result.merge!(result) if result
+ end
end
alias_method :node, :code
View
@@ -99,9 +99,9 @@ def attribute(*args)
# Creates an arbitrary code node that is included in the json output
# code(:foo) { "bar" }
# code(:foo, :if => lambda { ... }) { "bar" }
- def code(name, options={}, &block)
- @_options[:code] ||= {}
- @_options[:code][name] = { :options => options, :block => block }
+ def code(name = nil, options={}, &block)
+ @_options[:code] ||= []
+ @_options[:code] << { :name => name, :options => options, :block => block }
end
alias_method :node, :code
View
@@ -146,6 +146,18 @@
}
template.render(Object.new)
end.equals "{}"
+
+ asserts "that it can merge the result with a collection element given no name" do
+ template = rabl %{
+ collection @users
+ code do |user|
+ {:name => user.name}
+ end
+ }
+ scope = Object.new
+ scope.instance_variable_set :@users, [User.new(:name => 'a'), User.new(:name => 'b')]
+ template.render(scope)
+ end.equals "[{\"user\":{\"name\":\"a\"}},{\"user\":{\"name\":\"b\"}}]"
end

0 comments on commit b2bd8a0

Please sign in to comment.