lib/rabl/builder.rb in rabl-0.9.4.pre1 vs lib/rabl/builder.rb in rabl-0.10.0
- old
+ new
@@ -51,20 +51,36 @@
# Return Results
@_root_name ? { @_root_name => @_result } : @_result
end
def replace_nil_values
- @_result = @_result.inject({}) do |hash, (k, v)|
- hash[k] = v.nil? ? '' : v
- hash
+ @_result = deep_replace_nil_values(@_result)
+ end
+
+ def deep_replace_nil_values(hash)
+ hash.inject({}) do |hsh, (k, v)|
+ hsh[k] = if v.is_a?(Hash)
+ deep_replace_nil_values(v)
+ else
+ v.nil? ? '' : v
+ end
+ hsh
end
end
def replace_empty_string_values
- @_result = @_result.inject({}) do |hash, (k, v)|
- hash[k] = (!v.nil? && v != "") ? v : nil
- hash
+ @_result = deep_replace_empty_string_values(@_result)
+ end
+
+ def deep_replace_empty_string_values(hash)
+ hash.inject({}) do |hsh, (k, v)|
+ hsh[k] = if v.is_a?(Hash)
+ deep_replace_empty_string_values(v)
+ else
+ (!v.nil? && v != "") ? v : nil
+ end
+ hsh
end
end
def remove_nil_values
@_result = @_result.inject({}) do |hash, (k, v)|
@@ -97,11 +113,13 @@
# Indicates an attribute or method should be included in the json output
# attribute :foo, :as => "bar"
# attribute :foo, :as => "bar", :if => lambda { |m| m.foo }
def attribute(name, options={})
if @_object && attribute_present?(name) && resolve_condition(options)
- @_result[options[:as] || name] = data_object_attribute(name)
+ attribute = data_object_attribute(name)
+ name = (options[:as] || name).to_sym
+ @_result[name] = attribute
end
end
alias_method :attributes, :attribute
# Creates an arbitrary node that is included in the json output
@@ -109,11 +127,11 @@
# node(:foo, :if => lambda { |m| m.foo.present? }) { "bar" }
def node(name, options={}, &block)
return unless resolve_condition(options)
result = block.call(@_object)
if name.present?
- @_result[name] = result
+ @_result[name.to_sym] = result
elsif result.respond_to?(:each_pair) # merge hash into root hash
@_result.merge!(result)
end
end
alias_method :code, :node
@@ -128,10 +146,10 @@
object = data_object(data)
include_root = is_collection?(object) && options.fetch(:object_root, @options[:child_root]) # child @users
engine_options = @options.slice(:child_root).merge(:root => include_root)
engine_options.merge!(:object_root_name => options[:object_root]) if is_name_value?(options[:object_root])
object = { object => name } if data.respond_to?(:each_pair) && object # child :users => :people
- @_result[name] = self.object_to_hash(object, engine_options, &block)
+ @_result[name.to_sym] = self.object_to_hash(object, engine_options, &block)
end
# Glues data from a child node to the json_output
# glue(@user) { attribute :full_name => :user_full_name }
def glue(data, options={}, &block)