Sinatra with a persistent variable

前提是你 提交于 2019-11-30 08:41:38

You could try:

configure do
  @@nokogiri_object = parse_xml
end

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.

The proposed solution gives a warning

warning: class variable access from toplevel

You can use a 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

Two options:

  • Save the parsed file to a new file and always read that one.

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

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

The 'data' value is the parsed file.

That way you parse just once time, sort of a cache.

  • Save the parsed file to a NoSQL database, for example redis.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!