lib/rabl/builder.rb in rabl-0.3.0 vs lib/rabl/builder.rb in rabl-0.5.0
- old
+ new
@@ -23,12 +23,12 @@
# Attributes
@options[:attributes].each_pair do |attribute, name|
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|
child(settings[:data], settings[:options], &settings[:block])
end if @options.has_key?(:child)
@@ -59,24 +59,31 @@
# Creates an arbitrary code node that is included in the json output
# node(:foo) { "bar" }
# 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
# Creates a child node that is included in json output
# child(@user) { attribute :full_name }
# child(@user => :person) { ... }
# child(@users => :people) { ... }
def child(data, options={}, &block)
return false unless data.present?
name, object = data_name(data), data_object(data)
- include_root = object.respond_to?(:each) && @options[:child_root] # child @users
+ include_root = is_collection?(object) && @options[:child_root] # child @users
+ engine_options = @options.slice(:child_root).merge(:root => include_root)
object = { object => name } if data.respond_to?(:each_pair) && object # child :users => :people
- @_result[name] = self.object_to_hash(object, :root => include_root, &block) if resolve_condition(options)
+ @_result[name] = self.object_to_hash(object, engine_options, &block) if resolve_condition(options)
end
# Glues data from a child node to the json_output
# glue(@user) { attribute :full_name => :user_full_name }
def glue(data, &block)
@@ -87,11 +94,11 @@
end
# Extends an existing rabl template with additional attributes in the block
# extends("users/show") { attribute :full_name }
def extends(file, options={}, &block)
- options = options.merge(:object => @_object)
+ options = @options.slice(:child_root).merge(options).merge(:object => @_object)
result = self.partial(file, options, &block)
@_result.merge!(result) if result
end
end
-end
\ No newline at end of file
+end