(Canada on Rails, 2005)
"Rails Engines provide a means to share common functionality across many projects, in a package that's easy to both update *and* override.
"This presentation will explain the concepts behind Engines and demonstrate how they work within a Rails application. I will also discuss how Engines has dramatically enhanced collaboration within our own development team, and how such collaboration can be extended into the Rails community as a whole."
12. db/migrate/001_add_help.rb
class AddHelp < ActiveRecord::Migration
def self.up
create_table :help_pages do |t|
t.column :key, :string
t.column :title, :string
t.column :content, :text
end
end
def self.down
drop_table :help_pages
end
end
23. meanwhile, in our app:
class HelpPage < ActiveRecord::Base
# only words containing the
# letter ‘x’ are important
def summarize(limit=20)
content.split.select { |word|
word.include?(’x’)
}.flatten[0..limit].join
end
end
55. generating an engine
$ script/generate engine Help
Author's name: James Adam
Author's email: james.adam@gmail.com
We can automatically generate a license for you:
0) MIT 1) GPL 2) LGPL 3) None
Please select a license: 0
create vendor/plugins/help
create vendor/plugins/help/README
create vendor/plugins/help/install.rb
create vendor/plugins/help/init_engine.rb
create vendor/plugins/help/app
create vendor/plugins/help/app/models
create vendor/plugins/help/app/controllers
create vendor/plugins/help/app/helpers
create vendor/plugins/help/app/views
create vendor/plugins/help/db
56. client customisation
module HelpHelper
def help_link(key=nil) # overrides method in engine
key ||= params[:controller] + ‘/’ +
params[:action]
page = HelpPage.find_by_key(key)
if page.nil?
link_to(’Add help page?’, {:controller => ‘help’,
:action => ‘create’, :key => key})
else
link_to(‘More information...’, # different text
{:controller => ‘help’,
:action => ‘show’,
:id => page},
{:class => ‘info_link’})
end
end
end
/app/helpers/help_helper.rb
57. extending & overriding
class HelpController < ApplicationController
def create # method NOT in engine
if request.post?
page = HelpPage.new(params[:new_page])
unless page.save
flash[:message] = ‘Oh noes!’
end
end
end
end
/app/controllers/help_controller.rb