Rails应用程序:模块中定义的自动加载类

时间:2017-05-16 10:23:57

标签: ruby-on-rails ruby include autoload

在Rails 5.0.1应用程序中我有文件 app / actions / frontend / cart / get_cart_items_summarized.rb

module Actions
  module Frontend
    module Cart
      class GetCartItemsSummarized
        #content here
      end
    end
  end
end

app / helpers / application_helper.rb 中,我称之为:

def get_cart_items
  #...
  items = Actions::Frontend::Cart::GetCartItemsSummarized.new.call
  #...
end

但我得到了:

未初始化的常量ApplicationHelper :: Actions

为什么呢?我应该如何使用这个课程?

由于

3 个答案:

答案 0 :(得分:3)

在rails / autoloading中,第一级目录(直接位于app下)不被视为名称的一部分。这样您的模型就可以只是User而不是Models::User等等。

我的解决方法是将所有自定义内容放入app/lib。这样,lib会占用非命名图层,而文件夹结构的其余部分将成为名称。在您的示例中,将文件放到

app/lib/actions/frontend/cart/get_cart_items_summarized.rb

当然,随意将“lib”替换为您想要的任何内容(例如“app / custom”)。这个名字没关系。

答案 1 :(得分:0)

使用完全限定名称:

::Actions::Frontend::Cart::GetCartItemsSummarized.new.call

或者只是坚持Rails常量查找(下面应该有效):

GetCartItemsSummarized.new.call

答案 2 :(得分:0)

在“ config / application.rb”中,将“ app”添加到自动加载路径,例如:

class Application < Rails::Application

  config.autoload_paths += Dir[Rails.root.join('app')]

end