由Rufus Scheduler触发的Sinatra事件

时间:2017-04-18 15:36:50

标签: ruby variables scope sinatra rufus-scheduler

尝试从Rufus Scheduler中发送事件会导致此错误:

{ 70231586340180 rufus-scheduler intercepted an error:
  70231586340180   job:
  70231586340180     Rufus::Scheduler::IntervalJob "2s" {}
  70231586340180   error:
  70231586340180     70231586340180
  70231586340180     NameError
  70231586340180     undefined local variable or method `connections' for main:Object
  70231586340180       picture-frame.rb:31:in `send_event'
  70231586340180       picture-frame.rb:24:in `block in <main>'
...

似乎我无法从Rufus Job中访问connections。我怎样才能解决这个问题?这是我的代码:

require 'sinatra'
require 'rufus-scheduler'
require 'json'


set :server, :thin
connections = []
scheduler = Rufus::Scheduler.new


get '/' do
    erb :index
end

get '/events', provides: 'text/event-stream' do
  stream :keep_open do |out|
    connections << out
    connections.reject!(&:closed?)
  end
end

scheduler.interval '2s' do
    random = (0...8).map { (65 + rand(26)).chr }.join
    send_event('random', { random: random })
end

def send_event(id, body)
  body[:id] = id

  event = "data: #{body.to_json}"
  connections.each { |out| out << event }
end

1 个答案:

答案 0 :(得分:2)

这是一个带有全局变量的版本。

  

如何在Sinatra应用程序的上下文中添加连接?

很抱歉,这个$connections$scheduler位于整个Ruby流程的上下文中,但是对于有限的脚本/服务,没关系。

require 'sinatra'
require 'rufus-scheduler'
require 'json'


set :server, :thin
$connections = []
$scheduler = Rufus::Scheduler.new


get '/' do
    erb :index
end

get '/events', provides: 'text/event-stream' do
  stream :keep_open do |out|
    $connections << out
    $connections.reject!(&:closed?)
  end
end

def send_event(id, body)

  body[:id] = id

  event = "data: #{body.to_json}"
  $connections.each { |out| out << event }
end

$scheduler.interval '2s' do

  random = (0...8).map { (65 + rand(26)).chr }.join
  send_event('random', { random: random })
end