簡體   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