Sha256: 8190f647d76012ecf5addfb51ad97753904bc41f8af2717bb3318c45db26153f

Contents?: true

Size: 1.25 KB

Versions: 16

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Rodbot
  class Db

    # Database adapter for Redis
    #
    # All keys are implicitly nested inside the "rodbot:..." namespace to allow
    # using one and the same Redis db for more than just Rodbot.
    #
    # @example Enable in config/rodbot.rb
    #   db 'redis://localhost:6379/10'
    module Redis
      include Rodbot::Memoize

      def self.extended(*)
        require 'redis'
      end

      def set(*key, expires_in: nil, &block)
        block.call((get(*key) unless block.arity.zero?)).tap do |value|
          db.set(skey(*key), serialize(value), ex: expires_in)
        end
      end

      def get(*key)
        deserialize(db.get(skey(*key)))
      end

      def delete(*key)
        get(*key).tap do
          db.del(skey(*key))
        end
      end

      def scan(*key)
        cursor, result = 0, []
        loop do
          cursor, keys = db.scan(cursor, match: skey(*key))
          result.append(*keys)
          break result if cursor == '0'
        end.map { _1[7..] }
      end

      def flush
        db.flushdb
        self
      end

      private

      memoize def db
        ::Redis.new(url: url)
      end

      def skey(*key)
        key.prepend('rodbot').join(':')
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
rodbot-0.5.1 lib/rodbot/db/redis.rb
rodbot-0.5.0 lib/rodbot/db/redis.rb
rodbot-0.4.5 lib/rodbot/db/redis.rb
rodbot-0.4.4 lib/rodbot/db/redis.rb
rodbot-0.4.3 lib/rodbot/db/redis.rb
rodbot-0.4.2 lib/rodbot/db/redis.rb
rodbot-0.4.1 lib/rodbot/db/redis.rb
rodbot-0.4.0 lib/rodbot/db/redis.rb
rodbot-0.3.4 lib/rodbot/db/redis.rb
rodbot-0.3.3 lib/rodbot/db/redis.rb
rodbot-0.3.2 lib/rodbot/db/redis.rb
rodbot-0.3.1 lib/rodbot/db/redis.rb
rodbot-0.3.0 lib/rodbot/db/redis.rb
rodbot-0.2.0 lib/rodbot/db/redis.rb
rodbot-0.1.1 lib/rodbot/db/redis.rb
rodbot-0.1.0 lib/rodbot/db/redis.rb