Sinatra with constant variable

My sinatra application should parse an ~ 60 MB XML file. This file almost never changes: at night, cron overwrites it with another.

Are there any tricks or ways to store the analyzed file in memory as a variable so that I can read from it by incoming requests, but do not need to parse it again and again for each incoming request?

Some pseudo codes 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 

I need to know how to create such an @nokogiri_object so that it is saved when Sinatra starts. Is this even possible? Or do I need some storage for this?

+12
scope ruby sinatra
Jun 22 '11 at 17:05
source share
3 answers

You can try:

 configure do @@nokogiri_object = parse_xml end 

Then @@nokogiri_object will be available in your request methods. This is a class variable, not an instance variable, but should do what you want.

+9
Jun 22 '11 at 17:33
source share
— -

The proposed solution gives a warning

warning: accessing a class variable from toplevel

You can use the class method to access the class variable and the warning will disappear

 require 'sinatra' class Cache @@count = 0 def self.init() @@count = 0 end def self.increment() @@count = @@count + 1 end def self.count() return @@count end end configure do Cache::init() end get '/' do if Cache::count() == 0 Cache::increment() "First time" else Cache::increment() "Another time #{Cache::count()}" end end 
+8
Jan 29 '14 at 22:31
source share

Two options:

  • Save the analyzed file in a new file and always read it.

You can save in a file - serialize - a hash with two keys: last-modified and data.

The "last-modified" value is the date, and you check every request if that day is today. If it is not today, then a new file is downloaded, analyzed and saved with today's date.

The value "data" is the parsed file.

This way you analyze only once, the type of cache.

  • Save the parsed file to a NoSQL database, such as redis.
0
Jun 22 '11 at 17:12
source share



All Articles