挂载式Rails引擎初始化器应放置在何处?
Hey there! Since you're coming from a strong PHP background and tackling your first Rails mountable engine, it makes total sense to ask about the right spot for setup code like global variables. Let's break this down clearly:
First option (and most straightforward): Just create the
config/initializers/directory yourself
Rails engines are designed to mirror the structure of a regular Rails app as much as possible—even if the directory isn't generated by default, Rails will automatically load any files placed inyour_engine/config/initializers/when the engine boots.For example, create a file like
your_engine/config/initializers/my_engine_setup.rband add your variables there. A quick note: while global variables (prefixed with$) work, it's more idiomatic in Ruby/Rails to use constants or structured config objects to avoid namespace pollution:# 用常量代替全局变量更符合Rails习惯 MY_ENGINE_DEFAULT_SETTINGS = { api_endpoint: "https://api.example.com/v1", max_retries: 3 } # 如果确实需要全局变量(不推荐,但可行) $my_engine_global_flag = trueSecond option: Embed config in your engine's core file
If you prefer to keep setup code tied directly to the engine's boot process, you can add initialization logic in your engine's main file (your_engine/lib/your_engine/engine.rb), inside theEngineclass block:module YourEngine class Engine < Rails::Engine # 在引擎初始化前执行配置 config.before_initialize do YOUR_ENGINE_CONFIG = { default_locale: :en } end end endThis works well if your config is tightly linked to how the engine starts up, and avoids needing extra directories.
Pro tip for flexible config (recommended for production-grade engines)
If you want the host app to be able to override your engine's default settings, use Rails' built-inconfigsystem instead of raw variables. In yourengine.rb:module YourEngine class Engine < Rails::Engine # 初始化一个有序配置对象 config.your_engine = ActiveSupport::OrderedOptions.new config.your_engine.api_key = "default_secret_key" config.your_engine.per_page_limit = 15 end endThen, in either your engine's initializer or the host app's config, you can override values like:
Rails.application.config.your_engine.api_key = "host_app_custom_key"This follows Rails' standard config pattern and makes your engine more adaptable.
To wrap it up: Creating the config/initializers/ directory yourself is totally safe and aligns with how you'd work in a regular Rails app—this is probably the easiest approach to start with as you learn the Rails ecosystem.
内容的提问来源于stack exchange,提问作者Jon Lawton

