Class: LedgerSync::Util::ReadOnlyObject

Inherits:
Object
  • Object
show all
Defined in:
lib/ledger_sync/util/read_only_object.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ ReadOnlyObject

Returns a new instance of ReadOnlyObject.



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/ledger_sync/util/read_only_object.rb', line 8

def initialize(args = {})
  @raw = args.with_indifferent_access

  self.class.attributes.except { |_k, _| e.to_sym == :raw }.each do |name, attr_settings|
    if attr_settings.key?(:default)
      instance_variable_set(
        "@#{name}",
        raw.fetch(name, attr_settings[:default])
      )
    else
      instance_variable_set(
        "@#{name}",
        raw.fetch(attr_settings.fetch(:source, name))
      )
    end
  end
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



6
7
8
# File 'lib/ledger_sync/util/read_only_object.rb', line 6

def raw
  @raw
end

Class Method Details

.attribute(name, **keywords) ⇒ Object



34
35
36
37
# File 'lib/ledger_sync/util/read_only_object.rb', line 34

def self.attribute(name, **keywords)
  attributes[name.to_sym] = keywords
  attr_reader name
end

.attributesObject



30
31
32
# File 'lib/ledger_sync/util/read_only_object.rb', line 30

def self.attributes
  @attributes ||= {}
end

.new_from_array(data) ⇒ Object



39
40
41
# File 'lib/ledger_sync/util/read_only_object.rb', line 39

def self.new_from_array(data)
  data.map { |e| new_from_hash(e) }
end

.new_from_hash(data) ⇒ Object



43
44
45
46
47
# File 'lib/ledger_sync/util/read_only_object.rb', line 43

def self.new_from_hash(data)
  new(
    data.symbolize_keys
  )
end

.source_keysObject



49
50
51
# File 'lib/ledger_sync/util/read_only_object.rb', line 49

def self.source_keys
  @source_keys ||= attributes.map { |k, v| v.fetch(:source, k).to_sym }
end

Instance Method Details

#==(other) ⇒ Object



26
27
28
# File 'lib/ledger_sync/util/read_only_object.rb', line 26

def ==(other)
  self.class.attributes.keys.all? { |name| send(name) == other.send(name) }
end