Class: Lode::Tables::Abstract

Inherits:
Object
  • Object
show all
Defined in:
lib/lode/tables/abstract.rb

Overview

Provides an abstract table for subclassing.

Direct Known Subclasses

Dictionary, Value

Instance Method Summary collapse

Constructor Details

#initialize(store, key, setting: Setting.new) ⇒ Abstract

Returns a new instance of Abstract.



14
15
16
17
18
19
# File 'lib/lode/tables/abstract.rb', line 14

def initialize store, key, setting: Setting.new
  @store = store
  @key = key
  @setting = setting
  @records = store.fetch key, []
end

Instance Method Details

#allObject



23
# File 'lib/lode/tables/abstract.rb', line 23

def all = Success records.dup.freeze

#create(record, key: primary_key) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/lode/tables/abstract.rb', line 34

def create record, key: primary_key
  id = primary_id(record, key:)

  find(id, key:).bind { Failure "Record exists for #{key}: #{id}." }
                .or do |error|
                  return append record if error.include? "Unable to find"

                  Failure error
                end
end

#delete(id, key: primary_key) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/lode/tables/abstract.rb', line 55

def delete id, key: primary_key
  find(id, key:).fmap do |record|
    records.delete record
    store[key] = records
    record
  end
end

#find(id, key: primary_key) ⇒ Object



25
26
27
28
29
30
31
32
# File 'lib/lode/tables/abstract.rb', line 25

def find id, key: primary_key
  records.find { |record| primary_id(record, key:) == id }
         .then do |record|
           return Success record if record

           Failure "Unable to find #{key}: #{id.inspect}."
         end
end

#primary_keyObject



21
# File 'lib/lode/tables/abstract.rb', line 21

def primary_key = setting.primary_key

#update(change, key: primary_key) ⇒ Object



45
46
47
48
# File 'lib/lode/tables/abstract.rb', line 45

def update change, key: primary_key
  id = primary_id(change, key:)
  find(id, key:).bind { |existing| revise existing, change }
end

#upsert(record, key: primary_key) ⇒ Object



50
51
52
53
# File 'lib/lode/tables/abstract.rb', line 50

def upsert record, key: primary_key
  fail NoMethodError,
       "`#{self.class}##{__method__} #{method(__method__).parameters}` must be implemented."
end