无法在rails app中使用lib文件夹中定义的类

时间:2016-04-29 13:09:02

标签: ruby-on-rails class load

我在我的rails app lib / pundit / current_context.rb中的lib文件夹中创建了一个类:

class CurrentContext
  attr_reader :user, :account_asso

  def initialize(user, account_asso)
    @user = user
    @account_asso = account_asso
  end
end

然后在我的base_controller中调用该类:

  def pundit_user
    CurrentContext.new(current_user, account_asso)
  end

我总是得到:

NameError - uninitialized constant Api::V1::BaseController::CurrentContext:

我认为可能是因为我没有在lib中加载文件? 所以我在config / application.rb文件中添加了config.autoload_paths << Rails.root.join('lib')

require File.expand_path('../boot', __FILE__)

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module QuickBedApi
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
    # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
    # config.time_zone = 'Central Time (US & Canada)'

    # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
    # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
    # config.i18n.default_locale = :de
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
    # Do not swallow errors in after_commit/after_rollback callbacks.
    config.active_record.raise_in_transactional_callbacks = true
    config.autoload_paths << Rails.root.join('lib')
  end

end

不幸的是我仍然收到错误。我该如何解决?

3 个答案:

答案 0 :(得分:3)

自动包含lib /目录的所有子目录,

config.autoload_paths += Dir["#{config.root}/lib/**/"]

答案 1 :(得分:0)

尝试包含lib的所有文件夹:

config.autoload_paths.concat `find -type d`.split($/).map {|f| Rails.root.join(f) }

答案 2 :(得分:0)

我有同样的问题来调用我的lib文件夹的模块。

即使是“config.autoload_paths + =%W(#{config.root} / lib)”也不适用于我。

经过一些研究后,我发现除了我的文件中的“包含MyModules”之外,我还必须添加“require'my_modules'”以便能够调用它。

所以你可以尝试要求它