Class: Lux::Cache::SqliteServer

Inherits:
Object
  • Object
show all
Defined in:
lib/lux/cache/lib/sqlite_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(path = nil) ⇒ SqliteServer

Returns a new instance of SqliteServer.



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/lux/cache/lib/sqlite_server.rb', line 4

def initialize path = nil
  file = Pathname.new path || './tmp/lux_cache.sqlite'
  # file.delete if file.exist?
  @db = Sequel.sqlite file.to_s

  unless @db.tables.include?(:cache)
    @db.create_table :cache do
      primary_key :id
      datetime :valid_to
      string   :key
      blob     :value
    end

    @db.add_index :cache, :key
  end

  @cache = @db[:cache]
end

Instance Method Details

#clearObject



57
58
59
# File 'lib/lux/cache/lib/sqlite_server.rb', line 57

def clear
  @cache.truncate
end

#delete(key) ⇒ Object



47
48
49
50
# File 'lib/lux/cache/lib/sqlite_server.rb', line 47

def delete key
  @cache.where(key: key).delete
  nil
end

#fetch(key, ttl = nil) ⇒ Object



43
44
45
# File 'lib/lux/cache/lib/sqlite_server.rb', line 43

def fetch key, ttl = nil
  self.get(key) || self.set(key, yield, ttl)
end

#get(key) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/lux/cache/lib/sqlite_server.rb', line 31

def get key
  row = @cache.where(key: key).to_a.first

  if row
    if row[:valid_to] >= Time.now
      Marshal.load Base64.decode64 row[:value]
    else
      self.delete key
    end
  end
end

#get_multi(*args) ⇒ Object



52
53
54
55
# File 'lib/lux/cache/lib/sqlite_server.rb', line 52

def get_multi *args
  data = @cache.where(key: args).all
  data.inject({}) {|t, el| t[el[:key]] = Marshal.load Base64.decode64(el[:value]); t}
end

#set(key, data, ttl = nil) ⇒ Object



23
24
25
26
27
28
29
# File 'lib/lux/cache/lib/sqlite_server.rb', line 23

def set key, data, ttl = nil
  self.delete key
  ttl ||= 60 * 60 * 24
  value = Base64.encode64 Marshal.dump(data)
  @cache.insert(key: key, value: value, valid_to: Time.now + ttl.seconds)
  data
end