9

I want to write a gem that adds a app/services directory to a Rails application.

Since I want to add it from within the Gem i came up with this solution:

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

The problem is that config.autoload_path is a frozen array, so that modifing it seems not to be a good idea.

Any suggestions of how this could be achieved in a better way?

4

2 に答える 2

12

config.autoload_paths:set_autload_paths初期化子内で凍結されています。Array は に渡されるActiveSupport::Dependencies.autoload_pathsため、元の Array を変更してもあまり意味がありません。したがって、凍結されています。

渡されて凍結される前に、フックし: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

初期化フックに関するドキュメントは、guides.rubyonrails.org/initialization.htmlにあります。

于 2011-06-18T08:56:29.453 に答える
4

まず、Rails 3.0 以降、app/* の下のすべてのディレクトリは既にロード パスにあります。いずれにせよ、そうしたい場合は、代わりにパス API を使用する必要があります。Rails ソースコードの例:

https://github.com/rails/rails/blob/master/railties/lib/rails/engine/configuration.rb#L42

于 2011-06-20T22:16:38.550 に答える