如何定义从模块化sinatra应用程序的配置块调用的方法?

我有一个Sinatra应用程序,煮沸了,看起来基本上是这样的:

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 

不幸的是,这不起作用。 我得到undefined method read_config_file for MyApp:Class (NoMethodError)

read_config_file的逻辑非常重要,因此我不想在两者中都重复。 如何定义可以从我的配置块调用的方法? 或者我只是以完全错误的方式解决这个问题?

看起来configure块是在读取文件时执行的。 您只需在配置块之前移动方法的定义,并将其转换为类方法:

 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 

在计算类定义时,将运行配置块。 因此,上下文是类本身,而不是实例。 因此,您需要一个类方法,而不是实例方法。

 def self.read_config_file 

这应该工作。 虽然没有测试过。 ;)