私のモデル、Grape API、およびテストに 'lib/
'クラスまたはモジュールを含めるにはどうすればいいですか?例えば、私はクラスがあります。Rails 5アプリケーションでlibモジュールとクラスを正しくロードする方法
ROOT/lib/links/link.rb
module Links
class Link
...
end
end
をそして、私は私のUserモデルにそのクラスを含める(app/models/user.rb
)、ユーザーブドウのAPI(app/api/v1/users.rb
)、およびテストスイート(test/models/user_test.rb
とtest/api/v1/users/users_links_test.rb
)
例えば、私は
link = Links::Link.new(LINK_NAME, LINK_SITE)
が、私は得る:
3210
私はconfig/application.rb
にこれを追加しようとしました:
config.autoload_paths += Dir["#{Rails.root}/lib/**"]
require_relative 'boot'
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 "action_cable/engine"
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 ArbitraryAppName
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.
# Auto-load API and its subdirectories
config.paths.add 'app/api', glob: '**/*.rb'
config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
config.autoload_paths << "#{Rails.root}/lib"
# For Cross-Origin Resource Sharing (rack-cors)
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
が、それは動作しません。私は何が欠けていますか? lib
個のファイルを含めるにはどうすればいいですか?
EDIT: それは私が私がしなければそれはアクセスできる唯一の方法のように思える:
require "#{Rails.root}/lib/links/link"
は、より良い、より多くの従来の方法はありますか?
config.autoload_paths << whatever
は何もしていないようですが、別の問題があるようです。たとえば、puts ActiveSupport::Dependencies.autoload_paths
がrails console
にある場合、私の変更は表示されません。
アクセス中にエラーが発生しましたか?もしそうならログを追加してください – Zero
'app'ディレクトリの下に' lib'フォルダを移動することがよくあります –
あなたの問題はあなたの名前空間です、あなたは 'class Links :: Link 'with class link' –