lib/acfs/model/attributes.rb in acfs-0.22.2.b196 vs lib/acfs/model/attributes.rb in acfs-0.22.2
- old
+ new
@@ -123,15 +123,15 @@
# @param [ String, Symbol ] name Attribute name.
# @param [ Object ] value Value to write.
# @raise [ ArgumentError ] If no attribute with given name is defined.
#
def write_attribute(name, value, opts = {})
- if (attr = self.class.defined_attributes[name.to_s]).nil?
+ if (type = self.class.attribute_types[name.to_sym]).nil?
raise ArgumentError.new "Unknown attribute `#{name}`."
end
- write_raw_attribute name, attr.cast(value), opts
+ write_raw_attribute name, value.nil? ? nil : type.cast(value), opts
end
# @api private
#
# Write an attribute without checking type or existence or casting
@@ -185,21 +185,13 @@
# User.attributes # => { "name": nil, "age": 25 }
#
# @return [ Hash{ String => Object, Proc } ] Attributes with default values.
#
def attributes
- Hash.new.tap do |attrs|
- defined_attributes.each do |key, attr|
- attrs[key] = attr.default_value
- end
- end
+ @attributes ||= {}.merge superclass.respond_to?(:attributes) ? superclass.attributes : {}
end
- def defined_attributes
- @attributes ||= {}.merge superclass.respond_to?(:defined_attributes) ? superclass.defined_attributes : {}
- end
-
# @api public
#
# Return hash of attributes and there types.
#
# @example
@@ -217,12 +209,14 @@
end
private
def define_attribute(name, type, opts = {})
name = name.to_s
- attribute = type.new opts
+ default_value = opts.has_key?(:default) ? opts[:default] : nil
+ default_value = type.cast default_value unless default_value.is_a? Proc or default_value.nil?
- defined_attributes[name] = attribute
+ attributes[name] = default_value
+ attribute_types[name.to_sym] = type
define_attribute_method name
self.send :define_method, name do
read_attribute name
end