gpt4 book ai didi

ruby - Rufus Scheduler 触发的 Sinatra 事件

转载 作者:数据小太阳 更新时间:2023-10-29 08:58:21 27 4
gpt4 key购买 nike

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

{ 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

最佳答案

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

How do I put connections in the context of my Sinatra application?

抱歉,有了这个 $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

关于ruby - Rufus Scheduler 触发的 Sinatra 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43476509/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com