Module: Valued::Mutable
- Defined in:
- lib/valued/mutable.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
- #==(other) ⇒ Object
- #eql?(other) ⇒ Boolean
- #hash ⇒ Object
- #initialize(attributes = {}) ⇒ Object
- #inspect ⇒ Object
- #to_h ⇒ Object
- #to_s ⇒ Object
- #update(new_attributes) ⇒ Object
Class Method Details
.define(*attrs, &block) ⇒ Object
13 14 15 16 17 18 19 20 21 22 |
# File 'lib/valued/mutable.rb', line 13 def self.define(*attrs, &block) klass = Class.new do include Valued::Mutable attributes(*attrs) end klass.class_eval(&block) if block_given? klass end |
.included(base) ⇒ Object
24 25 26 |
# File 'lib/valued/mutable.rb', line 24 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#==(other) ⇒ Object
48 49 50 51 52 |
# File 'lib/valued/mutable.rb', line 48 def ==(other) _attributes.all? do |attribute| other.respond_to?(attribute) && send(attribute) == other.send(attribute) end end |
#eql?(other) ⇒ Boolean
54 55 56 |
# File 'lib/valued/mutable.rb', line 54 def eql?(other) self.class == other.class && self == other end |
#hash ⇒ Object
58 59 60 |
# File 'lib/valued/mutable.rb', line 58 def hash (_attributes.map { |attribute| send(attribute) } + [self.class]).hash end |
#initialize(attributes = {}) ⇒ Object
28 29 30 31 32 33 34 |
# File 'lib/valued/mutable.rb', line 28 def initialize(attributes = {}) _attributes.each do |attribute| if attributes.key?(attribute) instance_variable_set("@#{attribute}", attributes.fetch(attribute)) end end end |
#inspect ⇒ Object
72 73 74 75 76 77 78 |
# File 'lib/valued/mutable.rb', line 72 def inspect inspected_attributes = _attributes .map { |attribute| "#{attribute}=#{send(attribute).inspect}" } .join(' ') "#<#{self.class} #{inspected_attributes}>" end |
#to_h ⇒ Object
62 63 64 65 66 |
# File 'lib/valued/mutable.rb', line 62 def to_h _attributes.each_with_object({}) do |attribute, hash| hash[attribute] = send(attribute) end end |
#to_s ⇒ Object
68 69 70 |
# File 'lib/valued/mutable.rb', line 68 def to_s inspect end |
#update(new_attributes) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/valued/mutable.rb', line 36 def update(new_attributes) self.class.new( _attributes.each_with_object({}) do |attribute, result| if new_attributes.key?(attribute) result[attribute] = new_attributes[attribute] else result[attribute] = self.send(attribute) end end ) end |