Module: ShallowAttributes::InstanceMethods Abstract
- Included in:
- ShallowAttributes
- Defined in:
- lib/shallow_attributes/instance_methods.rb
Overview
This module is abstract.
Abstract class for value classes. Provides some helper methods for working with attributes.
Constant Summary collapse
- TO_H_PROC =
Lambda object for getting attributes hash for a specific value object.
->(value) { value.respond_to?(:to_hash) ? value.to_hash : value }
Instance Method Summary collapse
-
#==(object) ⇒ boolean
Compare values of two objects.
-
#attributes ⇒ Hash
(also: #to_h, #to_hash)
Returns hash of object attributes.
-
#attributes=(attributes) ⇒ Hash
Attribute values mass-assignment.
-
#coerce(value, _options = {}) ⇒ Object
Sets new values and returns self.
-
#initialize(attrs = {}) ⇒ Object
Initialize an instance object with specific attributes.
-
#inspect ⇒ String
Inspect instance object.
-
#reset_attribute(attribute) ⇒ Object
Reset specific attribute to default value.
Instance Method Details
#==(object) ⇒ boolean
Compare values of two objects
163 164 165 |
# File 'lib/shallow_attributes/instance_methods.rb', line 163 def ==(object) self.to_h == object.to_h end |
#attributes ⇒ Hash Also known as: to_h, to_hash
Returns hash of object attributes
57 58 59 60 61 62 63 64 |
# File 'lib/shallow_attributes/instance_methods.rb', line 57 def attributes hash = {} @attributes.map do |key, value| hash[key] = value.is_a?(Array) ? value.map(&TO_H_PROC) : TO_H_PROC.call(value) end hash end |
#attributes=(attributes) ⇒ Hash
Attribute values mass-assignment
89 90 91 92 93 94 |
# File 'lib/shallow_attributes/instance_methods.rb', line 89 def attributes=(attributes) attributes.each_pair do |key, value| @attributes[key.to_sym] = value end define_attributes end |
#coerce(value, _options = {}) ⇒ Object
Sets new values and returns self. Needs for embedded value.
141 142 143 144 |
# File 'lib/shallow_attributes/instance_methods.rb', line 141 def coerce(value, = {}) self.attributes = value self end |
#initialize(attrs = {}) ⇒ Object
Initialize an instance object with specific attributes
32 33 34 35 36 37 38 39 40 41 |
# File 'lib/shallow_attributes/instance_methods.rb', line 32 def initialize(attrs = {}) @attributes = {} attrs.each_pair do |key, value| key = key.to_sym @attributes[key] = value if default_values.key?(key) end define_attributes define_default_attributes define_mandatory_attributes end |
#inspect ⇒ String
Inspect instance object
181 182 183 |
# File 'lib/shallow_attributes/instance_methods.rb', line 181 def inspect "#<#{self.class}#{attributes.map{ |k, v| " #{k}=#{v.inspect}" }.join}>" end |
#reset_attribute(attribute) ⇒ Object
Reset specific attribute to default value.
113 114 115 |
# File 'lib/shallow_attributes/instance_methods.rb', line 113 def reset_attribute(attribute) instance_variable_set("@#{attribute}", default_value_for(attribute)) end |