lib/simple_model/attributes.rb in simple_model-1.2.1 vs lib/simple_model/attributes.rb in simple_model-1.2.2
- old
+ new
@@ -43,18 +43,25 @@
return self.send(arg) if (arg.is_a?(Symbol) && self.respond_to?(arg))
arg
end
# Returns attribute that have defaults in a hash: {:attrbute => "default value"}
+ # Checks for alias attributes to ensure they are not overwritten
def attributes_with_for_init(attrs)
d = attrs.with_indifferent_access
self.class.defined_attributes.each do |k,v|
- d[k] = fetch_default_value(v[:default]) if (d[k].blank? && v[:default] && v[:initialize])
+ if allow_set_default?(d,k,v)
+ d[k] = fetch_default_value(v[:default])
+ end
end
d
end
+ def allow_set_default?(d,k,v)
+ (v[:default] && v[:initialize] && (d[k].blank? && (self.class.alias_attributes[k].blank? || d.key?(self.class.alias_attributes[k]) && d[self.class.alias_attributes[k]].blank?)))
+ end
+
module ClassMethods
# Creates a new instance where the attributes store is set to object
# provided, which allows one to pass a session store hash or any other
# hash-like object to be used for persistance. Typically used for modeling
# session stores for authorization or shopping carts
@@ -72,13 +79,16 @@
new.attributes = session_hash
new.set(new.send(:attributes_with_for_init,session_hash))
new
end
+ def alias_attributes
+ @alias_attributes ||= {}.with_indifferent_access
+ end
def defined_attributes
- @defined_attributes ||= {}
+ @defined_attributes ||= {}.with_indifferent_access
end
def defined_attributes=defined_attributes
@defined_attributes = defined_attributes
end
@@ -177,9 +187,10 @@
end
# Creates alias setter and getter for the supplied attribute using the supplied alias
# See spec for example.
def alias_attribute(new_alias,attribute)
+ alias_attributes[attribute] = new_alias
define_method(new_alias) do
self.send(attribute)
end
define_method("#{new_alias.to_s}=") do |*args, &block|
self.send("#{attribute.to_s}=",*args, &block)
\ No newline at end of file