Module: Backrub

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

Constant Summary collapse

VERSION =
"0.0.1"
DEFAULT_BACKLOG_SIZE =
100

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#backlog_sizeObject



53
54
55
# File 'lib/backrub.rb', line 53

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



45
46
47
48
49
50
51
# File 'lib/backrub.rb', line 45

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
# 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)
    channels.first.each do |channel, offset|
      redis.lrange(channel, 0, offset - 1).reverse_each do |message|
        yield channel, message
      end
    end
    channels = channels.first.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