Class: Rails::Engine

Inherits:
Railtie show all
Defined in:
railties/lib/rails/engine.rb,
railties/lib/rails/engine/railties.rb,
railties/lib/rails/engine/configuration.rb

Overview

Rails::Engine allows you to wrap a specific Rails application and share it across different applications. Since Rails 3.0, every Rails::Application is nothing more than an engine, allowing you to share it very easily.

Any Rails::Engine is also a Rails::Railtie, so the same methods (like rake_tasks and generators) and configuration available in the latter can also be used in the former.

Creating an Engine

In Rails versions prior to 3.0, your gems automatically behaved as engines, however, this coupled Rails to Rubygems. Since Rails 3.0, if you want a gem to automatically behave as an engine, you have to specify an Engine for it somewhere inside your plugin's lib folder (similar to how we specify a Railtie):

# lib/my_engine.rb
module MyEngine
  class Engine < Rails::Engine
  end
end

Then ensure that this file is loaded at the top of your config/application.rb (or in your Gemfile) and it will automatically load models, controllers and helpers inside app, load routes at config/routes.rb, load locales at config/locales/*, and load tasks at lib/tasks/*.

Configuration

Besides the Railtie configuration which is shared across the application, in a Rails::Engine you can access autoload_paths, eager_load_paths and autoload_once_paths, which, differently from a Railtie, are scoped to the current engine.

Example:

class MyEngine < Rails::Engine
  # Add a load path for this specific Engine
  config.autoload_paths << File.expand_path("../lib/some/path", __FILE__)

  initializer "my_engine.add_middleware" do |app|
    app.middleware.use MyEngine::Middleware
  end
end

Generators

You can set up generators for engines with config.generators method:

class MyEngine < Rails::Engine
  config.generators do |g|
    g.orm             :active_record
    g.template_engine :erb
    g.test_framework  :test_unit
  end
end

You can also set generators for an application by using config.app_generators:

class MyEngine < Rails::Engine
  # note that you can also pass block to app_generators in the same way you
  # can pass it to generators method
  config.app_generators.orm :datamapper
end

Paths

Since Rails 3.0, both your application and engines do not have hardcoded paths. This means that you are not required to place your controllers at app/controllers, but in any place which you find convenient.

For example, let's suppose you want to place your controllers in lib/controllers. All you would need to do is:

class MyEngine < Rails::Engine
  paths["app/controllers"] = "lib/controllers"
end

You can also have your controllers loaded from both app/controllers and lib/controllers:

class MyEngine < Rails::Engine
  paths["app/controllers"] << "lib/controllers"
end

The available paths in an engine are:

class MyEngine < Rails::Engine
  paths["app"]                 #=> ["app"]
  paths["app/controllers"]     #=> ["app/controllers"]
  paths["app/helpers"]         #=> ["app/helpers"]
  paths["app/models"]          #=> ["app/models"]
  paths["app/views"]           #=> ["app/views"]
  paths["lib"]                 #=> ["lib"]
  paths["lib/tasks"]           #=> ["lib/tasks"]
  paths["config"]              #=> ["config"]
  paths["config/initializers"] #=> ["config/initializers"]
  paths["config/locales"]      #=> ["config/locales"]
  paths["config/routes"]       #=> ["config/routes.rb"]
end

Your Application class adds a couple more paths to this set. And as in your Application,all folders under app are automatically added to the load path. So if you have app/observers, it's added by default.

Endpoint

An engine can be also a rack application. It can be useful if you have a rack application that you would like to wrap with Engine and provide some of the Engine's features.

To do that, use the endpoint method:

module MyEngine
  class Engine < Rails::Engine
    endpoint MyRackApplication
  end
end

Now you can mount your engine in application's routes just like that:

MyRailsApp::Application.routes.draw do
  mount MyEngine::Engine => "/engine"
end

Middleware stack

As an engine can now be rack endpoint, it can also have a middleware stack. The usage is exactly the same as in Application:

module MyEngine
  class Engine < Rails::Engine
    middleware.use SomeMiddleware
  end
end

Routes

If you don't specify an endpoint, routes will be used as the default endpoint. You can use them just like you use an application's routes:

# ENGINE/config/routes.rb
MyEngine::Engine.routes.draw do
  match "/" => "posts#index"
end

Mount priority

Note that now there can be more than one router in your application, and it's better to avoid passing requests through many routers. Consider this situation:

MyRailsApp::Application.routes.draw do
  mount MyEngine::Engine => "/blog"
  match "/blog/omg" => "main#omg"
end

MyEngine is mounted at /blog, and /blog/omg points to application's controller. In such a situation, requests to /blog/omg will go through MyEngine, and if there is no such route in Engine's routes, it will be dispatched to main#omg. It's much better to swap that:

MyRailsApp::Application.routes.draw do
  match "/blog/omg" => "main#omg"
  mount MyEngine::Engine => "/blog"
end

Now, Engine will get only requests that were not handled by Application.

Asset path

When you use Engine with its own public directory, you will probably want to copy or symlink it to application's public directory. To simplify generating paths for assets, you can set asset_path for an engine:

module MyEngine
  class Engine < Rails::Engine
    config.asset_path = "/my_engine/%s"
  end
end

With such a config, asset paths will be automatically modified inside Engine:

image_path("foo.jpg") #=> "/my_engine/images/foo.jpg"

Serving static files

By default, Rails uses ActionDispatch::Static to serve static files in development mode. This is ok while you develop your application, but when you want to deploy it, assets from an engine will not be served by default. You should choose one of the two following strategies:

  • enable serving static files by setting config.serve_static_assets to true

  • copy engine's public files to application's public folder with rake ENGINE_NAME:install:assets, for example rake my_engine:install:assets

Engine name

There are some places where an Engine's name is used:

  • routes: when you mount an Engine with mount(MyEngine::Engine => '/my_engine'), it's used as default :as option

  • some of the rake tasks are based on engine name, e.g. my_engine:install:migrations, my_engine:install:assets

Engine name is set by default based on class name. For MyEngine::Engine it will be my_engine_engine. You can change it manually it manually using the engine_name method:

module MyEngine
  class Engine < Rails::Engine
    engine_name "my_engine"
  end
end

Isolated Engine

Normally when you create controllers, helpers and models inside an engine, they are treated as they were created inside the application. This means all application helpers and named routes will be available to your engine's controllers.

However, sometimes you want to isolate your engine from the application, especially if your engine has its own router. To do that, you simply need to call isolate_namespace. This method requires you to pass a module where all your controllers, helpers and models should be nested to:

module MyEngine
  class Engine < Rails::Engine
    isolate_namespace MyEngine
  end
end

With such an engine, everything that is inside the MyEngine module will be isolated from the application.

Consider such controller:

module MyEngine
  class FooController < ActionController::Base
  end
end

If an engine is marked as isolated, FooController has access only to helpers from Engine and url_helpers from MyEngine::Engine.routes.

The next thing that changes in isolated engines is the behaviour of routes. Normally, when you namespace your controllers, you also need to do namespace all your routes. With an isolated engine, the namespace is applied by default, so you can ignore it in routes:

MyEngine::Engine.routes.draw do
  resources :articles
end

The routes above will automatically point to MyEngine::ApplicationContoller. Furthermore, you don't need to use longer url helpers like my_engine_articles_path. Instead, you shuold simply use articles_path as you would do with your application.

To make that behaviour consistent with other parts of the framework, an isolated engine also has influence on ActiveModel::Naming. When you use a namespaced model, like MyEngine::Article, it will normally use the prefix "my_engine". In an isolated engine, the prefix will be ommited in url helpers and form fields for convenience.

polymorphic_url(MyEngine::Article.new) #=> "articles_path"

form_for(MyEngine::Article.new) do
  text_field :title #=> <input type="text" name="article[title]" id="article_title" />
end

Additionaly isolated engine will set its name according to namespace, so MyEngine::Engine.engine_name #=> "my_engine". It will also set MyEngine.table_name_prefix to "my_engine_", changing MyEngine::Article model to use my_engine_article table.

Using Engine's routes outside Engine

Since you can now mount an engine inside application's routes, you do not have direct access to Engine's url_helpers inside Application. When you mount an engine in an application's routes, a special helper is created to allow you to do that. Consider such a scenario:

# APP/config/routes.rb
MyApplication::Application.routes.draw do
  mount MyEngine::Engine => "/my_engine", :as => "my_engine"
  match "/foo" => "foo#index"
end

Now, you can use the my_engine helper inside your application:

class FooController < ApplicationController
  def index
    my_engine.root_url #=> /my_engine/
  end
end

There is also a main_app helper that gives you access to application's routes inside Engine:

module MyEngine
  class BarController
    def index
      main_app.foo_path #=> /foo
    end
  end
end

Note that the :as option given to mount takes the engine_name as default, so most of the time you can simply omit it.

Finally, if you want to generate a url to an engine's route using polymorphic_url, you also need to pass the engine helper. Let's say that you want to create a form pointing to one of the engine's routes. All you need to do is pass the helper as the first element in array with attributes for url:

form_for([my_engine, @user])

This code will use my_engine.user_path(@user) to generate the proper route.

Migrations & seed data

Engines can have their own migrations. The default path for migrations is exactly the same as in application: db/migrate

To use engine's migrations in application you can use rake task, which copies them to application's dir:

rake ENGINE_NAME:install:migrations

Note that some of the migrations may be skipped if a migration with the same name already exists in application. In such a situation you must decide whether to leave that migration or rename the migration in application and rerun copying migrations.

If your engine has migrations, you may also want to prepare data for the database in the seeds.rb file. You can load that data using the load_seed method, e.g.

MyEngine::Engine.load_seed

Defined Under Namespace

Classes: Configuration, Railties

Constant Summary

Constant Summary

Constants inherited from Railtie

Railtie::ABSTRACT_RAILTIES

Class Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods inherited from Railtie

abstract_railtie?, console, generators, #load_console, #load_generators, railtie_name, rake_tasks, subclasses

Methods included from Initializable

included, #run_initializers

Class Attribute Details

+ (Object) called_from

Returns the value of attribute called_from



339
340
341
# File 'railties/lib/rails/engine.rb', line 339

def called_from
  @called_from
end

+ (Object) isolated Also known as: isolated?

Returns the value of attribute isolated



339
340
341
# File 'railties/lib/rails/engine.rb', line 339

def isolated
  @isolated
end

Class Method Details

+ (Object) endpoint(endpoint = nil)



355
356
357
358
# File 'railties/lib/rails/engine.rb', line 355

def endpoint(endpoint = nil)
  @endpoint = endpoint if endpoint
  @endpoint
end

+ (Object) find(path)

Finds engine with given path



384
385
386
# File 'railties/lib/rails/engine.rb', line 384

def find(path)
  Rails::Engine::Railties.engines.find { |r| File.expand_path(r.root.to_s) == File.expand_path(path.to_s) }
end

+ (Object) inherited(base)



343
344
345
346
347
348
349
350
351
352
353
# File 'railties/lib/rails/engine.rb', line 343

def inherited(base)
  unless base.abstract_railtie?
    base.called_from = begin
      # Remove the line number from backtraces making sure we don't leave anything behind
      call_stack = caller.map { |p| p.sub(/:\d+.*/, '') }
      File.dirname(call_stack.detect { |p| p !~ %r[railties[\w.-]*/lib/rails|rack[\w.-]*/lib/rack] })
    end
  end

  super
end

+ (Object) isolate_namespace(mod)



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# File 'railties/lib/rails/engine.rb', line 360

def isolate_namespace(mod)
  engine_name(generate_railtie_name(mod))

  name = engine_name
  self.routes.default_scope = {:module => name}
  self.isolated = true

  unless mod.respond_to?(:_railtie)
    _railtie = self
    mod.singleton_class.instance_eval do
      define_method(:_railtie) do
        _railtie
      end

      unless mod.respond_to?(:table_name_prefix)
        define_method(:table_name_prefix) do
          "#{name}_"
        end
      end
   end
  end
end

Instance Method Details

- (Object) app



410
411
412
413
414
415
# File 'railties/lib/rails/engine.rb', line 410

def app
  @app ||= begin
    config.middleware = config.middleware.merge_into(default_middleware_stack)
    config.middleware.build(endpoint)
  end
end

- (Object) call(env)



421
422
423
# File 'railties/lib/rails/engine.rb', line 421

def call(env)
  app.call(env.merge!(env_config))
end

- (Object) config



445
446
447
# File 'railties/lib/rails/engine.rb', line 445

def config
  @config ||= Engine::Configuration.new(find_root_with_flag("lib"))
end

- (Object) eager_load!



397
398
399
400
401
402
403
404
# File 'railties/lib/rails/engine.rb', line 397

def eager_load!
  config.eager_load_paths.each do |load_path|
    matcher = /\A#{Regexp.escape(load_path)}\/(.*)\.rb\Z/
    Dir.glob("#{load_path}/**/*.rb").sort.each do |file|
      require_dependency file.sub(matcher, '\1')
    end
  end
end

- (Object) endpoint



417
418
419
# File 'railties/lib/rails/engine.rb', line 417

def endpoint
  self.class.endpoint || routes
end

- (Object) env_config



425
426
427
428
429
430
# File 'railties/lib/rails/engine.rb', line 425

def env_config
  @env_config ||= {
    'action_dispatch.routes' => routes,
    'action_dispatch.asset_path' => config.asset_path
  }
end

- (Object) initializers



438
439
440
441
442
443
# File 'railties/lib/rails/engine.rb', line 438

def initializers
  initializers = []
  railties.all { |r| initializers += r.initializers }
  initializers += super
  initializers
end

- (Object) load_seed

Load data from db/seeds.rb file. It can be used in to load engines' seeds, e.g.:

Blog::Engine.load_seed



453
454
455
456
# File 'railties/lib/rails/engine.rb', line 453

def load_seed
  seed_file = paths["db/seeds"].existent.first
  load(seed_file) if File.exist?(seed_file)
end

- (Object) load_tasks



392
393
394
395
# File 'railties/lib/rails/engine.rb', line 392

def load_tasks
  super
  paths["lib/tasks"].existent.sort.each { |ext| load(ext) }
end

- (Object) railties



406
407
408
# File 'railties/lib/rails/engine.rb', line 406

def railties
  @railties ||= self.class::Railties.new(config)
end

- (Object) routes



432
433
434
435
436
# File 'railties/lib/rails/engine.rb', line 432

def routes
  @routes ||= ActionDispatch::Routing::RouteSet.new
  @routes.append(&Proc.new) if block_given?
  @routes
end