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
- #hash ⇒ Object
- #initialize(args_hash) ⇒ Object
Class Method Details
.included(base) ⇒ Object
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/ruby-optics/record/record.rb', line 56 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.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?
42 43 44 45 46 47 48 |
# File 'lib/ruby-optics/record/record.rb', line 42 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
34 35 36 37 38 39 40 |
# File 'lib/ruby-optics/record/record.rb', line 34 def copy_with(args_hash) self.class.new( _current_attributes.merge( args_hash.reject { |k, v| !_current_attributes.keys.include?(k) } ) ) end |
#hash ⇒ Object
52 53 54 |
# File 'lib/ruby-optics/record/record.rb', line 52 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 |
# 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? if defined_attribute_params[:nullable] instance_variable_set( :"@#{attribute_name}", defined_attribute_params[:default] ) else raise ArgumentError.new( "Attribute with name #{attribute_name} is not provided" ) end else instance_variable_set( :"@#{attribute_name}", attribute_argument ) end end end |