Instiki 0.16.3: Rails 2.3.0

Instiki now runs on the Rails 2.3.0 Candidate Release.
Among other improvements, this means that it now 
automagically selects between WEBrick and Mongrel.

Just run

    ./instiki --daemon
This commit is contained in:
Jacques Distler 2009-02-04 14:26:08 -06:00
parent 43aadecc99
commit 4e14ccc74d
893 changed files with 71965 additions and 28511 deletions

View file

@ -1,4 +1,4 @@
== Add an `acts_as_yaffle` method to Active Record ==
== 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.

View file

@ -1,46 +1,104 @@
== Appendix ==
If you prefer to use RSpec instead of Test::Unit, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator].
=== References ===
* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
* http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii
* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-ii
* http://github.com/technoweenie/attachment_fu/tree/master
* 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
* http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
=== Contents of 'lib/yaffle.rb' ===
*vendor/plugins/yaffle/lib/yaffle.rb:*
[source, ruby]
----------------------------------------------
require "yaffle/core_ext"
require "yaffle/acts_as_yaffle"
require "yaffle/commands"
require "yaffle/routing"
%w{ models controllers helpers }.each do |dir|
path = File.join(File.dirname(__FILE__), 'app', dir)
$LOAD_PATH << path
ActiveSupport::Dependencies.load_paths << path
ActiveSupport::Dependencies.load_once_paths.delete(path)
end
# optionally:
# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
# require file
# end
----------------------------------------------
=== Final plugin directory structure ===
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
|-- MIT-LICENSE
|-- README
|-- Rakefile
|-- generators
| |-- yaffle_definition
| | |-- USAGE
| | |-- templates
| | | `-- definition.txt
| | `-- yaffle_definition_generator.rb
| |-- yaffle_migration
| | |-- USAGE
| | |-- templates
| | `-- yaffle_migration_generator.rb
| `-- yaffle_route
| |-- USAGE
| |-- templates
| `-- yaffle_route_generator.rb
|-- install.rb
|-- lib
| |-- app
| | |-- controllers
| | | `-- woodpeckers_controller.rb
| | |-- helpers
| | | `-- woodpeckers_helper.rb
| | `-- models
| | `-- woodpecker.rb
| |-- db
| | `-- migrate
| | `-- 20081116181115_create_birdhouses.rb
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
| | |-- core_ext.rb
| | `-- routing.rb
| `-- yaffle.rb
|-- pkg
| `-- yaffle-0.0.1.gem
|-- rails
| `-- init.rb
|-- tasks
| `-- yaffle_tasks.rake
|-- test
| |-- acts_as_yaffle_test.rb
| |-- core_ext_test.rb
| |-- database.yml
| |-- debug.log
| |-- definition_generator_test.rb
| |-- migration_generator_test.rb
| |-- route_generator_test.rb
| |-- routes_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
------------------------------------------------

View file

@ -1,10 +1,10 @@
== Add a controller ==
== 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/yaffle/woodpeckers_controller_test.rb:*
*vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:*
[source, ruby]
----------------------------------------------
@ -19,6 +19,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase
@controller = WoodpeckersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
ActionController::Routing::Routes.draw do |map|
map.resources :woodpeckers
end
end
def test_index

View file

@ -1,11 +1,6 @@
== Extending core classes ==
This section will explain how to add a method to String that will be available anywhere in your rails app by:
* Writing tests for the desired behavior
* Creating and requiring the correct files
=== Creating the test ===
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:
@ -40,26 +35,6 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String
Great - now you are ready to start development.
=== Organize your files ===
A common pattern in rails plugins is to set up the file structure like this:
--------------------------------------------------------
|-- lib
| |-- yaffle
| | `-- core_ext.rb
| `-- yaffle.rb
--------------------------------------------------------
The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb':
*vendor/plugins/yaffle/rails/init.rb*
[source, ruby]
--------------------------------------------------------
require 'yaffle'
--------------------------------------------------------
Then in 'lib/yaffle.rb' require 'lib/core_ext.rb':
*vendor/plugins/yaffle/lib/yaffle.rb*
@ -92,13 +67,13 @@ $ ./script/console
=== Working with init.rb ===
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.
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/init.rb*
*vendor/plugins/yaffle/rails/init.rb*
[source, ruby]
---------------------------------------------------
@ -111,7 +86,7 @@ end
Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
*vendor/plugins/yaffle/init.rb*
*vendor/plugins/yaffle/rails/init.rb*
[source, ruby]
---------------------------------------------------

View file

@ -0,0 +1,4 @@
# To change this template, choose Tools | Templates
# and open the template in the editor.
puts "Hello World"

View file

@ -0,0 +1,50 @@
== 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:*
[source, ruby]
----------------------------------------------
PKG_FILES = FileList[
'[a-zA-Z]*',
'generators/**/*',
'lib/**/*',
'rails/**/*',
'tasks/**/*',
'test/**/*'
]
spec = Gem::Specification.new do |s|
s.name = "yaffle"
s.version = "0.0.1"
s.author = "Gleeful Yaffler"
s.email = "yaffle@example.com"
s.homepage = "http://yafflers.example.com/"
s.platform = Gem::Platform::RUBY
s.summary = "Sharing Yaffle Goodness"
s.files = PKG_FILES.to_a
s.require_path = "lib"
s.has_rdoc = false
s.extra_rdoc_files = ["README"]
end
desc 'Turn this plugin into a gem.'
Rake::GemPackageTask.new(spec) do |pkg|
pkg.gem_spec = spec
end
----------------------------------------------
To build and install the gem locally, run the following commands:
----------------------------------------------
cd vendor/plugins/yaffle
rake gem
sudo gem install pkg/yaffle-0.0.1.gem
----------------------------------------------
To test this, create a new rails app, add 'config.gem "yaffle"' to environment.rb and all of your plugin's functionality will be available to you.

View file

@ -0,0 +1,144 @@
== 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*
[source, ruby]
-----------------------------------------------------------
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 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\.yaffles/, File.read(routes_path)
end
def test_destroys_route
content = <<-END
ActionController::Routing::Routes.draw do |map|
map.yaffles
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\.yaffles/, File.read(routes_path)
end
private
def fake_rails_root
File.join(File.dirname(__FILE__), "rails_root")
end
def routes_path
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*
[source, ruby]
-----------------------------------------------------------
require "yaffle/commands"
-----------------------------------------------------------
*vendor/plugins/yaffle/lib/yaffle/commands.rb*
[source, ruby]
-----------------------------------------------------------
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.yaffles\n"}
end
end
end
module Destroy
def yaffle_route
logger.route "map.yaffle"
gsub_file 'config/routes.rb', /\n.+?map\.yaffles/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_route/yaffle_route_generator.rb*
[source, ruby]
-----------------------------------------------------------
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
-----------------------------------------------------------
.Editor's note:
NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually.

View file

@ -0,0 +1,98 @@
== 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.
=== Testing generators ===
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*
[source, ruby]
------------------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
require 'rails_generator'
require 'rails_generator/scripts/generate'
class DefinitionGeneratorTest < Test::Unit::TestCase
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
private
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
end
def file_list
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*
[source, ruby]
------------------------------------------------------------------
class YaffleDefinitionGenerator < Rails::Generator::Base
def manifest
record do |m|
m.file "definition.txt", "definition.txt"
end
end
end
------------------------------------------------------------------
=== 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:
------------------------------------------------------------------
./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
------------------------------------------------------------------

View file

@ -1,4 +1,4 @@
== Add a helper ==
== 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.
@ -30,8 +30,6 @@ This is just a simple test to make sure the helper is being loaded correctly. A
ActiveSupport::Dependencies.load_paths << path
ActiveSupport::Dependencies.load_once_paths.delete(path)
end
ActionView::Base.send :include, WoodpeckersHelper
----------------------------------------------

View file

@ -29,24 +29,32 @@ This guide describes how to build a test-driven plugin that will:
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.
include::test_setup.txt[]
include::setup.txt[]
include::tests.txt[]
include::core_ext.txt[]
include::acts_as_yaffle.txt[]
include::migration_generator.txt[]
include::generator_method.txt[]
include::models.txt[]
include::controllers.txt[]
include::helpers.txt[]
include::custom_route.txt[]
include::routes.txt[]
include::odds_and_ends.txt[]
include::generators.txt[]
include::generator_commands.txt[]
include::migrations.txt[]
include::tasks.txt[]
include::gems.txt[]
include::rdoc.txt[]
include::appendix.txt[]

View file

@ -1,156 +0,0 @@
== Create a generator ==
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
=== Testing generators ===
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*
[source, ruby]
------------------------------------------------------------------
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.
=== Adding to the manifest ===
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*
[source, ruby]
------------------------------------------------------------------
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.
=== Manually test the generator ===
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*
[source, ruby]
------------------------------------------------------------------
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
end
def self.down
remove_column :birds, :last_squawk
end
end
------------------------------------------------------------------
=== 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
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
------------------------------------------------------------------

View file

@ -0,0 +1,194 @@
== 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:*
[source, ruby]
----------------------------------------------
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:
=== Create a custom rake task ===
*vendor/plugins/yaffle/tasks/yaffle_tasks.rake:*
[source, ruby]
----------------------------------------------
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
----------------------------------------------
=== Call migrations directly ===
*vendor/plugins/yaffle/lib/yaffle.rb:*
[source, ruby]
----------------------------------------------
Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
require file
end
----------------------------------------------
*db/migrate/20081116181115_create_birdhouses.rb:*
[source, ruby]
----------------------------------------------
class CreateBirdhouses < ActiveRecord::Migration
def self.up
Yaffle::CreateBirdhouses.up
end
def self.down
Yaffle::CreateBirdhouses.down
end
end
----------------------------------------------
.Editor's note:
NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
=== 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:
* 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*
[source, ruby]
------------------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
require 'rails_generator'
require 'rails_generator/scripts/generate'
class MigrationGeneratorTest < Test::Unit::TestCase
def setup
FileUtils.mkdir_p(fake_rails_root)
@original_files = file_list
end
def teardown
ActiveRecord::Base.pluralize_table_names = true
FileUtils.rm_r(fake_rails_root)
end
def test_generates_correct_file_name
Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "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_migration", "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
private
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
end
------------------------------------------------------------------
.Editor's note:
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_migration/yaffle_migration_generator.rb*
[source, ruby]
------------------------------------------------------------------
class YaffleMigrationGenerator < 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
custom_name
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*
[source, ruby]
------------------------------------------------------------------
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
end
def self.down
remove_column :birds, :last_squawk
end
end
------------------------------------------------------------------

View file

@ -1,4 +1,4 @@
== Add a model ==
== 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:
@ -20,7 +20,7 @@ vendor/plugins/yaffle/
As always, start with a test:
*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:*
*vendor/plugins/yaffle/test/woodpecker_test.rb:*
[source, ruby]
----------------------------------------------
@ -66,11 +66,9 @@ Finally, add the following to your plugin's 'schema.rb':
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :woodpeckers, :force => true do |t|
t.string :name
end
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.
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.

View file

@ -1,69 +0,0 @@
== Odds and ends ==
=== Generate RDoc Documentation ===
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
=== Write custom Rake tasks in your plugin ===
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*
[source, ruby]
---------------------------------------------------------
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
puts "squawk!"
end
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.
=== Store plugins in alternate locations ===
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!
[source, ruby]
---------------------------------------------------------
config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
---------------------------------------------------------
=== Create your own Plugin Loaders and Plugin Locators ===
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.
=== Use Custom Plugin Generators ===
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.

View file

@ -0,0 +1,18 @@
== RDoc Documentation ==
Once your plugin is stable 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. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api.
Once your comments are good to go, navigate to your plugin directory and run:
---------------------------------------------------------
rake rdoc
---------------------------------------------------------

View file

@ -1,6 +1,8 @@
== Add a Custom Route ==
== Routes ==
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.
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*
@ -22,10 +24,6 @@ class RoutingTest < Test::Unit::TestCase
private
# yes, I know about assert_recognizes, but it has proven problematic to
# use in these tests, since it uses RouteSet#recognize (which actually
# tries to instantiate the controller) and because it uses an awkward
# parameter order.
def assert_recognition(method, path, options)
result = ActionController::Routing::Routes.recognize_path(path, :method => method)
assert_equal options, result
@ -33,15 +31,16 @@ class RoutingTest < Test::Unit::TestCase
end
--------------------------------------------------------
*vendor/plugins/yaffle/init.rb*
Once you see the tests fail by running 'rake', you can make them pass with:
*vendor/plugins/yaffle/lib/yaffle.rb*
[source, ruby]
--------------------------------------------------------
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
require "yaffle/routing"
--------------------------------------------------------
*vendor/plugins/yaffle/lib/routing.rb*
*vendor/plugins/yaffle/lib/yaffle/routing.rb*
[source, ruby]
--------------------------------------------------------
@ -54,6 +53,8 @@ module Yaffle #:nodoc:
end
end
end
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
*config/routes.rb*
@ -61,7 +62,6 @@ end
[source, ruby]
--------------------------------------------------------
ActionController::Routing::Routes.draw do |map|
...
map.yaffles
end
--------------------------------------------------------

View file

@ -0,0 +1,84 @@
== Setup ==
=== Create the basic app ===
The examples in this guide require that you have a working rails application. To create a simple rails app execute:
------------------------------------------------
gem install rails
rails yaffle_guide
cd yaffle_guide
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.
.Editor's note:
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.
=== 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:
----------------------------------------------
./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:
----------------------------------------------
./script/generate plugin yaffle --with-generator
----------------------------------------------
You should see the following output:
----------------------------------------------
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/tasks
create vendor/plugins/yaffle/test
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib/yaffle.rb
create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
create vendor/plugins/yaffle/test/core_ext_test.rb
create vendor/plugins/yaffle/generators
create vendor/plugins/yaffle/generators/yaffle
create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
=== 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:
--------------------------------------------------------
|-- lib
| |-- yaffle
| `-- yaffle.rb
`-- rails
|
`-- init.rb
--------------------------------------------------------
*vendor/plugins/yaffle/rails/init.rb*
[source, ruby]
--------------------------------------------------------
require 'yaffle'
--------------------------------------------------------
Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean.

View file

@ -0,0 +1,27 @@
== 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_tasks.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_tasks.rake*
[source, ruby]
---------------------------------------------------------
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
puts "squawk!"
end
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.

View file

@ -116,9 +116,6 @@ ActiveRecord::Schema.define(:version => 0) do
t.string :last_tweet
t.datetime :last_tweeted_at
end
create_table :woodpeckers, :force => true do |t|
t.string :name
end
end
----------------------------------------------

View file

@ -0,0 +1,165 @@
== 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:
* A 'database.yml' file with all of your connection strings
* A 'schema.rb' file with your table definitions
* A test helper method that sets up the database
=== Test Setup ===
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
sqlite:
:adapter: sqlite
:dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: yaffle_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: root
: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:*
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
create_table :woodpeckers, :force => true do |t|
t.string :name
end
end
----------------------------------------------
*vendor/plugins/yaffle/test/test_helper.rb:*
[source, ruby]
----------------------------------------------
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
def load_schema
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../rails/init.rb'
end
----------------------------------------------
Now whenever you write a test that requires the database, you can call 'load_schema'.
=== Run the plugin tests ===
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:*
[source, ruby]
----------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
load_schema
class Hickwall < ActiveRecord::Base
end
class Wickwall < ActiveRecord::Base
end
def test_schema_has_loaded_correctly
assert_equal [], Hickwall.all
assert_equal [], Wickwall.all
end
end
----------------------------------------------
To run this, go to the plugin directory and run `rake`:
----------------------------------------------
cd vendor/plugins/yaffle
rake
----------------------------------------------
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"
-- create_table(:hickwalls, {:force=>true})
-> 0.0220s
-- create_table(:wickwalls, {:force=>true})
-> 0.0077s
-- initialize_schema_migrations_table()
-> 0.0007s
-- assume_migrated_upto_version(0)
-> 0.0007s
Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
Started
.
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:
----------------------------------------------
rake DB=sqlite
rake DB=sqlite3
rake DB=mysql
rake DB=postgresql
----------------------------------------------
Now you are ready to test-drive your plugin!