从Gem添加到Rails autoload_path

pho*_*oet 8 gem load-path ruby-on-rails-3

我想编写一个将app/services目录添加到Rails应用程序的gem .

由于我想从Gem中添加它,我想出了这个解决方案:

class Railtie < ::Rails::Railtie
  config.after_initialize do |app|
    ::Rails.logger.info "adding #{ActiveService::Configuration.path} to autoload_path"
    app.config.autoload_paths = [ActiveService::Configuration.path] + app.config.autoload_paths
  end
end
Run Code Online (Sandbox Code Playgroud)

问题是这config.autoload_path是一个冻结的数组,因此修改它似乎不是一个好主意.

有关如何以更好的方式实现这一目标的任何建议?

rub*_*iii 11

config.autoload_paths:set_autload_paths初始化器内被冻结.将数组传递给ActiveSupport::Dependencies.autoload_paths,因此修改原始数组没有多大意义.因此它被冷冻了.

你应该能够在传递和冻结之前进入:before => :set_autoload_paths并扩展config.autoload_paths:

class Railtie < ::Rails::Railtie
  initializer 'activeservice.autoload', :before => :set_autoload_paths do |app|
    app.config.autoload_paths << ActiveService::Configuration.path
  end
end
Run Code Online (Sandbox Code Playgroud)

有关初始化程序钩子的文档可以在guides.rubyonrails.org/initialization.html找到