Class: SimpleCache::SqliteStore

Inherits:
SqliteDatabase show all
Defined in:
lib/simple_cache/sqlite_store.rb

Constant Summary collapse

Marshal =
::SimpleCache::Marshal
TABLE_NAME =
"simple_cache"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from SqliteDatabase

#ask, #exec

Constructor Details

#initialize(name) ⇒ SqliteStore

Returns a new instance of SqliteStore.



39
40
41
42
43
44
45
46
47
48
# File 'lib/simple_cache/sqlite_store.rb', line 39

def initialize(name) 
  @path = "#{SimpleCache::SqliteStore.base_dir}/#{name}/simple_cache.sqlite3" 
  super @path

  begin
    ask("SELECT 1 FROM #{TABLE_NAME} LIMIT 1")
  rescue SQLite3::SQLException
    ask("CREATE TABLE #{TABLE_NAME}(uid INTEGER PRIMARY KEY, value TEXT, ttl INTEGER NOT NULL)")
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



37
38
39
# File 'lib/simple_cache/sqlite_store.rb', line 37

def path
  @path
end

Class Method Details

.base_dirObject



29
30
31
32
33
34
35
# File 'lib/simple_cache/sqlite_store.rb', line 29

def self.base_dir
  if RUBY_PLATFORM.downcase.include?("darwin")
    "#{Dir.home}/Library/Caches/org.radiospiel.simple_cache"
  else
    "#{Dir.home}/.org.radiospiel.simple_cache"
  end
end

Instance Method Details

#clearObject



70
71
72
# File 'lib/simple_cache/sqlite_store.rb', line 70

def clear
  ask "DELETE FROM #{TABLE_NAME}"
end

#fetch(key, &block) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/simple_cache/sqlite_store.rb', line 50

def fetch(key, &block)
  value, ttl = ask("SELECT value, ttl FROM #{TABLE_NAME} WHERE uid=?", Marshal.uid(key))
  if ttl && (ttl == 0 || ttl > Time.now.to_i)
    Marshal.unmarshal(value) 
  elsif block_given?
    yield self, key
  end
end

#store(key, value, ttl = nil) ⇒ Object



59
60
61
62
63
64
65
66
67
68
# File 'lib/simple_cache/sqlite_store.rb', line 59

def store(key, value, ttl = nil)
  unless value.nil?
    ask("REPLACE INTO #{TABLE_NAME}(uid, value, ttl) VALUES(?,?,?)", 
          Marshal.uid(key), Marshal.marshal(value), ttl ? ttl + Time.now.to_i : 0)
  else
    ask("DELETE FROM #{TABLE_NAME} WHERE uid=?", Marshal.uid(key))
  end

  value
end