我有一个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
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用.我明白了undefined method read_config_file for MyApp:Class (NoMethodError)
逻辑read_config_file是非平凡的,所以我不想在两者中都重复.如何定义可以从我的配置块调用的方法?或者我只是以完全错误的方式解决这个问题?
看起来configure块在读取文件时执行.您只需要在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
Run Code Online (Sandbox Code Playgroud)