Module: Backrub

Extended by:
Backrub
Included in:
Backrub
Defined in:
lib/backrub.rb

Constant Summary collapse

VERSION =
"1.0.0"
DEFAULT_BACKLOG_SIZE =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#backlog_sizeObject



60
61
62
# File 'lib/backrub.rb', line 60

def backlog_size
  @backlog_size || DEFAULT_BACKLOG_SIZE
end

#redisObject



16
17
18
# File 'lib/backrub.rb', line 16

def redis
  @redis ||= new_redis
end

#redis_configObject



12
13
14
# File 'lib/backrub.rb', line 12

def redis_config
  @redis_config ||= {}
end

Instance Method Details

#publish(channel, message) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/backrub.rb', line 52

def publish(channel, message)
  redis.multi do
    redis.publish(channel, message)
    redis.lpush(channel, message)
    redis.ltrim(channel, 0, backlog_size - 1)
  end
end

#subscribe(*channels) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/backrub.rb', line 20

def subscribe(*channels)
  raise ArgumentError.new "You have to pass at least one channel" if channels.count.zero?

  if channels.count == 1 && channels.first.is_a?(Hash)
    hash = channels.first

    hash.each do |channel, offset|
      if offset > 0
        backlog = redis.lrange(channel, 0, offset - 1)

        backlog.reverse_each do |message|
          yield channel.to_s, message
        end
      end
    end

    channels = hash.keys
  end

  begin
    # Open a new connection because the connection blocks, causing other threads to be unable to use it
    local_redis = new_redis
    local_redis.subscribe(*channels) do |on|
      on.message do |channel, message|
        yield channel, message
      end
    end
  ensure
    local_redis.quit
  end
end