Rails + Redis订阅返回错误

时间:2013-08-19 11:51:15

标签: ruby-on-rails redis runtime-error

Rails 4 + Redis 3.0.4

当我尝试使用Redis订阅频道时:

$ rails c
irb(main):001:0> redis = Redis.new
=> #<Redis client v3.0.2 for redis://127.0.0.1:6379/0>
irb(main):002:0> redis.subscribe('test-channel')

它会抛出错误:

LocalJumpError: no block given (yield)
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis/subscribe.rb:52:in `initialize'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis/subscribe.rb:30:in `new'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis/subscribe.rb:30:in `subscription'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis/subscribe.rb:12:in `subscribe'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis.rb:2221:in `_subscription'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis.rb:1883:in `block in subscribe'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis.rb:36:in `block in synchronize'
from .rvm/rubies/ruby-1.9.3-p392/lib/ruby/1.9.1/monitor.rb:211:in `mon_synchronize'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis.rb:36:in `synchronize'
from .rvm/gems/ruby-1.9.3-p392/gems/redis-3.0.4/lib/redis.rb:1882:in `subscribe'
from (irb):2
from .rvm/gems/ruby-1.9.3-p392/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from .rvm/gems/ruby-1.9.3-p392/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from .rvm/gems/ruby-1.9.3-p392/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

我做错了什么?

1 个答案:

答案 0 :(得分:3)

狂野的猜测是订阅期待一个阻止。

所以传递一个块,提示:使用do end block。

像这样:

$redis.subscribe('rubyonrails', 'ruby-lang') do |on|   
  on.message do |channel, msg|
   data = JSON.parse(msg)
   puts "##{channel} - [#{data['user']}]: #{data['msg']}"   
  end 
end