Module: ModelX::Attributes
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
-
#[](attribute) ⇒ Object
Reads an attribute value.
-
#assign_attributes(values, options = {}) ⇒ Object
Assigns the model’s attributes with the values from the given hash.
-
#attributes ⇒ Object
Attributes hash.
-
#attributes=(values) ⇒ Object
Assigns the attributes hash by setting all given values through attribute writers.
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.
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, = {}) raise ArgumentError, "hash required" unless values.is_a?(Hash) = .symbolize_keys .assert_valid_keys :missing values.each do |key, value| if respond_to?(:"#{key}=") send :"#{key}=", value elsif [:missing] == :raise raise AttributeNotFound, "attribute :#{key} not found" end end self end |
#attributes ⇒ Object
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.
34 35 36 |
# File 'lib/model_x/attributes.rb', line 34 def attributes=(values) assign_attributes values end |