lib/virtus/instance_methods.rb in virtus-0.2.0 vs lib/virtus/instance_methods.rb in virtus-0.3.0
- old
+ new
@@ -80,21 +80,18 @@
#
# @return [Hash]
#
# @api public
def attributes
- self.class.attributes.each_with_object({}) do |attribute, attributes|
- name = attribute.name
- attributes[name] = self[name] if attribute.public_reader?
- end
+ get_attributes(&:public_reader?)
end
# Mass-assign attribute values
#
# Keys in the +attribute_values+ param can be symbols or strings.
- # Only non-private referenced Attribute writer methods will be called.
- # Non-attribute setter methods on the receiver will not be called.
+ # All referenced Attribute writer methods *will* be called.
+ # Non-attribute setter methods on the receiver *will* be called.
#
# @example
# class User
# include Virtus
#
@@ -110,15 +107,11 @@
#
# @return [Hash]
#
# @api public
def attributes=(attribute_values)
- attributes = self.class.attributes
- set_attributes(attribute_values.select { |name,|
- attribute = attributes[name]
- attribute && attribute.public_writer?
- })
+ set_attributes(attribute_values)
end
# Returns a hash of all publicly accessible attributes
#
# @example
@@ -139,45 +132,31 @@
attributes
end
private
- # Mass-assign attribute values
+ # Get values of all attributes defined for this class, ignoring privacy
#
- # Keys in the +attribute_values+ param can be symbols or strings.
- # All referenced Attribute writer methods *will* be called.
- # Non-attribute setter methods on the receiver *will* be called.
- #
- # @example
- # class User
- # include Virtus
- #
- # attribute :name, String
- # attribute :age, Integer
- # end
- #
- # user = User.new
- # user.attributes = { :name => 'John', 'age' => 28 }
- #
- # @param [#to_hash] attribute_values
- # a hash of attribute names and values to set on the receiver
- #
# @return [Hash]
#
# @api private
- def set_attributes(attribute_values)
- attribute_values.each { |pair| set_attribute(*pair) }
+ def get_attributes
+ self.class.attributes.each_with_object({}) do |attribute, attributes|
+ name = attribute.name
+ attributes[name] = get_attribute(name) if yield(attribute)
+ end
end
- # Get values of all attributes defined for this class, ignoring privacy
+ # Mass-assign attribute values
#
+ # @see Virtus::InstanceMethods#attributes=
+ #
# @return [Hash]
#
# @api private
- def get_attributes
- self.class.attributes.each_with_object({}) do |attribute, attributes|
- attribute_name = attribute.name
- attributes[attribute_name] = get_attribute(attribute_name)
+ def set_attributes(attribute_values)
+ attribute_values.each do |name, value|
+ set_attribute(name, value) if self.class.allowed_writer_methods.include?("#{name}=")
end
end
# Returns a value of the attribute with the given name
#