Sha256: 361c1032a7f0edeac6d9ccbbcb6407295d7c98664b15920074bafc2ed069c3d1

Contents?: true

Size: 1.01 KB

Versions: 4

Compression:

Stored size: 1.01 KB

Contents

require 'redis'

module Headsail
  class Redis
    attr_reader :connection

    def initialize(key_name)
      @key_name = key_name
      setup_connection
      setup_service
      setup_next_id
    end

    def add(data)
      @connection.incr(next_id_key)
      @connection.set(new_key, data)
    rescue
      setup_connection
    end

    private

    def new_key
      "#{@key_name}:#{next_id}"
    end

    def next_id
      @connection.get(next_id_key)
    end

    def next_id_key
      @next_id_key ||= "#{@key_name}:next_id"
    end

    def setup_connection
      @connection = ::Redis.new(url: ENV['REDIS_URL'])
      @connection.ping
    rescue
      Headsail.err("Failed to connect to Redis server at ENV 'REDIS_URL'.")
      exit 1
    end

    def setup_service
      return if @connection.exists(@key_name)
      @connection.set(@key_name, true)
      @connection.lpush('apis', @key_name)
    end

    def setup_next_id
      @connection.set(next_id_key, 0) unless @connection.exists(next_id_key)
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
headsail-0.1.15 lib/headsail/redis.rb
headsail-0.1.14 lib/headsail/redis.rb
headsail-0.1.13 lib/headsail/redis.rb
headsail-0.1.12 lib/headsail/redis.rb