organization, controlling load order
From 097b4678f6d52e86a9d46ba6c862e6eb6ef7bbdd Mon Sep 17 00:00:00 2001
From: Jeff Dean
@@ -229,6 +232,9 @@ ul#navMain {
Using an After-Initializer
ActiveRecord::Base includej a variety of configuration options:
logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then passed on to any new database connections made. You can retrieve this logger by calling logger on either an ActiveRecord model class or an ActiveRecord model instance. Set to nil to disable logging.
primary_key_prefix_type lets you adjust the naming for primary key columns. By default, Rails assumes that primary key columns are named id (and this configuration option doesn't need to be set.) There are two other choices:
+:table_name would make the primary key for the Customer class customerid +
++:table_name_with_underscore would make the primary key for the Customer class customer_id +
+table_name_prefix lets you set a global string to be prepended to table names. If you set this to northwest_, then the Customer class will look for northwest_customers as its table. The default is an empty string.
table_name_suffix lets you set a global string to be appended to table names. If you set this to _northwest, then the Customer class will look for customers_northwest as its table. The default is an empty string.
pluralize_table_names specifies whether Rails will look for singular or plural table names in the database. If set to true (the default), then the Customer class will use the customers table. If set to false, then the Customers class will use the customer table.
colorize_logging (true by default) specifies whether or not to use ANSI color codes when logging information from ActiveRecord.
default_timezone determines whether to use Time.local (if set to :local) or Time.utc (if set to :utc) when pulling dates and times from the database. The default is :local.
schema_format controls the format for dumping the database schema to a file. The options are :ruby (the default) for a database-independent version that depends on migrations, or :sql for a set of (potentially database-dependent) SQL statements.
timestamped_migrations controls whether migrations are numbered with serial integers or with timestamps. The default is true, to use timestamps, which are preferred if there are multiple developers working on the same application.
lock_optimistically controls whether ActiveRecord will use optimistic locking. By default this is true.
The MySQL adapter adds one additional configuration option:
ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans controls whether ActiveRecord will consider all tinyint(1) columns in a MySQL database to be booleans. By default this is true.
The schema dumper adds one additional configuration option:
ActiveRecord::SchemaDumper.ignore_tables accepts an array of tables that should not be included in any generated schema file. This setting is ignored unless ActiveRecord::Base.schema_format == :ruby.
ActionController::Base includes a number of configuration settings:
asset_host provides a string that is prepended to all of the URL-generating helpers in AssetHelper. This is designed to allow moving all javascript, CSS, and image files to a separate asset host.
consider_all_requests_local is generally set to true during development and false during production; if it is set to true, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to false and implement local_request? to specify which requests should provide debugging information on errors.
allow_concurrency should be set to true to allow concurrent (threadsafe) action processing. Set to false by default.
param_parsers provides an array of handlers that can extract information from incoming HTTP requests and add it to the params hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active.
default_charset specifies the default character set for all renders. The default is "utf-8".
logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.
resource_action_separator gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/".
resource_path_names is a hash of default names for several RESTful actions. By default, the new action is named new and the edit action is named edit.
request_forgery_protection_token sets the token parameter name for RequestForgery. Calling protect_from_forgery sets it to :authenticity_token by default.
optimise_named_routes turns on some optimizations in generating the routing table. It is set to true by default.
use_accept_header sets the rules for determining the response format. If this is set to true (the default) then respond_to and Request#format will take the Accept header into account. If it is set to false then the request format will be determined solely by examining params[:format]. If there is no format parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request.
allow_forgery_protection enables or disables CSRF protection. By default this is false in test mode and true in all other modes.
relative_url_root can be used to tell Rails that you are deploying to a subdirectory. The default is ENV[RAILS_RELATIVE_URL_ROOT].
The caching code adds two additional settings:
ActionController::Caching::Pages.page_cache_directory sets the directory where Rails will create cached pages for your web server. The default is Rails.public_path (which is usually set to RAILS_ROOT "/public"+).
ActionController::Caching::Pages.page_cache_extension sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is .html.
The dispatcher includes one setting:
ActionController::Dispatcher.error_file_path gives the path where Rails will look for error files such as 404.html. The default is Rails.public_path.
The Active Record session store can also be configured:
CGI::Session::ActiveRecordStore::Session.data_column_name sets the name of the column to use to store session data. By default it is data
organization, controlling load order
ENV
activerecord/lib/active_record/attribute_methods.rb 9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer ⇒ false 11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer ⇒ false
activerecord/lib/active_record/base.rb -394: cattr_accessor :logger, :instance_writer ⇒ false -443: cattr_accessor :configurations, :instance_writer ⇒ false -450: cattr_accessor :primary_key_prefix_type, :instance_writer ⇒ false -456: cattr_accessor :table_name_prefix, :instance_writer ⇒ false -461: cattr_accessor :table_name_suffix, :instance_writer ⇒ false -467: cattr_accessor :pluralize_table_names, :instance_writer ⇒ false -473: cattr_accessor :colorize_logging, :instance_writer ⇒ false -478: cattr_accessor :default_timezone, :instance_writer ⇒ false -487: cattr_accessor :schema_format , :instance_writer ⇒ false -491: cattr_accessor :timestamped_migrations , :instance_writer ⇒ false
activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb -11: cattr_accessor :connection_handler, :instance_writer ⇒ false
activerecord/lib/active_record/connection_adapters/mysql_adapter.rb -166: cattr_accessor :emulate_booleans
activerecord/lib/active_record/fixtures.rb -498: cattr_accessor :all_loaded_fixtures
activerecord/lib/active_record/locking/optimistic.rb -38: base.cattr_accessor :lock_optimistically, :instance_writer ⇒ false
activerecord/lib/active_record/migration.rb -259: cattr_accessor :verbose
activerecord/lib/active_record/schema_dumper.rb -13: cattr_accessor :ignore_tables
activerecord/lib/active_record/serializers/json_serializer.rb -4: base.cattr_accessor :include_root_in_json, :instance_writer ⇒ false
activerecord/Rakefile -142: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object
activerecord/test/cases/lifecycle_test.rb -61: cattr_reader :last_inherited
activerecord/test/cases/mixin_test.rb -9: cattr_accessor :forced_now_time
activeresource/lib/active_resource/base.rb 206: cattr_accessor :logger
activeresource/Rakefile @@ -430,6 +460,13 @@ November 5, 2008: Rough outline by Mike Gun 12: cattr_accessor :local_request
Rakefile 32: rdoc.options << -A cattr_accessor=object
+need to look for def self. ? +
+For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.
The examples in this guide require that you have a working rails application. To create a simple rails app execute:
To begin just change one thing - move init.rb to rails/init.rb.
If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
To setup your plugin to allow for easy testing you'll need to add 3 files:
Now whenever you write a test that requires the database, you can call load_schema.
Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:
vendor/plugins/yaffle/test/yaffle_test.rb:
Now you are ready to test-drive your plugin!
This section will explain how to add a method to String that will be available anywhere in your rails app by:
In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:
vendor/plugins/yaffle/test/core_ext_test.rb
Great - now you are ready to start development.
A common pattern in rails plugins is to set up the file structure like this:
When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.
Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.
If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:
A common pattern in plugins is to add a method called acts_as_something to models. In this case, you want to write a method called acts_as_yaffle that adds a squawk method to your models.
To begin, set up your files so that you have:
With structure you can easily separate the methods that will be used for the class (like Hickwall.some_method) and the instance (like @hickwell.some_method).
This plugin will expect that you've added a method to your model named last_squawk. However, the plugin users might have already defined a method on their model named last_squawk that they use for something else. This plugin will allow the name to be changed by adding a class method called yaffle_text_field.
To start out, write a failing test that shows the behavior you'd like:
vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
This plugin will add a method named squawk to any Active Record objects that call acts_as_yaffle. The squawk method will simply set the value of one of the fields in the database.
To start out, write a failing test that shows the behavior you'd like:
vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.
To create a generator you must:
-Add your instructions to the manifest method of the generator -
--Add any necessary template files to the templates directory -
--Test the generator manually by running various combinations of script/generate and script/destroy -
--Update the USAGE file to add helpful documentation for your generator -
-Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
-Creates a new fake rails root directory that will serve as destination -
--Runs the generator forward and backward, making whatever assertions are necessary -
--Removes the fake rails root -
-For the generator in this section, the test could look something like this:
vendor/plugins/yaffle/test/yaffle_generator_test.rb
require File.dirname(__FILE__) + '/test_helper.rb' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' - -class GeneratorTest < Test::Unit::TestCase - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_bird/, new_file - end - -end -
You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. To start, update your generator file to look like this:
vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - end - - def yaffle_local_assigns - returning(assigns = {}) do - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - end - end -end -
The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.
It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
To run the generator, type the following at the command line:
./script/generate yaffle bird-
and you will see a new file:
db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end -
Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
script/generate-
You should see something like this:
Installed Generators - Plugins (vendor/plugins): yaffle - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration-
When you run script/generate yaffle you should see the contents of your vendor/plugins/yaffle/generators/yaffle/USAGE file.
For this plugin, update the USAGE file looks like this:
Description: - Creates a migration that adds yaffle squawk fields to the given model - -Example: - ./script/generate yaffle hickwall - - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall-
You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
This section describes how you you can create your own commands to add and remove a line of text from routes.rb. This example creates a very simple method that adds or removes a text file.
To start, add the following test method:
vendor/plugins/yaffle/test/generator_test.rb
def test_generates_definition - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - definition = File.read(File.join(fake_rails_root, "definition.txt")) - assert_match /Yaffle\:/, definition -end -
Run rake to watch the test fail, then make the test pass add the following:
vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
Yaffle: A bird-
vendor/plugins/yaffle/lib/yaffle.rb
require "yaffle/commands" -
vendor/plugins/yaffle/lib/commands.rb
require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Update - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update -
Finally, call your new method in the manifest:
vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end -
This section describes how to add a model named Woodpecker to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:
Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.
This section describes how to add a controller named woodpeckers to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
You can test your plugin's controller as you would test any other controller:
Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.
This section describes how to add a helper named WoodpeckersHelper to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
You can test your plugin's helper as you would test any other helper:
Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
vendor/plugins/yaffle/test/routing_test.rb
You can also see if your routes work by running rake routes from your app directory.
Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.
Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.
To add a generator to a plugin:
-Your name. +Write a test
-How to install. +Add your instructions to the manifest method of the generator
-How to add the functionality to the app (several examples of common use cases). +Add any necessary template files to the templates directory
-Warning, gotchas or tips that might help save users time. +Update the USAGE file to add helpful documentation for your generator
Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
Once your comments are good to go, navigate to your plugin directory and run:
Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+Creates a new fake rails root directory that will serve as destination +
++Runs the generator +
++Asserts that the correct files were generated +
++Removes the fake rails root +
+This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
vendor/plugins/yaffle/test/definition_generator_test.rb
require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class DefinitionGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_equal "definition.txt", File.basename(new_file) + end + +end +
You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
To make it pass, create the generator:
vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb
class YaffleDefinitionGenerator < Rails::Generator::Base + def manifest + record do |m| + m.file "definition.txt", "definition.txt" + end + end +end +
If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
./script/generate+
You should see something like this:
Installed Generators + Plugins (vendor/plugins): yaffle_definition + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration+
When you run script/generate yaffle_definition -h you should see the contents of your vendor/plugins/yaffle/generators/yaffle_definition/USAGE.
For this plugin, update the USAGE file could look like this:
Description: + Adds a file with the definition of a Yaffle to the app's main directory+
You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
This section describes how you you can create your own commands to add and remove a line of text from config/routes.rb.
To start, add the following test method:
vendor/plugins/yaffle/test/route_generator_test.rb
require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class RouteGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + + def setup + FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_match /map\.yaffle/, File.read(routes_path) + end + + def test_destroys_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.yaffle + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_no_match /map\.yaffle/, File.read(routes_path) + end +end +
Run rake to watch the test fail, then make the test pass add the following:
vendor/plugins/yaffle/lib/yaffle.rb
require "yaffle/commands" +
vendor/plugins/yaffle/lib/yaffle/commands.rb
require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_route + logger.route "map.yaffle" + look_for = 'ActionController::Routing::Routes.draw do |map|' + unless options[:pretend] + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + end + end + end + + module Destroy + def yaffle_route + logger.route "map.yaffle" + gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + end + end + + module List + def yaffle_route + end + end + + module Update + def yaffle_route + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +
vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb
class YaffleRouteGenerator < Rails::Generator::Base + def manifest + record do |m| + m.yaffle_route + end + end +end +
To see this work, type:
./script/generate yaffle_route +./script/destroy yaffle_route+
+![]() |
+If you haven't set up the custom route from above, script/destroy will fail and you'll have to remove it manually. | +
If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.
If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.
Let's say you have the following migration in your plugin:
vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:
class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +
Here are a few possibilities for how to allow developers to use your plugin migrations:
vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:
class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +
vendor/plugins/yaffle/tasks/yaffle.rake:
namespace :db do + namespace :migrate do + desc "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false." + task :yaffle => :environment do + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true + ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + end + end +end +
vendor/plugins/yaffle/lib/yaffle.rb:
Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| + require file +end +
db/migrate/20081116181115_create_birdhouses.rb:
class CreateBirdhouses < ActiveRecord::Migration + def self.up + Yaffle::CreateBirdhouses.up + end + + def self.down + Yaffle::CreateBirdhouses.down + end +end +
+![]() |
+several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. | +
Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
+call your script/generate script and pass in whatever options they need +
++examine the generated migration, adding/removing columns or other options as necessary +
+This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb
require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class MigrationGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) + end + + def test_pluralizes_properly + ActiveRecord::Base.pluralize_table_names = false + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) + end + +end +
+![]() |
+the migration generator checks to see if a migation already exists, and it's hard-coded to check the db/migrate directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. | +
After running the test with rake you can make it pass with:
vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, + :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" + } + end + end + + private + def custom_file_name + custom_name = class_name.underscore.downcase + custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + end + + def yaffle_local_assigns + returning(assigns = {}) do + assigns[:migration_action] = "add" + assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" + assigns[:table_name] = custom_file_name + assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] + end + end +end +
The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.
It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
To run the generator, type the following at the command line:
./script/generate yaffle_migration bird+
and you will see a new file:
db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + end + + def self.down + remove_column :birds, :last_squawk + end +end +
Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
+Your name. +
++How to install. +
++How to add the functionality to the app (several examples of common use cases). +
++Warning, gotchas or tips that might help save users time. +
+Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
Once your comments are good to go, navigate to your plugin directory and run:
rake rdoc
When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
vendor/plugins/yaffle/tasks/yaffle.rake
yaffle:squawk # Prints out the word 'Yaffle'
You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.
Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.
You can even store plugins inside of other plugins for complete plugin madness!
config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")-
If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.
If you are an RSpec fan, you can install the rspec_plugin_generator gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master.
@@ -1550,41 +1805,58 @@ http://www.gnu.org/software/src-highlite --> http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
+http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +
+The final plugin should have a directory structure that looks something like this:
|-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db+
vendor/plugins/yaffle/ +|-- MIT-LICENSE +|-- README +|-- Rakefile +|-- generators +| `-- yaffle +| |-- USAGE +| |-- templates +| | `-- definition.txt +| `-- yaffle_generator.rb +|-- install.rb +|-- lib +| |-- app +| | |-- controllers +| | | `-- woodpeckers_controller.rb +| | |-- helpers +| | | `-- woodpeckers_helper.rb +| | `-- models +| | `-- woodpecker.rb +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +|-- rails +| `-- init.rb +|-- tasks +| `-- yaffle_tasks.rake +|-- test +| |-- acts_as_yaffle_test.rb +| |-- core_ext_test.rb +| |-- database.yml +| |-- debug.log +| |-- generator_test.rb +| |-- schema.rb +| |-- test_helper.rb +| |-- woodpecker_test.rb +| |-- woodpeckers_controller_test.rb +| |-- wookpeckers_helper_test.rb +| |-- yaffle_plugin.sqlite3.db +| `-- yaffle_test.rb +`-- uninstall.rb
Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run rake db:migrate. Active Record will work out which migrations should be run.
Migrations are a convenient way for you to alter your database in a structured and organised manner. You could edit fragments of SQL by hand but you would then be responsible for telling other developers that they need to go and run it. You'd also have to keep track of which changes need to be run against the production machines next time you deploy. Active Record tracks which migrations have already been run so all you have to do is update your source and run rake db:migrate. Active Record will work out which migrations should be run. It will also update your db/schema.rb file to match the structure of your database.
Migrations also allow you to describe these transformations using Ruby. The great thing about this is that (like most of Active Record's functionality) it is database independent: you don't need to worry about the precise syntax of CREATE TABLE any more that you worry about variations on SELECT * (you can drop down to raw SQL for database specific features). For example you could use SQLite3 in development, but MySQL in production.
You'll learn all about migrations including:
Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be db:migrate. In its most basic form it just runs the up method for all the migrations that have not yet been run. If there are no such migrations it exits.
Note that running the db:migrate also invokes the db:schema:dump task, which will update your db/schema.rb file to match the structure of your database.
If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run