Module: ModelX::Attributes

Extended by:
ActiveSupport::Concern
Included in:
Mixin
Defined in:
lib/model_x/attributes.rb

Overview

Provides attribute DSL methods.

Defaults && types

For each attribute, you can set a default which is returned if the virtual attribute would otherwise be nil.

You may also specify a ‘type’ for the virtual attribute. This does nothing more than evaluate the line <type> :<attribute> into the model, e.g.

attribute :has_price, :type => :boolean

is equivalent to

attribute :has_price
boolean :has_price

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#[](attribute) ⇒ Object

Reads an attribute value.



66
67
68
# File 'lib/model_x/attributes.rb', line 66

def [](attribute)
  read_attribute attribute
end

#assign_attributes(values, options = {}) ⇒ Object

Assigns the model’s attributes with the values from the given hash.

Options Hash (options):

  • :missing (Symbol) — default: :raise

    Specify the behavior for missing attributes. :raise raises an exception, :ignore ignores the missing attributes.

Raises:

  • (ArgumentError)


43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/model_x/attributes.rb', line 43

def assign_attributes(values, options = {})
  raise ArgumentError, "hash required" unless values.is_a?(Hash)

  options = options.symbolize_keys
  options.assert_valid_keys :missing

  values.each do |key, value|
    if respond_to?(:"#{key}=")
      send :"#{key}=", value
    elsif options[:missing] == :raise
      raise AttributeNotFound, "attribute :#{key} not found"
    end
  end
  self
end

#attributesObject

Attributes hash. Builds an attributes hash from current instance variables.



23
24
25
26
27
28
29
# File 'lib/model_x/attributes.rb', line 23

def attributes
  @attributes ||= self.class.attributes.inject({}) do |attrs, name|
    next attrs if name == :'attributes'
    attrs[name.to_sym] = send(name)
    attrs
  end
end

#attributes=(values) ⇒ Object

Assigns the attributes hash by setting all given values through attribute writers.

Raises:



34
35
36
# File 'lib/model_x/attributes.rb', line 34

def attributes=(values)
  assign_attributes values
end