助手不使用模块化Sinatra应用程序

时间:2015-07-29 01:05:20

标签: ruby sinatra rack view-helpers

我在使用模块化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

有点难过。有什么帮助吗?

2 个答案:

答案 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()