Module: Mixture::Extensions::Attributable::InstanceMethods

Defined in:
lib/mixture/extensions/attributable.rb

Overview

The instance methods for attribution.

Instance Method Summary collapse

Instance Method Details

#attribute(key) ⇒ Object #attribute(key, value) ⇒ void

Overloads:

  • #attribute(key) ⇒ Object

    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).

    Parameters:

    • key (Symbol)

      The name of the attribute.

    Returns:

    • (Object)

      The value of the attribute.

  • #attribute(key, value) ⇒ void

    This method returns an undefined 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.

    Parameters:

    • key (Symbol)

      The name of the attribute.

    • value (Object)

      The new value of the attribute.



91
92
93
94
95
96
97
98
99
100
# File 'lib/mixture/extensions/attributable.rb', line 91

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

#attributesHash{Symbol => Object}

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

Returns:

  • (Hash{Symbol => Object})


57
58
59
60
61
# File 'lib/mixture/extensions/attributable.rb', line 57

def attributes
  Hash[self.class.attributes.map do |name, attr|
    [name, instance_variable_get(attr.ivar)]
  end]
end

#attributes=(attrs) ⇒ void

This method returns an undefined value.

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

Parameters:

  • attrs (Hash)

    The attributes to set.



49
50
51
# File 'lib/mixture/extensions/attributable.rb', line 49

def attributes=(attrs)
  attrs.each { |key, value| attribute(key, value) }
end

#unknown_attribute(attr) ⇒ Object

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

Parameters:

  • attr (Symbol)

    The attribute.

Raises:

  • (ArgumentError)


68
69
70
# File 'lib/mixture/extensions/attributable.rb', line 68

def unknown_attribute(attr)
  fail ArgumentError, "Unknown attribute #{attr} passed"
end