module ModelX::Attributes
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
Public Instance Methods
[](attribute)
click to toggle source
Reads an attribute value.
# File lib/model_x/attributes.rb, line 66 def [](attribute) read_attribute attribute end
assign_attributes(values, options = {})
click to toggle source
Assigns the model's attributes with the values from the given hash.
@option options [Symbol] :missing (:raise)
Specify the behavior for missing attributes. +:raise+ raises an exception, +:ignore+ ignores the missing attributes.
# 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
attributes()
click to toggle source
Attributes
hash. Builds an attributes hash from current instance variables.
# 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)
click to toggle source
Assigns the attributes hash by setting all given values through attribute writers.
@raise [AttributeNotFound] if a certain attribute is not found.
# File lib/model_x/attributes.rb, line 34 def attributes=(values) assign_attributes values end
Protected Instance Methods
read_attribute(attribute)
click to toggle source
Reads an attribute value.
# File lib/model_x/attributes.rb, line 60 def read_attribute(attribute) instance_variable_get("@#{attribute}") end
write_attribute(attribute, value)
click to toggle source
Writes an attribute value
# File lib/model_x/attributes.rb, line 71 def write_attribute(attribute, value) @attributes = nil instance_variable_set "@#{attribute}", value end