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.



96
97
98
99
100
101
102
103
104
105
# 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

#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})


62
63
64
65
66
# 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) ⇒ 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.



54
55
56
# File 'lib/mixture/extensions/attributable.rb', line 54

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)


73
74
75
# File 'lib/mixture/extensions/attributable.rb', line 73

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