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 gettring attributes hash for specific value object.
->(value) { value.respond_to?(:to_hash) ? value.to_hash : value }
Instance Method Summary collapse
-
#==(object) ⇒ boolean
Equalate two value objects.
-
#attributes ⇒ Hash
(also: #to_h, #to_hash)
Returns hash of object attributes.
-
#attributes=(attributes) ⇒ Hash
Mass-assignment attribut values.
-
#coerce(value, _options = {}) ⇒ Object
Sets new values and returns self.
-
#initialize(attrs = {}) ⇒ Object
Initialize instance object with specific attributes.
-
#inspect ⇒ String
Inspect instance object.
-
#reset_attribute(attribute) ⇒ Object
Reser specific attribute to defaul value.
Instance Method Details
#==(object) ⇒ boolean
Equalate two value objects
160 161 162 |
# File 'lib/shallow_attributes/instance_methods.rb', line 160 def ==(object) self.to_h == object.to_h end |
#attributes ⇒ Hash Also known as: to_h, to_hash
Returns hash of object attributes
56 57 58 59 60 61 62 63 |
# File 'lib/shallow_attributes/instance_methods.rb', line 56 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
Mass-assignment attribut values
88 89 90 91 |
# File 'lib/shallow_attributes/instance_methods.rb', line 88 def attributes=(attributes) @attributes.merge!(attributes) define_attributes end |
#coerce(value, _options = {}) ⇒ Object
Sets new values and returns self. Needs for embedded value.
138 139 140 141 |
# File 'lib/shallow_attributes/instance_methods.rb', line 138 def coerce(value, = {}) self.attributes = value self end |
#initialize(attrs = {}) ⇒ Object
Initialize instance object with specific attributes
32 33 34 35 36 37 38 39 40 |
# 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 end |
#inspect ⇒ String
Inspect instance object
178 179 180 |
# File 'lib/shallow_attributes/instance_methods.rb', line 178 def inspect "#<#{self.class}#{attributes.map{ |k, v| " #{k}=#{v.inspect}" }.join}>" end |
#reset_attribute(attribute) ⇒ Object
Reser specific attribute to defaul value.
110 111 112 |
# File 'lib/shallow_attributes/instance_methods.rb', line 110 def reset_attribute(attribute) instance_variable_set("@#{attribute}", default_value_for(attribute)) end |