Module: Record
- Defined in:
- lib/ruby-optics/record/record.rb
Class Method Summary collapse
Instance Method Summary collapse
- #==(another_record) ⇒ Object (also: #eql?)
- #copy_with(args_hash) ⇒ Object
- #deconstruct_keys(keys) ⇒ Object
- #hash ⇒ Object
- #initialize(args_hash) ⇒ Object
Class Method Details
.included(base) ⇒ Object
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/ruby-optics/record/record.rb', line 63 def self.included(base) base.define_singleton_method(:attribute) do |attribute_name, nullable: false, default: nil| @_record_attributes_defs ||= [] @_record_attributes_defs << { attribute_name: attribute_name, nullable: nullable, default: default } base.send(:attr_reader, attribute_name) end base.instance_variable_set(:"@_lenses", {}) base.define_singleton_method(:lens) do |*attribute_names| head, *tail = attribute_names fst_lens = (@_lenses[head] ||= RecordLens.build(head)) return fst_lens if tail.empty? [fst_lens, *tail].reduce { |result_lens, attribute_name| result_lens.compose_lens(RecordLens.build(attribute_name)) } end end |
Instance Method Details
#==(another_record) ⇒ Object Also known as: eql?
43 44 45 46 47 48 49 |
# File 'lib/ruby-optics/record/record.rb', line 43 def ==(another_record) return false unless another_record.is_a?(self.class) another_record_attributes = another_record.send(:_current_attributes) _current_attributes == another_record_attributes end |
#copy_with(args_hash) ⇒ Object
35 36 37 38 39 40 41 |
# File 'lib/ruby-optics/record/record.rb', line 35 def copy_with(args_hash) self.class.new( _current_attributes.merge( args_hash.reject { |k, v| !_current_attributes.keys.include?(k) } ) ) end |
#deconstruct_keys(keys) ⇒ Object
58 59 60 |
# File 'lib/ruby-optics/record/record.rb', line 58 def deconstruct_keys(keys) _current_attributes end |
#hash ⇒ Object
53 54 55 |
# File 'lib/ruby-optics/record/record.rb', line 53 def hash [self.class, _current_attributes].hash end |
#initialize(args_hash) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/ruby-optics/record/record.rb', line 6 def initialize(args_hash) defined_attributes = self.class.instance_variable_get( :"@_record_attributes_defs" ) || [] defined_attributes.each do |defined_attribute_params| attribute_name = defined_attribute_params[:attribute_name] attribute_argument = args_hash[attribute_name] if attribute_argument.nil? default_value = defined_attribute_params[:default] if defined_attribute_params[:nullable] || default_value instance_variable_set( :"@#{attribute_name}", default_value ) else raise ArgumentError.new( "Attribute with name #{attribute_name} is not provided" ) end else instance_variable_set( :"@#{attribute_name}", attribute_argument ) end end end |