我如何在我的模型、Grape API和测试中包含一个'lib/'类或模块呢?例如,我有一个类:
ROOT/lib/links/link.rb
但是它不起作用。我漏掉了什么?我应该如何包含
编辑: 看起来唯一能访问它的方法是这样做:
还有另一个问题,添加
ROOT/lib/links/link.rb
module Links
class Link
...
end
end
我希望在我的用户模型 (app/models/user.rb
)、用户Grape 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)
但我得到了:
uninitialized constant API::V1::Users::APITest::Links
我已经尝试将以下内容添加到我的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
文件并如何调用这些类?编辑: 看起来唯一能访问它的方法是这样做:
require "#{Rails.root}/lib/links/link"
有更好、更常规的方法吗?还有另一个问题,添加
config.autoload_paths << whatever
似乎没有任何作用。例如,当我在rails console
中运行puts ActiveSupport::Dependencies.autoload_paths
时,我的更改不会出现。
lib
文件夹移动到app
目录下。 - Andrey Deinekoclass Links::Link
替换为class Link
。 - Paul Hofferapp/lib/links/link.rb
下面,但仍然出现了uninitialized constant API::V1::Users::APITest::Links
错误,使用link = Links::Link.new(LINK_NAME, LINK_SITE)
。 - the_basterd