带有持久变量的 Sinatra [英] Sinatra with a persistent variable
问题描述
我的 sinatra 应用程序必须解析一个 ~60MB 的 XML 文件.这个文件几乎不会改变:在每晚的 cron 作业中,它被另一个覆盖.
My sinatra app has to parse a ~60MB XML-file. This file hardly ever changes: on a nightly cron job, It is overwritten with another one.
是否有技巧或方法可以将解析后的文件作为变量保存在内存中,以便我可以在传入请求中读取它,但不必为每个传入请求一遍又一遍地解析它?
Are there tricks or ways to keep the parsed file in memory, as a variable, so that I can read from it on incoming requests, but not have to parse it over and over for each incoming request?
一些伪代码来说明我的问题.
Some Pseudocode to illustrate my problem.
get '/projects/:id'
return @nokigiri_object.search("//projects/project[@id=#{params[:id]}]/name/text()")
end
post '/projects/update'
if params[:token] == "s3cr3t"
@nokogiri_object = reparse_the_xml_file
end
end
我需要知道的是如何创建这样一个@nokogiri_object,以便在 Sinatra 运行时它仍然存在.这可能吗?或者我需要一些存储空间?
What I need to know, is how to create such a @nokogiri_object so that it persists when Sinatra runs. Is that possible at all? Or do I need some storage for that?
推荐答案
你可以试试:
configure do
@@nokogiri_object = parse_xml
end
然后 @@nokogiri_object
将在您的请求方法中可用.它是一个类变量而不是一个实例变量,但应该做你想做的.
Then @@nokogiri_object
will be available in your request methods. It's a class variable rather than an instance variable, but should do what you want.
这篇关于带有持久变量的 Sinatra的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!