Class: Moneta::Adapters::Sequel

Inherits:
Base
  • Object
show all
Defined in:
lib/moneta/adapters/sequel.rb

Overview

Sequel backend

Instance Method Summary collapse

Methods inherited from Base

#[], #[]=, #close, #decrement, #fetch

Methods included from Mixins::WithOptions

#expires, #prefix, #raw, #with

Constructor Details

#initialize(options = {}) ⇒ Sequel

Constructor

Parameters:

  • options (Hash) (defaults to: {})

Options Hash (options):

  • :db (String)

    Sequel database

  • :table (String/Symbol) — default: :moneta

    Table name

  • All (Object)

    other options passed to ‘Sequel#connect`

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
23
# File 'lib/moneta/adapters/sequel.rb', line 14

def initialize(options = {})
  raise ArgumentError, 'Option :db is required' unless db = options.delete(:db)
  table = options.delete(:table) || :moneta
  @db = ::Sequel.connect(db, options)
  @db.create_table?(table) do
    String :k, :null => false, :primary_key => true
    String :v
  end
  @table = @db[table]
end

Instance Method Details

#clear(options = {}) ⇒ Object



71
72
73
74
# File 'lib/moneta/adapters/sequel.rb', line 71

def clear(options = {})
  @table.delete
  self
end

#delete(key, options = {}) ⇒ Object



62
63
64
65
66
67
68
69
# File 'lib/moneta/adapters/sequel.rb', line 62

def delete(key, options = {})
  @db.transaction do
    if value = load(key, options)
      @table.filter(:k => key).delete
      value
    end
  end
end

#increment(key, amount = 1, options = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/moneta/adapters/sequel.rb', line 45

def increment(key, amount = 1, options = {})
  @db.transaction do
    locked_table = @table.for_update
    if record = locked_table[:k => key]
      value = record[:v]
      intvalue = value.to_i
      raise 'Tried to increment non integer value' unless value == nil || intvalue.to_s == value.to_s
      intvalue += amount
      locked_table.update(:k => key, :v => intvalue.to_s)
      intvalue
    else
      locked_table.insert(:k => key, :v => amount.to_s)
      amount
    end
  end
end

#key?(key, options = {}) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
# File 'lib/moneta/adapters/sequel.rb', line 25

def key?(key, options = {})
  @table[:k => key] != nil
end

#load(key, options = {}) ⇒ Object



29
30
31
32
# File 'lib/moneta/adapters/sequel.rb', line 29

def load(key, options = {})
  record = @table[:k => key]
  record && record[:v]
end

#store(key, value, options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/moneta/adapters/sequel.rb', line 34

def store(key, value, options = {})
  @db.transaction do
    if key?(key, options)
      @table.update(:k => key, :v => value)
    else
      @table.insert(:k => key, :v => value)
    end
    value
  end
end