Module: ActiveAttr::Attributes
- Extended by:
- ActiveSupport::Concern
- Includes:
- ActiveModel::AttributeMethods
- Defined in:
- lib/active_attr/attributes.rb
Overview
Attributes provides a set of class methods for defining an attributes schema and instance methods for reading and writing attributes.
Defined Under Namespace
Modules: ClassMethods
Instance Method Summary collapse
-
#==(other) ⇒ true, false
Performs equality checking on the result of attributes and its type.
-
#attributes ⇒ Hash
Returns the raw attributes Hash.
- #initialize(*args) ⇒ Object
-
#inspect ⇒ String
Returns the class name plus its attributes.
-
#read_attribute(name) ⇒ Object
(also: #[], #attribute)
Read a value from the model’s attributes.
-
#write_attribute(name, value) ⇒ Object
(also: #[]=, #attribute=)
Write a single attribute to the model’s attribute hash.
Instance Method Details
#==(other) ⇒ true, false
Performs equality checking on the result of attributes and its type.
38 39 40 41 |
# File 'lib/active_attr/attributes.rb', line 38 def ==(other) return false unless other.instance_of? self.class attributes == other.attributes end |
#attributes ⇒ Hash
Returns the raw attributes Hash
51 52 53 54 |
# File 'lib/active_attr/attributes.rb', line 51 def attributes attribute_names = self.class.attributes.map { |definition| definition.name.to_s } Hash[attribute_names.map { |key| [key, send(key)] }] end |
#initialize(*args) ⇒ Object
57 58 59 |
# File 'lib/active_attr/attributes.rb', line 57 def initialize(*args) @attributes ||= {} end |
#inspect ⇒ String
Returns the class name plus its attributes
69 70 71 72 73 74 75 76 77 |
# File 'lib/active_attr/attributes.rb', line 69 def inspect attribute_descriptions = self.class.attributes.sort.map do |attribute| "#{attribute.name.to_s}: #{read_attribute(attribute.name).inspect}" end.join(", ") attribute_descriptions = " " + attribute_descriptions unless attribute_descriptions.empty? "#<#{self.class.name}#{attribute_descriptions}>" end |
#read_attribute(name) ⇒ Object Also known as: [], attribute
Read a value from the model’s attributes. If the value does not exist it will return nil.
90 91 92 |
# File 'lib/active_attr/attributes.rb', line 90 def read_attribute(name) @attributes[name.to_s] end |
#write_attribute(name, value) ⇒ Object Also known as: []=, attribute=
Write a single attribute to the model’s attribute hash.
106 107 108 |
# File 'lib/active_attr/attributes.rb', line 106 def write_attribute(name, value) @attributes[name.to_s] = value end |