lib/rabl/builder.rb in rabl-0.14.0 vs lib/rabl/builder.rb in rabl-0.14.1
- old
+ new
@@ -135,11 +135,14 @@
# 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 = {})
- return unless @_object && attribute_present?(name) && resolve_condition(options)
+ return unless
+ @_object &&
+ attribute_present?(name) &&
+ resolve_condition(options)
attribute = data_object_attribute(name)
name = create_key(options[:as] || name)
@_result[name] = attribute
end
@@ -198,38 +201,37 @@
engines << partial_as_engine(file, options, &block)
end
# Evaluate conditions given a symbol/proc/lambda/variable to evaluate
def call_condition_proc(condition, object)
- # This will evaluate lambda, proc & symbol and call it with 1 argument
- return condition.to_proc.call(object) if condition.is_a?(Proc) || condition.is_a?(Symbol)
- # Else we send directly the object
- condition
+ case condition
+ when Proc then condition.call(object)
+ when Symbol then condition.to_proc.call(object)
+ else condition
+ end
end
# resolve_condition(:if => true) => true
# resolve_condition(:if => 'Im truthy') => true
# resolve_condition(:if => lambda { |m| false }) => false
# resolve_condition(:unless => lambda { |m| false }) => true
# resolve_condition(:unless => lambda { |m| false }, :if => proc { true}) => true
def resolve_condition(options)
result = true
- result &&= call_condition_proc(options[:if], @_object) if options.key?(:if)
- result &&= !call_condition_proc(options[:unless], @_object) if options.key?(:unless)
+ result &&= call_condition_proc(options[:if], @_object) if
+ options.key?(:if)
+ result &&= !call_condition_proc(options[:unless], @_object) if
+ options.key?(:unless)
result
end
private
# Checks if an attribute is present. If not, check if the configuration specifies that this is an error
# attribute_present?(created_at) => true
def attribute_present?(name)
- if @_object.respond_to?(name)
- true
- elsif Rabl.configuration.raise_on_missing_attribute
- raise "Failed to render missing attribute #{name}"
- else
- false
- end
+ @_object.respond_to?(name) ||
+ (Rabl.configuration.raise_on_missing_attribute &&
+ raise("Failed to render missing attribute #{name}"))
end
# Returns a guess at the format in this context_scope
# request_format => "xml"
def request_format