lib/contentful/resource.rb in contentful-0.3.0 vs lib/contentful/resource.rb in contentful-0.3.1
- old
+ new
@@ -6,12 +6,12 @@
# This is done by the default in the existing resource classes
#
# You can define your own classes that behave like contentful resources:
# See examples/custom_classes.rb to see how.
#
- # Take a look at examples/resource_mapping.rb on how to register them to be returned
- # by the client by default
+ # Take a look at examples/resource_mapping.rb on how to register them
+ # to be returned by the client by default
module Resource
COERCIONS = {
string: ->(v) { v.to_s },
integer: ->(v) { v.to_i },
float: ->(v) { v.to_f },
@@ -24,11 +24,12 @@
def initialize(object, request = nil, client = nil, nested_locale_fields = false, default_locale = Contentful::Client::DEFAULT_CONFIGURATION[:default_locale] )
self.class.update_coercions!
@nested_locale_fields = nested_locale_fields
@default_locale = default_locale
- @properties = extract_from_object object, :property, self.class.property_coercions.keys
+ @properties = extract_from_object(object, :property,
+ self.class.property_coercions.keys)
@request = request
@client = client
end
def inspect(info = nil)
@@ -70,21 +71,22 @@
def extract_from_object(object, namespace, keys = nil)
if object
keys ||= object.keys
keys.each.with_object({}) do |name, res|
- res[name.to_sym] = coerce_value_or_array(
- object.is_a?(::Array) ? object : object[name.to_s],
- self.class.public_send(:"#{namespace}_coercions")[name.to_sym]
- )
+ value = object.is_a?(::Array) ? object : object[name.to_s]
+ kind = self.class.public_send(:"#{namespace}_coercions")[name.to_sym]
+ res[name.to_sym] = coerce_value_or_array(value, kind)
end
else
{}
end
end
def coerce_value_or_array(value, what = nil)
- if value.is_a? ::Array
+ if value.nil?
+ nil
+ elsif value.is_a? ::Array
value.map { |v| coerce_or_create_class(v, what) }
else
coerce_or_create_class(value, what)
end
end