module Mixture::Extensions::Attributable::InstanceMethods

The instance methods for attribution.

Public Instance Methods

attribute(key, value = Undefined) click to toggle source

@overload attribute(key)

Accesses an attribute by the given key name.  If the
attribute could not be found, it calls
{#unknown_attribute}.  It uses the instance variable value
of the attribute as the value of the attribute (e.g. it
uses `@name` for the `name` attribute).

@param key [Symbol] The name of the attribute.
@return [Object] The value of the attribute.

@overload attribute(key, value)

Sets an attribute value by the given key name.  If the
attribute could not be found, it calls
{#unknown_attribute}.  It calls any of the update
callbacks via {Attribute#update}, and sets the instance
variable for the attribute.

@param key [Symbol] The name of the attribute.
@param value [Object] The new value of the attribute.
@return [void]
# File lib/mixture/extensions/attributable.rb, line 96
def attribute(key, value = Undefined)
  attr = self.class.attributes.fetch(key) do
    return unknown_attribute(key)
  end

  return instance_variable_get(attr.ivar) if value == Undefined

  value = attr.update(value)
  instance_variable_set(attr.ivar, value)
end
attributes() click to toggle source

The attributes defined on this instance. It returns a hash containing the key-value pairs for each attribute.

@return [Hash{Symbol => Object}]

# File lib/mixture/extensions/attributable.rb, line 62
def attributes
  Hash[self.class.attributes.map do |name, attr|
    [name, instance_variable_get(attr.ivar)]
  end]
end
attributes=(attrs) click to toggle source

Sets the attributes on the instance. It iterates through the given hash and uses {#attribute} to set the key, value pair.

@param attrs [Hash] The attributes to set. @return [void]

# File lib/mixture/extensions/attributable.rb, line 54
def attributes=(attrs)
  attrs.each { |key, value| attribute(key, value) }
end
unknown_attribute(attr) click to toggle source

Called when an unknown attribute is accessed using {#attribute}. By default, it just raises an `ArgumentError`.

@param attr [Symbol] The attribute. @raise [ArgumentError]

# File lib/mixture/extensions/attributable.rb, line 73
def unknown_attribute(attr)
  fail ArgumentError, "Unknown attribute #{attr.inspect} passed"
end