How to define a method to be called from the configure block of a modular sinatra application?

拜拜、爱过 提交于 2019-12-08 19:38:19

问题


I have a Sinatra app that, boiled down, looks basically like this:

class MyApp < Sinatra::Base

  configure :production do
    myConfigVar = read_config_file()
  end

  configure :development do
    myConfigVar = read_config_file()
  end

  def read_config_file()
    # interpret a config file
  end

end

Unfortunately, this doesn't work. I get undefined method read_config_file for MyApp:Class (NoMethodError)

The logic in read_config_file is non-trivial, so I don't want to duplicate in both. How can I define a method that can be called from both my configuration blocks? Or am I just approaching this problem in entirely the wrong way?


回答1:


It seems the configure block is executed as the file is read. You simply need to move the definition of your method before the configure block, and convert it to a class method:

class MyApp < Sinatra::Base

  def self.read_config_file()
    # interpret a config file
  end

  configure :production do
    myConfigVar = self.read_config_file()
  end

  configure :development do
    myConfigVar = self.read_config_file()
  end

end



回答2:


Your configure blocks are run when the class definition is evaluated. So, the context is the class itself, not an instance. So, you need a class method, not an instance method.

def self.read_config_file

That should work. Haven't tested though. ;)



来源:https://stackoverflow.com/questions/10021869/how-to-define-a-method-to-be-called-from-the-configure-block-of-a-modular-sinatr

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