Sha256: 1af197a7b7c7ca930f7fef6156ee2eb7ebacef9f318c15029dfd503923219d4d

Contents?: true

Size: 1004 Bytes

Versions: 1

Compression:

Stored size: 1004 Bytes

Contents

require 'msgpack'
require 'speed_gun/store'

class SpeedGun::Store::RedisStore < SpeedGun::Store
  DEFAULT_PREFIX = 'speed-gun'
  DEFAULT_EXPIRES_IN_SECONDS = 60 * 60 * 24

  def initialize(options = {})
    @prefix = options[:prefix] || DEFAULT_PREFIX
    @client = options[:client] || default_client(options)
    @expires = (options[:expires] || DEFAULT_EXPIRES_IN_SECONDS).to_i
  end

  def save(object)
    @client.setex(
      key(object.class, object.id),
      @expires,
      object.to_hash.to_msgpack
    )
  end

  def load(klass, id)
    klass.from_hash(id, MessagePack.unpack(@client.get(key(klass, id))))
  end

  private

  def key(klass, id)
    klass_name = klass.name
    klass_name.gsub!(/([a-z])([A-Z])/) { |c| "#{$1.to_s}_#{$2.to_s.downcase}" }
    klass_name.gsub!(/[A-Z]/) { |c| "#{c.downcase}" }
    klass_name.gsub!('::', '-')

    [@prefix, klass_name, id].join('-')
  end

  def default_client(options)
    require 'redis' unless defined? Redis
    Redis.new(options)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
speed_gun-1.0.0.rc1 lib/speed_gun/store/redis_store.rb