我在使用模块化Sinatra应用程序helpers时遇到了一些麻烦。我有一个主控制器和一些继承它的人。因此/
映射到Root
,/auth
映射到Auth
等。
主要模块:
require 'sinatra/base'
# Lots of other requires
# Helper
module Utils
def test
puts "Test helper"
return 'test'
end
end
# Main app
class Application < Sinatra::Base
helpers Utils
# Lots of config
end
&#34;控制器&#34;继承Application
,如:
class Root < Application
get '/' do
puts Utils # Exists
puts Utils.test # Breaks
# view() Defined directly in `Application`, runs slim
view :index
end
end
这导致:
> 的NoMethodError私人方法`test&#39;要求Utils:Module
有点难过。有什么帮助吗?
答案 0 :(得分:2)
使用帮助程序模块可使其中的所有方法直接用于路径中的代码,而无需在模板名称前添加前缀。
你可以这样做:
get '/' do
puts test
# view() Defined directly in `Application`, runs slim
view :index
end
您获得private method `test' called for Utils:Module
而非undefined method `test' for Utils:Module
的原因是因为内核中已存在test
method,因此可在所有类中作为私有方法使用。
答案 1 :(得分:1)
好吧,看起来答案很简单。
通过helpers()
添加模块时,其方法只能method_name()
而不是ModuleName.method_name()
。
所以在这种情况下,在Root
和苗条模板中,我只需要调用test()