Sinatra:把我的一些助手放在单独的文件夹中

时间:2014-02-05 00:06:46

标签: ruby sinatra

我有一个Sinatra应用程序,我有一些助手,他们有他们的文件夹(助手),我有website_helpers.rb等等。我想将一些帮助程序移动到helpers文件夹中的自己的文件夹中:拥有帮助程序/子帮助程序,因为我想要放在subhelpers文件夹中的文件与其他文件夹不同,因此为它们设置不同的文件夹是有意义的

我尝试将其添加到我的config.ru

Dir.glob('./helpers/subhelpers/*.rb').each { |file| require file }

然后在控制器中我有:

helpers MyHelperFromSubHelpers

但我收到错误uninitialized constant (NameError)

任何想法如何解决这个问题,以便有一个清晰的结构?

1 个答案:

答案 0 :(得分:1)

TBH,听起来你过度使用它,如果你想进入更像Java的每个命名空间必须是目录布局,那么Rails总是存在。除此之外,通常,单独文件中的帮助程序放在Sinatra命名空间中 - 请参阅http://www.sinatrarb.com/extensions.html#extending-the-request-context-with-sinatrahelpers

就个人而言,我把它们放进去了:

project-root/
  lib/
    sinatra/
      name-of-extension.rb

主要是因为如果扩展非常有用,我最终会想要在另一个项目中使用它,这是Sinatra gem的标准布局,这使得将它简单地提取到一个并且几乎没有任何变化在调用代码中。

Dir.glob will only return the file name and not the full path with each match,因此您需要添加路径:

Dir.glob('./helpers/subhelpers/*.rb').each do |file|
  require File.expand_path File.join( File.dirname(__FILE__), "./helpers/subhelpers/", file)
end

可能会修复它。