From 39e1ac658efc80e4c54abef4f1c7679e4b3dc2ac Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sun, 18 Jan 2009 18:10:58 +0000 Subject: Merge docrails --- railties/doc/guides/html/creating_plugins.html | 908 ++++++++++--------------- 1 file changed, 346 insertions(+), 562 deletions(-) (limited to 'railties/doc/guides/html/creating_plugins.html') diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 850822c8ed..3347f77228 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -1,310 +1,142 @@ - - The Basics of Creating Rails Plugins - - - - - + + The Basics of Creating Rails Plugins + + + + - -
- - - -
-

The Basics of Creating Rails Plugins

-
+
+ + + +
+

The Basics of Creating Rails Plugins

+
-

A Rails plugin is either an extension or a modification of the core framework. Plugins provide:

-
    +

    A Rails plugin is either an extension or a modification of the core framework. Plugins provide:

    +
    • a way for developers to share bleeding-edge ideas without hurting the stable code base @@ -321,8 +153,8 @@ an outlet for the core developers so that they don’t have to include every coo

    -

    After reading this guide you should be familiar with:

    -
      +

      After reading this guide you should be familiar with:

      +
      • Creating a plugin from scratch @@ -359,8 +191,8 @@ Avoiding common pitfalls with init.rb

      -

      This guide describes how to build a test-driven plugin that will:

      -
        +

        This guide describes how to build a test-driven plugin that will:

        +
        • Extend core ruby classes like Hash and String @@ -392,13 +224,13 @@ A custom route method that can be used in routes.rb

        -

        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.

        +

        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.

    1. Setup

    1.1. Create the basic app

    -

    The examples in this guide require that you have a working rails application. To create a simple rails app execute:

    +

    The examples in this guide require that you have a working rails application. To create a simple rails app execute:

    gem install rails
    @@ -408,32 +240,32 @@ script/generate scaffold bird name:string
     rake db:migrate
     script/server
    -

    Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.

    +

    Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.

    +
    Editor’s note:
    The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
    Note -
    Editor's note:
    The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.

    1.2. Generate the plugin skeleton

    -

    Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.

    -

    This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories.

    -

    Examples:

    +

    Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.

    +

    This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories.

    +

    Examples:

    ./script/generate plugin yaffle
     ./script/generate plugin yaffle --with-generator
    -

    To get more detailed help on the plugin generator, type ./script/generate plugin.

    -

    Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the --with-generator option now:

    +

    To get more detailed help on the plugin generator, type ./script/generate plugin.

    +

    Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the --with-generator option now:

    ./script/generate plugin yaffle --with-generator
    -

    You should see the following output:

    +

    You should see the following output:

    create  vendor/plugins/yaffle/lib
    @@ -455,7 +287,7 @@ create  vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
     create  vendor/plugins/yaffle/generators/yaffle/USAGE

    1.3. Organize your files

    -

    To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:

    +

    To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:

    |-- lib
    @@ -465,20 +297,19 @@ create  vendor/plugins/yaffle/generators/yaffle/USAGE
    | `-- init.rb
    -

    vendor/plugins/yaffle/rails/init.rb

    +

    vendor/plugins/yaffle/rails/init.rb

    -
    require 'yaffle'
    -
    -

    Now you can add any require statements to lib/yaffle.rb and keep init.rb clean.

    +
    require 'yaffle'
+

Now you can add any require statements to lib/yaffle.rb and keep init.rb clean.

2. Tests

-

In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:

-
    +

    In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you’ll need to add 3 files:

    +
    • A database.yml file with all of your connection strings @@ -496,7 +327,7 @@ A test helper method that sets up the database

    2.1. Test Setup

    -

    vendor/plugins/yaffle/test/database.yml:

    +

    vendor/plugins/yaffle/test/database.yml:

    sqlite:
    @@ -521,8 +352,8 @@ mysql:
       :password: password
       :database: yaffle_plugin_test
    -

    For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:

    -

    vendor/plugins/yaffle/test/schema.rb:

    +

    For this guide you’ll need 2 tables/models, Hickwalls and Wickwalls, so add the following:

    +

    vendor/plugins/yaffle/test/schema.rb:

    create_table :woodpeckers, :force => true do |t| t.string :name end -end -
    -

    vendor/plugins/yaffle/test/test_helper.rb:

    +end
+

vendor/plugins/yaffle/test/test_helper.rb:

assert_equal [], Wickwall.all end -end -
-

To run this, go to the plugin directory and run rake:

+end
+

To run this, go to the plugin directory and run rake:

cd vendor/plugins/yaffle
 rake
-

You should see output like:

+

You should see output like:

/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
@@ -637,7 +465,7 @@ Finished in 0.002236 seconds.
 
 1 test, 1 assertion, 0 failures, 0 errors
-

By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:

+

By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:

rake DB=sqlite
@@ -645,13 +473,13 @@ rake DB=sqlite3
 rake DB=mysql
 rake DB=postgresql
-

Now you are ready to test-drive your plugin!

+

Now you are ready to test-drive your plugin!

3. Extending core classes

-

This section will explain how to add a method to String that will be available anywhere in your rails app.

-

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

+

This section will explain how to add a method to String that will be available anywhere in your rails app.

+

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

def test_to_squawk_prepends_the_word_squawk assert_equal "squawk! Hello World", "Hello World".to_squawk end -end -
-

Navigate to your plugin directory and run rake test:

+end
+

Navigate to your plugin directory and run rake test:

cd vendor/plugins/yaffle
 rake test
-

The test above should fail with the message:

+

The test above should fail with the message:

 1) Error:
@@ -679,18 +506,17 @@ test_to_squawk_prepends_the_word_squawk(CoreExtTest):
 NoMethodError: undefined method `to_squawk' for "Hello World":String
     ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk'
-

Great - now you are ready to start development.

-

Then in lib/yaffle.rb require lib/core_ext.rb:

-

vendor/plugins/yaffle/lib/yaffle.rb

+

Great - now you are ready to start development.

+

Then in lib/yaffle.rb require lib/core_ext.rb:

+

vendor/plugins/yaffle/lib/yaffle.rb

-
require "yaffle/core_ext"
-
-

Finally, create the core_ext.rb file and add the to_squawk method:

-

vendor/plugins/yaffle/lib/yaffle/core_ext.rb

+
require "yaffle/core_ext"
+

Finally, create the core_ext.rb file and add the to_squawk method:

+

vendor/plugins/yaffle/lib/yaffle/core_ext.rb

def to_squawk "squawk! #{self}".strip end -end -
-

To test that your method does what it says it does, run the unit tests with rake from your plugin directory. To see this in action, fire up a console and start squawking:

+end +

To test that your method does what it says it does, run the unit tests with rake from your plugin directory. To see this in action, fire up a console and start squawking:

$ ./script/console
@@ -710,10 +535,10 @@ http://www.gnu.org/software/src-highlite -->
 => "squawk! Hello World"

3.1. Working with init.rb

-

When rails loads plugins it looks for the file named init.rb or rails/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:

-

vendor/plugins/yaffle/rails/init.rb

+

When rails loads plugins it looks for the file named init.rb or rails/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:

+

vendor/plugins/yaffle/rails/init.rb

def is_a_special_hash? true end -end -
-

Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:

-

vendor/plugins/yaffle/rails/init.rb

+end +

Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:

+

vendor/plugins/yaffle/rails/init.rb

def is_a_special_hash? true end -end -
+end

4. Add an acts_as method to Active Record

-

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:

-

vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

+

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:

+

vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

require File.dirname(__FILE__) + '/test_helper.rb'
 
 class ActsAsYaffleTest < Test::Unit::TestCase
-end
-
-

vendor/plugins/yaffle/lib/yaffle.rb

+end
+

vendor/plugins/yaffle/lib/yaffle.rb

-
require 'yaffle/acts_as_yaffle'
-
-

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

+
require 'yaffle/acts_as_yaffle'
+

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

module Yaffle
   # your code will go here
-end
-
-

Note that after requiring acts_as_yaffle you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.

-

One of the most common plugin patterns for acts_as_yaffle plugins is to structure your file like so:

-

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

+end +

Note that after requiring acts_as_yaffle you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models.

+

One of the most common plugin patterns for acts_as_yaffle plugins is to structure your file like so:

+

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

module InstanceMethods # any method placed here will apply to instaces, like @hickwall end -end -
-

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).

+end +

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).

4.1. Add a class 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 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

def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end -end -
-

To make these tests pass, you could modify your acts_as_yaffle file like so:

-

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

+end +

To make these tests pass, you could modify your acts_as_yaffle file like so:

+

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

end end -ActiveRecord::Base.send :include, Yaffle -
+ActiveRecord::Base.send :include, Yaffle

4.2. Add an instance method

-

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

+

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

wickwall.squawk("Hello World") assert_equal "squawk! Hello World", wickwall.last_tweet end -end -
-

Run this test to make sure the last two tests fail, then update acts_as_yaffle.rb to look like this:

-

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

+end +

Run this test to make sure the last two tests fail, then update acts_as_yaffle.rb to look like this:

+

vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb

end end -ActiveRecord::Base.send :include, Yaffle -
+ActiveRecord::Base.send :include, Yaffle
+
Editor’s note:
The use of write_attribute to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use send("#{self.class.yaffle_text_field}=", string.to_squawk).
Note -
Editor's note:
The use of write_attribute to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use send("#{self.class.yaffle_text_field}=", string.to_squawk).

5. Models

-

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:

+

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:

vendor/plugins/yaffle/
@@ -952,8 +767,8 @@ ActiveRecord::Base

As always, start with a test:

-

vendor/plugins/yaffle/yaffle/woodpecker_test.rb:

+

As always, start with a test:

+

vendor/plugins/yaffle/yaffle/woodpecker_test.rb:

def test_woodpecker assert_kind_of Woodpecker, Woodpecker.new end -end -
-

This is just a simple test to make sure the class is being loaded correctly. After watching it fail with rake, you can make it pass like so:

-

vendor/plugins/yaffle/lib/yaffle.rb:

+end
+

This is just a simple test to make sure the class is being loaded correctly. After watching it fail with rake, you can make it pass like so:

+

vendor/plugins/yaffle/lib/yaffle.rb:

$LOAD_PATH << path ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) -end -
-

Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the load_once_paths allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.

-

vendor/plugins/yaffle/lib/app/models/woodpecker.rb:

+end +

Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the load_once_paths allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin.

+

vendor/plugins/yaffle/lib/app/models/woodpecker.rb:

class Woodpecker < ActiveRecord::Base
-end
-
-

Finally, add the following to your plugin's schema.rb:

-

vendor/plugins/yaffle/test/schema.rb:

+end +

Finally, add the following to your plugin’s schema.rb:

+

vendor/plugins/yaffle/test/schema.rb:

create_table :woodpeckers, :force => true do |t|
   t.string :name
-end
-
-

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.

+end +

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.

6. Controllers

-

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:

-

vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:

+

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:

+

vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:

get :index assert_response :success end -end -
-

This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with rake, you can make it pass like so:

-

vendor/plugins/yaffle/lib/yaffle.rb:

+end
+

This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with rake, you can make it pass like so:

+

vendor/plugins/yaffle/lib/yaffle.rb:

$LOAD_PATH << path ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) -end -
-

vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:

+end +

vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:

render :text => "Squawk!" end -end -
-

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.

+end +

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.

7. Helpers

-

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:

-

vendor/plugins/yaffle/test/woodpeckers_helper_test.rb

+

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:

+

vendor/plugins/yaffle/test/woodpeckers_helper_test.rb

def test_tweet assert_equal "Tweet! Hello", tweet("Hello") end -end -
-

This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with rake, you can make it pass like so:

-

vendor/plugins/yaffle/lib/yaffle.rb:

+end
+

This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with rake, you can make it pass like so:

+

vendor/plugins/yaffle/lib/yaffle.rb:

$LOAD_PATH << path ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) -end -
-

vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:

+end +

vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:

"Tweet! #{text}" end -end -
-

Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.

+end +

Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.

8. Routes

-

In a standard routes.rb file you use routes like map.connect or map.resources. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with map.yaffles.

-

Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this:

-

vendor/plugins/yaffle/test/routing_test.rb

+

In a standard routes.rb file you use routes like map.connect or map.resources. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with map.yaffles.

+

Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this:

+

vendor/plugins/yaffle/test/routing_test.rb

result = ActionController::Routing::Routes.recognize_path(path, :method => method) assert_equal options, result end -end -
-

Once you see the tests fail by running rake, you can make them pass with:

-

vendor/plugins/yaffle/lib/yaffle.rb

+end
+

Once you see the tests fail by running rake, you can make them pass with:

+

vendor/plugins/yaffle/lib/yaffle.rb

-
require "yaffle/routing"
-
-

vendor/plugins/yaffle/lib/yaffle/routing.rb

+
require "yaffle/routing"
+

vendor/plugins/yaffle/lib/yaffle/routing.rb

end end -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -
-

config/routes.rb

+ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +

config/routes.rb

ActionController::Routing::Routes.draw do |map|
   map.yaffles
-end
-
-

You can also see if your routes work by running rake routes from your app directory.

+end +

You can also see if your routes work by running rake routes from your app directory.

9. Generators

-

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: generating a simple text file.

+

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: generating a simple text file.

9.1. Testing generators

-

Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:

-
    +

    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 @@ -1217,8 +1018,8 @@ 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

    +

    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

    Dir.glob(File.join(fake_rails_root, "*")) 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

    +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

m.file "definition.txt", "definition.txt" end end -end -
+end

9.2. The USAGE file

-

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:

+

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:

+

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:

+

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:
@@ -1297,10 +1096,10 @@ http://www.gnu.org/software/src-highlite -->
 

10. Generator Commands

-

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

+

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

File.join(fake_rails_root, "config", "routes.rb") end -end -
-

Run rake to watch the test fail, then make the test pass add the following:

-

vendor/plugins/yaffle/lib/yaffle.rb

+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 "yaffle/commands"
+

vendor/plugins/yaffle/lib/yaffle/commands.rb

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

+Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +

vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb

m.yaffle_route end end -end -
-

To see this work, type:

+end +

To see this work, type:

./script/generate yaffle_route
@@ -1442,16 +1237,16 @@ http://www.gnu.org/software/src-highlite -->
 Note
 
 
-
Editor's note:
If you haven't set up the custom route from above, script/destroy will fail and you'll have to remove it manually. +
Editor’s note:
If you haven’t set up the custom route from above, script/destroy will fail and you’ll have to remove it manually.

11. Migrations

-

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:

+

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:

def self.down drop_table :birdhouses end -end -
-

Here are a few possibilities for how to allow developers to use your plugin migrations:

+end
+

Here are a few possibilities for how to allow developers to use your plugin migrations:

11.1. Create a custom rake task

-

vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:

+

vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:

def self.down drop_table :birdhouses end -end -
-

vendor/plugins/yaffle/tasks/yaffle.rake:

+end +

vendor/plugins/yaffle/tasks/yaffle.rake:

Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby end end -end -
+end

11.2. Call migrations directly

-

vendor/plugins/yaffle/lib/yaffle.rb:

+

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:

+end +

db/migrate/20081116181115_create_birdhouses.rb:

def self.down Yaffle::CreateBirdhouses.down end -end -
+end
+
Editor’s note:
several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
Note -
Editor's note:
several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.

11.3. Generate migrations

-

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:

-
+
Editor’s note:
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.
Note -
Editor's note:
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

+

After running the test with rake you can make it pass with:

+

vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb

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:

+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

+

and you will see a new file:

+

db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

def self.down remove_column :birds, :last_squawk end -end -
+end

12. Rake tasks

-

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

+

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

task :squawk => :environment do puts "squawk!" end -end -
-

When you run rake -T from your plugin you will see:

+end
+

When you run rake -T from your plugin you will see:

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.

-

Note that tasks from vendor/plugins/yaffle/Rakefile are not available to the main app.

+

You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.

+

Note that tasks from vendor/plugins/yaffle/Rakefile are not available to the main app.

13. PluginGems

-

Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.

-

Historically rails plugins loaded the plugin's init.rb file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, init.rb was moved to rails/init.rb.

-

It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in Rakefile. A rake task that packages the gem might look like this:

-

vendor/plugins/yaffle/Rakefile:

+

Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem.

+

Historically rails plugins loaded the plugin’s init.rb file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, init.rb was moved to rails/init.rb.

+

It’s common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in Rakefile. A rake task that packages the gem might look like this:

+

vendor/plugins/yaffle/Rakefile:

# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| # require file # end -

15.3. Final plugin directory structure

-

The final plugin should have a directory structure that looks something like this:

+

The final plugin should have a directory structure that looks something like this:

|-- MIT-LICENSE
@@ -1906,7 +1690,7 @@ http://www.gnu.org/software/src-highlite -->
 
- - + + -- cgit v1.2.3