/
juggernaut.rb
49 lines (39 loc) · 906 Bytes
/
juggernaut.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
require "redis"
require "json"
# Attempt to provide Engine to Rails
require "juggernaut/rails/engine"
module Juggernaut
EVENTS = [
"juggernaut:subscribe",
"juggernaut:unsubscribe",
"juggernaut:custom"
]
def options
@options ||= {}
end
def options=(val)
@options = val
end
def url=(url)
options[:url] = url
end
def publish(channels, data, options = {})
message = ({:channels => Array(channels).uniq, :data => data}).merge(options)
redis.publish(key, message.to_json)
end
def subscribe
Redis.connect(options).subscribe(*EVENTS) do |on|
on.message do |type, msg|
yield(type.gsub(/^juggernaut:/, "").to_sym, JSON.parse(msg))
end
end
end
protected
def redis
@redis ||= Redis.connect(options)
end
def key(*args)
args.unshift(:juggernaut).join(":")
end
extend self
end