我正在尝试在Rails应用程序中编写一个小功能,该应用程序使用随机词gem生成随机名词,然后将其复数.我第一次访问开发中的页面时能够让它工作,但是我想让脚本在每次加载页面时再次运行.现在,后续页面加载(直到我反弹服务器)给我FiberError in WelcomeController#randomwords,fiber called across threads.我试图自己解决这个问题,但我对编程很陌生,并不太了解Fibers的工作原理.我尝试使用Queue,但无法弄清楚如何让它工作,再次因为我不完全理解这个类.我该如何解决这个具体问题?
资料来源:welcome_helper.rb
def random
noun = RandomWord.nouns.next.split('_').sample.pluralize
if noun.include? "_"
noun = noun.split("_").join.pluralize
else
noun.pluralize!
end
return noun
end
Run Code Online (Sandbox Code Playgroud) 我在Ruby On Rails应用程序中有一个方法,我想同时运行.该方法应该创建一个包含来自站点的报告的zip文件,其中zip中的每个文件都是PDF.从html到PDF的转换有点慢,因此需要多线程.
我想使用5个线程,所以我想我会在线程之间有一个共享的枚举器.每个线程都会从Enumerator中弹出一个值,然后运行do stuff.这就是我认为它会起作用的方式:
t = Zip::OutputStream::write_buffer do |z|
mutex = Mutex.new
gen = Enumerator.new{ |g|
Report.all.includes("employee" => ["boss", "client"], "projects" => {"project_owner" => ["project_team"]}).find_each do |report|
g.yield report
end
}
5.times.map {
Thread.new do
begin
loop do
mutex.synchronize do
@report = gen.next
end
title = @report.title + "_" + @report.id.to_s
title += ".pdf" unless title.end_with?(".pdf")
pdf = PDFKit.new(render_to_string(:template => partial_url, locals: {array: [@report]},
:layout => false)).to_pdf
mutex.synchronize do
z.put_next_entry(title)
z.write(pdf)
end
end
rescue StopIteration
# …Run Code Online (Sandbox Code Playgroud)