繁体   English   中英

在Rails应用程序的lib文件夹中定义的无法使用类

[英]Cant use class defined inside lib folder in rails app

我已经在我的Rails应用程序li​​b / 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

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

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

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

尝试包括lib所有文件夹:

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

我在调用我的lib文件夹中的模块时遇到了同样的问题。

甚至“ config.autoload_paths + =%W(#{config.root} / lib)”对我也不起作用。

经过一些研究,我发现除了要在文件中包含“ include MyModules”外,我还必须添加“ require'my_modules”。

所以你可以尝试要求它

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM