Sha256: 26b6fd0c724145927c37a6433bbbda67f4e672194e44d2870f382f2977908faa
Contents?: true
Size: 1.1 KB
Versions: 2
Compression:
Stored size: 1.1 KB
Contents
# -- The settings table; has support for ttl etc. --------------------------- require "json" class MicroSql::KeyValueTable < MicroSql::Table def initialize(db, table_name = "settings") super db, "CREATE TABLE #{table_name}(uid TEXT PRIMARY KEY, value TEXT, ttl BIGINT)" end def [](key) value, ttl = db.ask("SELECT value, ttl FROM #{table_name} WHERE uid=?", key) decode(value) if !ttl || ttl < Time.now.to_i end def cached(key, ttl = nil, &block) self[key] || update(key, yield, ttl) end def update(key, value, ttl = nil) if value encoded = encode(value) ttl += Time.now.to_i if ttl affected = @db.ask("UPDATE #{table_name} SET value=?, ttl=? WHERE uid=?", encoded, ttl, key) if affected == 0 @db.ask("INSERT INTO #{table_name}(value, ttl, uid) VALUES(?,?,?)", encoded, ttl, key) end else @db.ask("DELETE FROM #{table_name} WHERE uid=?", key) end value end alias :[]= :update private def decode(io) return unless io JSON.parse("[#{io}]").first end def encode(value) value && value.to_json end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
micro_sql-0.3.1 | lib/micro_sql/key_value_table.rb |
micro_sql-0.3.0 | lib/micro_sql/key_value_table.rb |