【问题标题】:Helpers not working with a modular Sinatra app助手不使用模块化 Sinatra 应用程序
【发布时间】:2015-07-29 01:05:19
【问题描述】:

我在让helpers 使用模块化 Sinatra 应用程序时遇到了一些麻烦。我有一个主控制器和一堆从它继承的其他控制器。所以/ 映射到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

“控制器”继承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 at /

为 Utils:Module 调用私有方法 `test'

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

【问题讨论】:

    标签: ruby sinatra rack view-helpers


    【解决方案1】:

    使用 helpers 模块可以让路由中的代码直接使用其中的所有方法,而无需在其前面加上模块名称。

    你可以这样做:

    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,因此它可以作为所有类的私有方法使用。

    【讨论】:

    • 有没有办法实现与此相反的(对于命名空间问题),即定义一个模块,以便可以使用模块名称调用其辅助方法并且仍然可以访问请求context 和 Sinatra 的其他助手(例如session)?在 OP 的示例中,能够从路由调用Utils.test,而不是普通的test()
    • @ArmanH 我看到了你的问题和关于这个的赏金。我认为没有一种干净的方法可以做你想做的事。通过将名称与模块一起使用,该方法将在不同的上下文中运行,但您需要它在相同的上下文中才能获取其他帮助程序。 (当然,这是 Ruby,可能有一些 hacky 方法可以让它工作)。
    【解决方案2】:

    嗯,看起来答案很简单。

    当通过helpers() 包含一个模块时,它的方法可以简单地作为method_name() 而不是ModuleName.method_name()

    所以在这种情况下,无论是在 Root 和 slim 模板中,我需要做的就是调用 test()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2013-08-23
      • 2014-05-23
      • 1970-01-01
      • 2014-09-27
      相关资源
      最近更新 更多