From 3b2b77baaef3c8b9a8794f4c37916adf27a4d63e Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Fri, 31 Oct 2008 11:15:12 +1030
Subject: Removed extra space from the array conditions section.
---
railties/doc/guides/source/finders.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 945b527e1d..2e6b368e3f 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -134,7 +134,7 @@ If you'd like to add conditions to your find, you could just specify them in the
=== Array Conditions ===
- Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
+Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
The reason for doing code like:
--
cgit v1.2.3
From ccd9ef158953e30e66a4da143314955cd64e71c8 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Wed, 12 Nov 2008 01:21:09 -0500
Subject: Updated preparation section of plugins guide
---
railties/doc/guides/html/creating_plugins.html | 92 ++++++++++------------
.../source/creating_plugins/odds_and_ends.txt | 21 ++---
.../guides/source/creating_plugins/preparation.txt | 47 +++++------
3 files changed, 75 insertions(+), 85 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 48d5f03687..349986c0d3 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -204,7 +204,7 @@ ul#navMain {
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.
+
+
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. Create the plugin
-
The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.
+
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.
For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that.
-
-
-
rm vendor/plugins/yaffle/lib/yaffle.rb
-
-
-
-
-
-
-
-
Editor's note:
Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be require "yaffle". If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
-
-
1.3. Setup the plugin for testing
-
Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.
+
In this guide you will learn how to test your plugin against multiple different 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:
@@ -464,7 +453,6 @@ A test helper that sets up the database before your tests.
-
For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
ENV['RAILS_ENV']='test'
ENV['RAILS_ROOT']||= File.dirname(__FILE__)+'/../../../..'require'test/unit'
@@ -522,7 +515,6 @@ ActiveRecord::Base= ENV['DB']
-# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=beginrequire'rubygems'
@@ -547,11 +539,9 @@ ActiveRecord::Baserequire File.dirname(__FILE__)+'/../init.rb'class Hickwall < ActiveRecord::Base
- acts_as_yaffle
endclass Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field =>:last_tweet,:yaffle_date_field =>:last_tweeted_at
end
@@ -1219,32 +1209,34 @@ ActionController::Routing
8.1. Work with init.rb
The plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.
-
If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
-
The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash:
+
If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in init.rb, and it makes the plugin more difficult to turn into a gem.
+
A better alternative is to reopen the class in a different file, and require that file from init.rb.
+
If you must reopen a class in init.rb, there are various techniques. One way is to use module_eval or class_eval:
Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:
+
vendor/plugins/yaffle/init.rb
-
-
# File: vendor/plugins/yaffle/init.rb
-
-Hash.class_eval do
- def is_a_special_hash?
- true
- end
-end
-
+
+
class::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+
8.2. 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:
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
index eb127f73ca..32da7ed7f3 100644
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -4,27 +4,30 @@
The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
-If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
+If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem.
-The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
+A better alternative is to reopen the class in a different file, and require that file from `init.rb`.
+
+If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`:
+
+*vendor/plugins/yaffle/init.rb*
[source, ruby]
---------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-class ::Hash
+Hash.class_eval do
def is_a_special_hash?
true
end
end
---------------------------------------------------
-OR you can use `module_eval` or `class_eval`:
+Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
----------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
+*vendor/plugins/yaffle/init.rb*
-Hash.class_eval do
+[source, ruby]
+---------------------------------------------------
+class ::Hash
def is_a_special_hash?
true
end
diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt
index 77e3a3561f..83717c7ac8 100644
--- a/railties/doc/guides/source/creating_plugins/preparation.txt
+++ b/railties/doc/guides/source/creating_plugins/preparation.txt
@@ -2,11 +2,12 @@
=== Create the basic app ===
-In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
+The examples in this guide require that you have a working rails application. To create a simple rails app execute:
------------------------------------------------
-rails plugin_demo
-cd plugin_demo
+gem install rails
+rails yaffle_guide
+cd yaffle_guide
script/generate scaffold bird name:string
rake db:migrate
script/server
@@ -14,25 +15,28 @@ 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.
-=== Create the plugin ===
+=== Generate the plugin skeleton ===
-The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
+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 BrowserFilters
-./script/generate plugin BrowserFilters --with-generator
+./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator
----------------------------------------------
-Later in the plugin we will create a generator, so go ahead and add 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
+./script/generate plugin yaffle --with-generator
----------------------------------------------
You should see the following output:
@@ -57,19 +61,10 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
-For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that.
-
-----------------------------------------------
-rm vendor/plugins/yaffle/lib/yaffle.rb
-----------------------------------------------
-
-.Editor's note:
-NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
-
=== Setup the plugin for testing ===
-Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.
+In this guide you will learn how to test your plugin against multiple different 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:
@@ -77,8 +72,6 @@ To setup your plugin to allow for easy testing you'll need to add 3 files:
* A 'schema.rb' file with your table definitions.
* A test helper that sets up the database before your tests.
-For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
-
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
@@ -105,7 +98,9 @@ mysql:
:database: yaffle_plugin_test
----------------------------------------------
-*vendor/plugins/yaffle/test/test_helper.rb:*
+For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
+
+*vendor/plugins/yaffle/test/schema.rb:*
[source, ruby]
----------------------------------------------
@@ -121,9 +116,12 @@ ActiveRecord::Schema.define(:version => 0) do
t.datetime :last_tweeted_at
end
end
+----------------------------------------------
-# File: vendor/plugins/yaffle/test/test_helper.rb
+*vendor/plugins/yaffle/test/test_helper.rb:*
+[source, ruby]
+----------------------------------------------
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
@@ -135,7 +133,6 @@ 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'
@@ -160,10 +157,8 @@ load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init.rb'
class Hickwall < ActiveRecord::Base
- acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
end
----------------------------------------------
--
cgit v1.2.3
From 6b143ab86f88cf9e0572352c9afec4936995b4a4 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Wed, 12 Nov 2008 01:33:53 -0500
Subject: Plugins Guide: added example of how to run tests, including how to
run with multiple databases
---
railties/doc/guides/html/creating_plugins.html | 54 ++++++++++++++++++++
.../guides/source/creating_plugins/preparation.txt | 58 ++++++++++++++++++++++
2 files changed, 112 insertions(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 349986c0d3..4c5f72c4d2 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -208,6 +208,8 @@ ul#navMain {
@@ -544,6 +546,58 @@ ActiveRecord::Baseclass Wickwall < ActiveRecord::Base
end
+
1.4. 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:
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:
diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt
index 83717c7ac8..dc9ef6bc29 100644
--- a/railties/doc/guides/source/creating_plugins/preparation.txt
+++ b/railties/doc/guides/source/creating_plugins/preparation.txt
@@ -162,3 +162,61 @@ end
class Wickwall < ActiveRecord::Base
end
----------------------------------------------
+
+=== 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
+
+ def test_active_record_classes_from_test_helper
+ assert_kind_of Hickwall, Hickwall.new
+ assert_kind_of Wickwall, Wickwall.new
+ 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!
--
cgit v1.2.3
From 7f24653e7a39da9eb85b282e929d0712b2f1c9b7 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Wed, 12 Nov 2008 01:48:02 -0500
Subject: Plugins guide: Cleanup the intro
---
railties/doc/guides/html/creating_plugins.html | 112 +++++++++------------
.../doc/guides/source/creating_plugins/index.txt | 88 +++++-----------
2 files changed, 74 insertions(+), 126 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 4c5f72c4d2..32bcab1359 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -267,113 +267,96 @@ ul#navMain {
The Basics of Creating Rails Plugins
-
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.
-
In this tutorial you will learn how to create a plugin that includes:
+
A Rails plugin is either an extension or a modification of the core framework. Plugins provide:
-Core Extensions - extending String with a to_squawk method:
+a way for developers to share bleeding-edge ideas without hurting the stable code base
-An acts_as_yaffle method for ActiveRecord models that adds a squawk method:
+a segmented architecture so that units of code can be fixed or updated on their own release schedule
-A view helper that will print out squawking info:
+an outlet for the core developers so that they don’t have to include every cool new feature under the sun
-
-
-
squawk_info_for(@hickwall)
-
+
+
After reading this guide you should be familiar with:
+
-A generator that creates a migration to add squawk columns to a model:
+Creating a plugin from scratch
-
-
-
script/generate yaffle hickwall
-
-A custom generator command:
+Writing and running tests for the plugin
-
-
-
class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
-
-A custom route method:
+Storing models, views, controllers, helpers and even other plugins in your plugins
+
This guide describes how to build a test-driven plugin that will:
-test your plugins.
+Extend core ruby classes like Hash and String
+
+
+
+
+Add methods to ActiveRecord::Base in the tradition of the acts_as plugins
+
+
+
+
+Add a view helper that can be used in erb templates
-work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins.
+Add a new generator that will generate a migration
-create documentation for your plugin.
+Add a custom generator command
-write custom Rake tasks in your plugin.
+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.
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:
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index f2ed6ed8bb..d3042f8d56 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -1,68 +1,32 @@
The Basics of Creating Rails Plugins
====================================
-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.
-
-In this tutorial you will learn how to create a plugin that includes:
-
- * Core Extensions - extending String with a `to_squawk` method:
-+
-[source, ruby]
--------------------------------------------
-# Anywhere
-"hello!".to_squawk # => "squawk! hello!"
--------------------------------------------
-
-* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method:
-+
-[source, ruby]
--------------------------------------------
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_sang_at
-end
-
-Hickwall.new.squawk("Hello World")
--------------------------------------------
-
-* A view helper that will print out squawking info:
-+
-[source, ruby]
--------------------------------------------
-squawk_info_for(@hickwall)
--------------------------------------------
-
-* A generator that creates a migration to add squawk columns to a model:
-+
--------------------------------------------
-script/generate yaffle hickwall
--------------------------------------------
-
-* A custom generator command:
-+
-[source, ruby]
--------------------------------------------
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
--------------------------------------------
-
-* A custom route method:
-+
-[source, ruby]
--------------------------------------------
-ActionController::Routing::Routes.draw do |map|
- map.yaffles
-end
--------------------------------------------
-
-In addition you'll learn how to:
-
- * test your plugins.
- * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins.
- * create documentation for your plugin.
- * write custom Rake tasks in your plugin.
+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
+ * a segmented architecture so that units of code can be fixed or updated on their own release schedule
+ * an outlet for the core developers so that they don’t have to include every cool new feature under the sun
+
+After reading this guide you should be familiar with:
+
+ * Creating a plugin from scratch
+ * Writing and running tests for the plugin
+ * Storing models, views, controllers, helpers and even other plugins in your plugins
+ * Writing generators
+ * Writing custom Rake tasks in your plugin
+ * Generating RDoc documentation for your plugin
+ * Avoiding common pitfalls with 'init.rb'
+
+This guide describes how to build a test-driven plugin that will:
+
+ * Extend core ruby classes like Hash and String
+ * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins
+ * Add a view helper that can be used in erb templates
+ * Add a new generator that will generate a migration
+ * Add a custom generator command
+ * 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.
include::preparation.txt[]
--
cgit v1.2.3
From 40bc386ed8cc403050292ab19428f1e467fa1737 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Wed, 12 Nov 2008 02:05:19 -0500
Subject: Plugin Guide: cleaned up file paths, made formatting more consistent
---
railties/doc/guides/html/creating_plugins.html | 142 +++++++++------------
.../source/creating_plugins/acts_as_yaffle.txt | 29 +++--
.../source/creating_plugins/custom_generator.txt | 14 +-
.../source/creating_plugins/custom_route.txt | 16 +--
.../creating_plugins/migration_generator.txt | 20 ++-
.../source/creating_plugins/odds_and_ends.txt | 4 +-
.../source/creating_plugins/string_to_squawk.txt | 21 ++-
.../guides/source/creating_plugins/view_helper.txt | 12 +-
8 files changed, 125 insertions(+), 133 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 32bcab1359..97e14965a5 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -605,14 +605,13 @@ Require that file from your init.rb.
Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is lib/core_ext.rb.
First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
require'test/unit'class CoreExtTest < Test::Unit::TestCase
# Replace this with your real tests.
@@ -622,15 +621,13 @@ http://www.gnu.org/software/src-highlite -->
end
Start off by removing the default test, and adding a require statement for your test helper.
require File.dirname(__FILE__)+'/test_helper.rb'class CoreExtTest < Test::Unit::TestCase
end
@@ -648,14 +645,13 @@ rake test
No tests were specified
Great - now you are ready to start development. The first thing we'll do is to add a method to String called to_squawk which will prefix the string with the word “squawk!”. The test will look something like this:
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 keep things clean, create a new test file called acts_as_yaffle_test.rb in your plugin's test directory and require your test helper.
One of the most common plugin patterns for acts_as_yaffle plugins is to structure your file like so:
+
vendor/plugins/lib/acts_as_yaffle.rb
end
Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
Note the use of write_attribute to write to the field in model.
+
+
+
+
+
+
+
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).
+
+
4. Create a squawk_info_for view helper
@@ -923,14 +920,13 @@ Write the tests.
First, create the test to define the functionality you want:
class AddYaffleFieldsToBirds < ActiveRecord::Migration
defself.up
add_column :birds,:last_squawk,:string
add_column :birds,:last_squawked_at,:datetime
@@ -1100,25 +1092,24 @@ Add the method to your generator.
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
ActionController::Routing::Routes.draw do|map|...
map.yaffles
end
@@ -1328,14 +1313,13 @@ http://www.gnu.org/software/src-highlite -->
8.4. 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
-
# File: vendor/plugins/yaffle/tasks/yaffle.rake
-
-namespace :yaffle do
+
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk =>:environment do
puts "squawk!"
diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
index 12d40deb18..06878543e4 100644
--- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -4,10 +4,10 @@ A common pattern in plugins is to add a method called `acts_as_something` to mod
To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
@@ -18,16 +18,18 @@ class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
+*vendor/plugins/lib/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/lib/acts_as_yaffle.rb
-
module Yaffle
end
------------------------------------------------------
One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
+*vendor/plugins/lib/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
module Yaffle
@@ -65,10 +67,10 @@ end
Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
@@ -92,10 +94,10 @@ end
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
+*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -117,10 +119,10 @@ end
Now you can add tests for the instance methods, and the instance method itself:
+*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
@@ -163,10 +165,10 @@ class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
+*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -190,4 +192,5 @@ module Yaffle
end
------------------------------------------------------
-Note the use of `write_attribute` to write to the field in model.
+.Editor's note:
+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)`.
diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt
index 6d9613ea01..a8cf1b48ce 100644
--- a/railties/doc/guides/source/creating_plugins/custom_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/custom_generator.txt
@@ -8,19 +8,20 @@ You may have noticed above that you can used one of the built-in rails migration
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
require "commands"
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
-----------------------------------------------------------
+*vendor/plugins/yaffle/lib/commands.rb*
+
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/commands.rb
-
require 'rails_generator'
require 'rails_generator/commands'
@@ -49,16 +50,15 @@ module Yaffle #:nodoc:
end
-----------------------------------------------------------
+*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-
Yaffle is a bird
-----------------------------------------------------------
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
+
[source, ruby]
-----------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt
index 7e399247ee..1fce902a4e 100644
--- a/railties/doc/guides/source/creating_plugins/custom_route.txt
+++ b/railties/doc/guides/source/creating_plugins/custom_route.txt
@@ -2,10 +2,10 @@
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*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/test/routing_test.rb
-
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
@@ -33,18 +33,18 @@ class RoutingTest < Test::Unit::TestCase
end
--------------------------------------------------------
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
+*vendor/plugins/yaffle/lib/routing.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/routing.rb
-
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
@@ -56,10 +56,10 @@ module Yaffle #:nodoc:
end
--------------------------------------------------------
+*config/routes.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: config/routes.rb
-
ActionController::Routing::Routes.draw do |map|
...
map.yaffles
diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
index 598a0c8437..1a477a69ab 100644
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt
@@ -6,11 +6,15 @@ We'll be relying on the built-in rails generate template for this tutorial. Goi
Type:
- script/generate
+------------------------------------------------------------------
+script/generate
+------------------------------------------------------------------
You should see the line:
- Plugins (vendor/plugins): yaffle
+------------------------------------------------------------------
+Plugins (vendor/plugins): yaffle
+------------------------------------------------------------------
When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
@@ -27,10 +31,10 @@ Example:
Now you can add code to your generator:
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
+
[source, ruby]
------------------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
@@ -67,14 +71,16 @@ This does a few things:
When you run the generator like
- script/generate yaffle bird
+------------------------------------------------------------------
+script/generate yaffle bird
+------------------------------------------------------------------
You will see a new file:
+*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
+
[source, ruby]
------------------------------------------------------------------
-# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
-
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
index 32da7ed7f3..88cd4fe9ed 100644
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -81,10 +81,10 @@ When you created the plugin with the built-in rails generator, it generated a ra
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]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/tasks/yaffle.rake
-
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
index 50516cef69..63f1131442 100644
--- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
+++ b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
@@ -10,10 +10,10 @@ Most plugins store their code classes in the plugin's lib directory. When you a
First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
+*vendor/plugins/yaffle/test/core_ext_test.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/test/core_ext_test.rb
-
require 'test/unit'
class CoreExtTest < Test::Unit::TestCase
@@ -26,11 +26,10 @@ end
Start off by removing the default test, and adding a require statement for your test helper.
+*vendor/plugins/yaffle/test/core_ext_test.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/test/core_ext_test.rb
-
-require 'test/unit'
require File.dirname(__FILE__) + '/test_helper.rb'
class CoreExtTest < Test::Unit::TestCase
@@ -53,10 +52,10 @@ No tests were specified
Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this:
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
class CoreExtTest < Test::Unit::TestCase
def test_string_should_respond_to_squawk
assert_equal true, "".respond_to?(:to_squawk)
@@ -72,17 +71,17 @@ class CoreExtTest < Test::Unit::TestCase
end
--------------------------------------------------------
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
require "core_ext"
--------------------------------------------------------
+*vendor/plugins/yaffle/lib/core_ext.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/core_ext.rb
-
String.class_eval do
def to_squawk
"squawk! #{self}".strip
diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt
index b03a190e1a..4eaec93824 100644
--- a/railties/doc/guides/source/creating_plugins/view_helper.txt
+++ b/railties/doc/guides/source/creating_plugins/view_helper.txt
@@ -8,10 +8,10 @@ Creating a view helper is a 3-step process:
First, create the test to define the functionality you want:
+*vendor/plugins/yaffle/test/view_helpers_test.rb*
+
[source, ruby]
---------------------------------------------------------------
-# File: vendor/plugins/yaffle/test/view_helpers_test.rb
-
require File.dirname(__FILE__) + '/test_helper.rb'
include YaffleViewHelper
@@ -28,20 +28,20 @@ end
Then add the following statements to init.rb:
+*vendor/plugins/yaffle/init.rb*
+
[source, ruby]
---------------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
require "view_helpers"
ActionView::Base.send :include, YaffleViewHelper
---------------------------------------------------------------
Then add the view helpers file and
+*vendor/plugins/yaffle/lib/view_helpers.rb*
+
[source, ruby]
---------------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/view_helpers.rb
-
module YaffleViewHelper
def squawk_info_for(yaffle)
returning "" do |result|
--
cgit v1.2.3
From 7f023b5e3bd62c1f91ee341c1af155c0953e693a Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Wed, 12 Nov 2008 21:45:42 +1030
Subject: Updated finders guide
---
railties/doc/guides/source/finders.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 2e6b368e3f..d26711fce2 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -120,7 +120,7 @@ To find all the clients you would simply type +Client.all+ and that would find a
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
# "Michael", locked: false, orders_count: 3,
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
--------------------------------------------------------
+-------------------------------------------------------
As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
--
cgit v1.2.3
From ff359af86505b4d317b7467e7f79aa2ef2c5e795 Mon Sep 17 00:00:00 2001
From: athonlab
Date: Thu, 13 Nov 2008 09:31:10 +0530
Subject: Rails testing guide revised based on feedback from Pratik and few
miscellaneous fixes. [#8]
---
.../guides/source/testing_rails_applications.txt | 390 +++++++++++++--------
1 file changed, 249 insertions(+), 141 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt
index 31b6fc2cfa..6cced2fdd1 100644
--- a/railties/doc/guides/source/testing_rails_applications.txt
+++ b/railties/doc/guides/source/testing_rails_applications.txt
@@ -11,18 +11,17 @@ This guide won't teach you to write a Rails application; it assumes basic famili
== Why Write Tests for your Rails Applications? ==
- * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
- * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
- * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
* Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+ * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
+ * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-== Before you Start Writing Tests ==
+== Introduction to Testing ==
-Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
=== The 3 Environments ===
-Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
@@ -55,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
==== What Are Fixtures? ====
-_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
+_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
-==== YAML the Camel is a Mammal with Enamel ====
+==== YAML ====
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
@@ -69,13 +68,11 @@ Here's a sample YAML fixture file:
---------------------------------------------
# low & behold! I am a YAML comment!
david:
- id: 1
name: David Heinemeier Hansson
birthday: 1979-10-15
profession: Systems development
steve:
- id: 2
name: Steve Ross Kellock
birthday: 1974-09-27
profession: guy with keyboard
@@ -83,55 +80,24 @@ steve:
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
-==== Comma Seperated ====
-
-Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
-
-A CSV fixture looks like this:
-
---------------------------------------------------------------
-id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
---------------------------------------------------------------
-
-The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
-
- * Leading and trailing spaces are trimmed from each value when it is imported
- * If you use a comma as data, the cell must be encased in quotes
- * If you use a quote as data, you must escape it with a 2nd quote
- * Don't use blank lines
- * Nulls can be defined by including no data between a pair of commas
-
-Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
-
-* +celebrity-holiday-figures-1+
-* +celebrity-holiday-figures-2+
-* +celebrity-holiday-figures-3+
-
-The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
-
==== ERb'in It Up ====
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
-I'll demonstrate with a YAML file:
-
[source, ruby]
--------------------------------------------------------------
<% earth_size = 20 -%>
mercury:
- id: 1
size: <%= earth_size / 50 %>
+ brightest_on: <%= 113.days.ago.to_s(:db) %>
venus:
- id: 2
size: <%= earth_size / 2 %>
+ brightest_on: <%= 67.days.ago.to_s(:db) %>
mars:
- id: 3
size: <%= earth_size - 69 %>
+ brightest_on: <%= 13.days.from_now.to_s(:db) %>
--------------------------------------------------------------
Anything encased within the
@@ -141,7 +107,7 @@ Anything encased within the
<% %>
------------------------
-tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
+tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
==== Fixtures in Action ====
@@ -164,9 +130,7 @@ users(:david)
users(:david).id
--------------------------------------------------------------
-But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!
-
-Now you can get at the methods only available to that class.
+Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
[source, ruby]
--------------------------------------------------------------
@@ -177,14 +141,18 @@ david = users(:david).find
email(david.girlfriend.email, david.location_tonight)
--------------------------------------------------------------
-== Unit Testing Your Models ==
+== Unit Testing your Models ==
In Rails, unit tests are what you write to test your models.
-When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
+For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
+
+NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
+
+When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
-------------------------------------------------------
-$ script/generate model Post
+$ script/generate scaffold post title:string body:text
...
create app/models/post.rb
create test/unit/post_test.rb
@@ -243,6 +211,36 @@ This line of code is called an _assertion_. An assertion is a line of code that
Every test contains one or more assertions. Only when all the assertions are successful the test passes.
+=== Preparing you Application for Testing ===
+
+Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
+
+[source, shell]
+-------------------------------------------------------
+$ rake db:migrate
+...
+$ rake db:test:load
+-------------------------------------------------------
+
+Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
+
+NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
+
+==== Rake Tasks for Preparing you Application for Testing ==
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+------------------------------------------------------------------------------------
+
+TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
+
=== Running Tests ===
Running a test is as simple as invoking the file containing the test cases through Ruby:
@@ -277,65 +275,90 @@ Finished in 0.023513 seconds.
The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary.
-To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
+To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save
end
--------------------------------------------------
-If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
+Let us run this newly added test.
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
- expected to not be nil.
+ is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors
-------------------------------------------------------
In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
[source,ruby]
--------------------------------------------------
-def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
+def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save, "Saved the post without a title"
end
--------------------------------------------------
Running this test shows the friendlier assertion message:
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
- expected to not be nil.
+Saved the post without a title.
+ is not true.
+
+1 tests, 1 assertions, 1 failures, 0 errors
+-------------------------------------------------------
+
+Now to get this test to pass we can add a model level validation for the _title_ field.
+
+[source,ruby]
+--------------------------------------------------
+class Post < ActiveRecord::Base
+ validates_presence_of :title
+end
+--------------------------------------------------
+
+Now the test should pass. Let us verify by running the test again:
+
+-------------------------------------------------------
+$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
+Loaded suite unit/post_test
+Started
+.
+Finished in 0.193608 seconds.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 0 failures, 0 errors
-------------------------------------------------------
+Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD).
+
+TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
+
To see how an error gets reported, here's a test containing an error:
[source,ruby]
@@ -350,29 +373,21 @@ end
Now you can see even more output in the console from running the tests:
-------------------------------------------------------
-$ ruby unit/post_test.rb
+$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
-
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
- expected to not be nil.
+E
+Finished in 0.195757 seconds.
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #
+NameError: undefined local variable or method `some_undefined_variable' for #
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
+1 tests, 0 assertions, 0 failures, 1 errors
-------------------------------------------------------
Notice the 'E' in the output. It denotes a test with error.
@@ -383,8 +398,6 @@ NOTE: The execution of each test method stops as soon as any error or a assertio
Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
-
=== Assertions Available ===
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
@@ -454,32 +467,9 @@ You should test for things such as:
* was the correct object stored in the response template?
* was the appropriate message displayed to the user in the view
-When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
-
-[source, shell]
--------------------------------------------------------
-$ script/generate controller post
-...
- create app/controllers/post_controller.rb
- create test/functional/post_controller_test.rb
-...
--------------------------------------------------------
-
-Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
-
-[source,ruby]
---------------------------------------------------
-require 'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
---------------------------------------------------
+Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
-Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
+Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
[source,ruby]
--------------------------------------------------
@@ -513,6 +503,23 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param
get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
--------------------------------------------------
+NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
+
+Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_create_post
+ assert_difference('Post.count') do
+ post :create, :post => { :title => 'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+--------------------------------------------------
+
+Now you can try running all the tests and they should pass.
+
=== Available Request Types for Functional Tests ===
If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
@@ -756,6 +763,130 @@ class UserFlowsTest < ActionController::IntegrationTest
end
--------------------------------------------------
+== Rake Tasks for Running your Tests ==
+
+You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+
+[grid="all"]
+--------------------------------`----------------------------------------------------
+Tasks Description
+------------------------------------------------------------------------------------
++rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
+------------------------------------------------------------------------------------
+
+
+== Brief Note About Test::Unit ==
+
+Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
+
+NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
+
+== Setup and Teardown ==
+
+If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
+
+[source,ruby]
+--------------------------------------------------
+require 'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post = posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+--------------------------------------------------
+
+Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
+
+ * a block
+ * a method (like in the earlier example)
+ * a method name as a symbol
+ * a lambda
+
+Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
+
+[source,ruby]
+--------------------------------------------------
+require '../test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post = nil
+ end
+
+ def test_should_show_post
+ get :show, :id => @post.id
+ assert_response :success
+ end
+
+ def test_should_update_post
+ put :update, :id => @post.id, :post => { }
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count', -1) do
+ delete :destroy, :id => @post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post = posts(:one)
+ end
+
+end
+--------------------------------------------------
+
+== Testing Routes ==
+
+Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
+
+[source,ruby]
+--------------------------------------------------
+def test_should_route_to_post
+ assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
+end
+--------------------------------------------------
+
== Testing Your Mailers ==
Testing mailer classes requires some specific tools to do a thorough job.
@@ -845,30 +976,6 @@ class UserControllerTest < ActionController::TestCase
end
----------------------------------------------------------------
-== Rake Tasks for Testing
-
-You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
-
-[grid="all"]
---------------------------------`----------------------------------------------------
-Tasks Description
-------------------------------------------------------------------------------------
-+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.
-------------------------------------------------------------------------------------
-
-TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
-
== Other Testing Approaches
The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
@@ -882,6 +989,7 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
+* November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
* October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
-* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
+* October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
--
cgit v1.2.3
From bc75de8e4f60a774423290872aeb25d09561531b Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Thu, 13 Nov 2008 00:51:54 -0500
Subject: Plugin Guide: updated core_extensions section
---
.../html/activerecord_validations_callbacks.html | 2 +-
railties/doc/guides/html/command_line.html | 434 +++++++++++++++++
railties/doc/guides/html/creating_plugins.html | 151 +++---
railties/doc/guides/html/routing_outside_in.html | 2 +-
.../guides/html/testing_rails_applications.html | 541 +++++++++++++--------
.../guides/source/creating_plugins/core_ext.txt | 126 +++++
.../doc/guides/source/creating_plugins/index.txt | 4 +-
.../source/creating_plugins/odds_and_ends.txt | 34 --
.../guides/source/creating_plugins/preparation.txt | 222 ---------
.../source/creating_plugins/string_to_squawk.txt | 102 ----
.../guides/source/creating_plugins/test_setup.txt | 222 +++++++++
11 files changed, 1191 insertions(+), 649 deletions(-)
create mode 100644 railties/doc/guides/html/command_line.html
create mode 100644 railties/doc/guides/source/creating_plugins/core_ext.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/preparation.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/string_to_squawk.txt
create mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index 45eec6ffa1..0aa507a9b9 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -726,7 +726,7 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
class Invoice < ActiveRecord::Base
- validate :expiration_date_cannot_be_in_the_past,:discount_cannot_be_be_more_than_total_value
+ validate :expiration_date_cannot_be_in_the_past,:discount_cannot_be_more_than_total_value
def expiration_date_cannot_be_in_the_past
errors.add(:expiration_date,"can't be in the past")if!expiration_date.blank? and expiration_date < Date.today
diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html
new file mode 100644
index 0000000000..2add20446e
--- /dev/null
+++ b/railties/doc/guides/html/command_line.html
@@ -0,0 +1,434 @@
+
+
+
+
+ A Guide to The Rails Command Line
+
+
+
+
+
+
+
+
+
+
+
+
+
Ruby on Rails
+
Sustainable productivity for web-application development
Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
+
+
+
+
+
+
This output will seem very familiar when we get to the generate command. Creepy foreshadowing!
+
+
+
1.2. server
+
Let's try it! The server command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.
+
+
+
+
+
+
WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section]
+
+
+
Here we'll flex our server command, which without any prodding of any kind will run our new shiny Rails app:
+
+
+
$ cd commandsapp
+$ ./script/server
+=> Booting WEBrick...
+=> Rails 2.2.0 application started on http://0.0.0.0:3000
+=> Ctrl-C to shutdown server; call with --help for options
+[2008-11-0410:11:38] INFO WEBrick 1.3.1
+[2008-11-0410:11:38] INFO ruby 1.8.5(2006-12-04)[i486-linux]
+[2008-11-0410:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
+
+
WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
+
See? Cool! It doesn't do much yet, but we'll change that.
+
1.3. generate
+
The generate command uses templates to create a whole lot of things. You can always find out what's available by running generate by itself. Let's do that:
You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
+
+
+
Using generators will save you a large amount of time by writing boilerplate code for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
+
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
+
+
+
+
+
+
All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like rails or ./script/generate). For others, you can try adding —help or -h to the end, as in ./script/server —help.
Ah, the controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let's make a Greetings controller with an action of hello, which will say something nice to us.
Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command!
This section will explain how to add a method to String that will be available anywhere in your rails app by:
-Write tests for the desired functionality.
-
-
-
-
-Create a file for the code you wish to use.
+Writing tests for the desired behavior
-Require that file from your init.rb.
+Creating and requiring the correct files
-
Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is lib/core_ext.rb.
-
First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
-
vendor/plugins/yaffle/test/core_ext_test.rb
+
2.1. Working with init.rb
+
When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 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 itself, 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.
+
If you must reopen a class in init.rb you can use module_eval or class_eval:
+
vendor/plugins/yaffle/init.rb
-
require'test/unit'
-
-class CoreExtTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk
+
Hash.class_eval do
+ def is_a_special_hash?
+ trueendend
-
Start off by removing the default test, and adding a require statement for your test helper.
+
Another way is to explicitly define the top-level module space for all modules and classes, like ::Hash:
+
vendor/plugins/yaffle/init.rb
+
+
+
class::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+
+
2.2. Creating the test
+
In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:
Your test should fail with no such file to load — ./test/../lib/core_ext.rb (LoadError) because we haven't created any file yet. Create the file lib/core_ext.rb and re-run the tests. You should see a different error message:
Great - now you are ready to start development. The first thing we'll do is to add a method to String called to_squawk which will prefix the string with the word “squawk!”. The test will look something like this:
+
Great - now you are ready to start development.
+
2.3. Organize your files
+
A common pattern in rails plugins is to set up the file structure something like this:
The first thing we need to to is to require our lib/yaffle.rb file from init.rb:
vendor/plugins/yaffle/init.rb
-
class CoreExtTest < Test::Unit::TestCase
- def test_string_should_respond_to_squawk
- assert_equal true,"".respond_to?(:to_squawk)
- end
-
- def test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal "squawk!","".to_squawk
- end
-
- def test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal "squawk! Hello World","Hello World".to_squawk
- end
-end
+
require'yaffle'
-
vendor/plugins/yaffle/init.rb
+
Then in lib/yaffle.rb require lib/core_ext.rb:
+
vendor/plugins/yaffle/lib/yaffle.rb
-
require"core_ext"
+
require"yaffle/core_ext"
-
vendor/plugins/yaffle/lib/core_ext.rb
+
Finally, create the core_ext.rb file and add the to_squawk method:
+
vendor/plugins/yaffle/lib/yaffle/core_ext.rb
endend
-
When monkey-patching existing classes it's often better to use class_eval instead of opening the class directly.
-
To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
+
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:
The plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.
-
If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in init.rb, and it makes the plugin more difficult to turn into a gem.
-
A better alternative is to reopen the class in a different file, and require that file from init.rb.
-
If you must reopen a class in init.rb, there are various techniques. One way is to use module_eval or class_eval:
-
vendor/plugins/yaffle/init.rb
-
-
-
Hash.class_eval do
- 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/init.rb
-
-
-
class::Hash
- def is_a_special_hash?
- true
- end
-end
-
-
8.2. Generate RDoc Documentation
+
8.1. 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:
@@ -1292,7 +1281,7 @@ Warning, gotchas or tips that might help save users time.
rake rdoc
-
8.3. Store models, views, helpers, and controllers in your plugins
+
8.2. Store models, views, helpers, and controllers in your plugins
You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
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.
Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
8.4. Write custom Rake tasks in your plugin
+
8.3. 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:
8.6. Create your own Plugin Loaders and Plugin Locators
+
8.5. 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.
@@ -309,12 +320,7 @@ Identify other popular testing approaches and plugins
-Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
-
-
-
-
-Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
+Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
@@ -324,16 +330,16 @@ By simply running your Rails tests you can ensure your code adheres to the desir
-Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
+Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
-
2. Before you Start Writing Tests
+
2. Introduction to Testing
-
Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
+
Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
2.1. The 3 Environments
-
Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
+
Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
One place you'll find this distinction is in the config/database.yml file. This YAML configuration file has 3 different sections defining 3 unique database setups:
@@ -370,9 +376,9 @@ fixtures/ functional2.3. The Low-Down on Fixtures
For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.
2.3.1. What Are Fixtures?
-
Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV.
+
Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV. In this guide we will use YAML which is the preferred format.
You'll find fixtures under your test/fixtures directory. When you run script/generate model to create a new model, fixture stubs will be automatically created and placed in this directory.
-
2.3.2. YAML the Camel is a Mammal with Enamel
+
2.3.2. YAML
YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the .yml file extension (as in users.yml).
# low & behold! I am a YAML comment!
david:
- id:1
name: David Heinemeier Hansson
birthday:1979-10-15
profession: Systems development
steve:
- id:2
name: Steve Ross Kellock
birthday:1974-09-27
profession: guy with keyboard
Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
-
2.3.3. Comma Seperated
-
Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the test/fixtures directory, but these end with the .csv file extension (as in celebrity_holiday_figures.csv).
-
A CSV fixture looks like this:
-
-
-
id, username, password, stretchable, comments
-1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
-2, ebunny, ihateeggs, true, Hoppity hop y'all
-3, tfairy, ilovecavities, true, "Pull your teeth, I will"
-
-
The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
-
-
-
-Leading and trailing spaces are trimmed from each value when it is imported
-
-
-
-
-If you use a comma as data, the cell must be encased in quotes
-
-
-
-
-If you use a quote as data, you must escape it with a 2nd quote
-
-
-
-
-Don't use blank lines
-
-
-
-
-Nulls can be defined by including no data between a pair of commas
-
-
-
-
Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
-
-
-
-celebrity-holiday-figures-1
-
-
-
-
-celebrity-holiday-figures-2
-
-
-
-
-celebrity-holiday-figures-3
-
-
-
-
The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
-
2.3.4. ERb'in It Up
+
2.3.3. ERb'in It Up
ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
-
2.3.5. Fixtures in Action
+
tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The brightest_on attribute will also be evaluated and formatted by Rails to be compatible with the database.
+
2.3.4. Fixtures in Action
Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:
@@ -500,7 +446,7 @@ Dump the fixture data into a variable in case you want to access it directly
-
2.3.6. Hashes with Special Powers
+
2.3.5. Hashes with Special Powers
Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:
+
$ rake db:migrate
+...
+$ rake db:test:load
+
+
Above rake db:migrate runs any pending migrations on the developemnt environment and updates db/schema.rb. rake db:test:load recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run db:test:prepare as it first checks for pending migrations and warns you appropriately.
+
+
+
+
+
+
db:test:prepare will fail with an error if db/schema.rb doesn't exists.
+
+
+
3.1.1. Rake Tasks for Preparing you Application for Testing ==
+rake db:test:clone+ Recreate the test database from the current environment's database schema
++rake db:test:clone_structure+ Recreate the test databases from the development structure
++rake db:test:load+ Recreate the test database from the current +schema.rb+
++rake db:test:prepare+ Check for pending migrations and load the test schema
++rake db:test:purge+ Empty the test database.
+
+
+
+
+
+
+
You can see all these rake tasks and their descriptions by running rake —tasks —describe
+
+
+
3.2. Running Tests
Running a test is as simple as invoking the file containing the test cases through Ruby:
-
def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post
+
def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save
end
-
If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
+
Let us run this newly added test.
-
$ ruby unit/post_test.rb
+
$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.027274 seconds.
+F
+Finished in 0.197094 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-<nil> expected to not be nil.
+<false> is not true.
-2 tests, 2 assertions, 1 failures, 0 errors
+1 tests, 1 assertions, 1 failures, 0 errors
In the output, F denotes a failure. You can see the corresponding trace shown under 1) along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
@@ -677,30 +670,60 @@ test_should_have_atleast_one_post(PostTest)
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-
def test_should_have_atleast_one_post
- post = Post.find(:first)
- assert_not_nil post,"Should not be nil as Posts table should have atleast one post"
+
def test_should_not_save_post_without_title
+ post = Post.new
+ assert !post.save,"Saved the post without a title"end
Running this test shows the friendlier assertion message:
-
$ ruby unit/post_test.rb
+
$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
Loaded suite unit/post_test
Started
-F.
-Finished in 0.024727 seconds.
+F
+Finished in 0.198093 seconds.
1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
+test_should_not_save_post_without_title(PostTest)
+ [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
+Saved the post without a title.
+<false> is not true.
+
+1 tests, 1 assertions, 1 failures, 0 errors
+
+
Now to get this test to pass we can add a model level validation for the title field.
+
+
+
class Post < ActiveRecord::Base
+ validates_presence_of :title
+end
+
+
Now the test should pass. Let us verify by running the test again:
Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as Test-Driven Development (TDD).
+
+
+
+
+
+
Many Rails developers practice Test-Driven Development (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with 15 TDD steps to create a Rails application.
+
+
To see how an error gets reported, here's a test containing an error:
Now you can see even more output in the console from running the tests:
-
$ ruby unit/post_test.rb
+
$ ruby unit/post_test.rb -n test_should_report_error
Loaded suite unit/post_test
Started
-FE.
-Finished in 0.108389 seconds.
+E
+Finished in 0.195757 seconds.
- 1) Failure:
-test_should_have_atleast_one_post(PostTest)
- [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
- /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
-Should not be nil as Posts table should have atleast one post.
-<nil> expected to not be nil.
-
- 2) Error:
+ 1) Error:
test_should_report_error(PostTest):
-NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
+NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
/opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
- unit/post_test.rb:15:in `test_should_report_error'
+ unit/post_test.rb:16:in `test_should_report_error'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
/opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
-3 tests, 2 assertions, 1 failures, 1 errors
+1 tests, 0 assertions, 0 failures, 1 errors
Notice the E in the output. It denotes a test with error.
@@ -749,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #<
The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
-
3.2. What to Include in Your Unit Tests
+
3.3. What to Include in Your Unit Tests
Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
-
-
-
-
-
-
Many Rails developers practice test-driven development (TDD), in which the tests are written before the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with 15 TDD steps to create a Rails application.
-
-
-
3.3. Assertions Available
+
3.4. Assertions Available
By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit, the testing library used by Rails. The [msg] parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.
Creating your own assertions is an advanced topic that we won't cover in this tutorial.
-
3.4. Rails Specific Assertions
+
3.5. Rails Specific Assertions
Rails adds some custom assertions of its own to the test/unit framework:
-
When you use script/generate to create a controller, it automatically creates a functional test for that controller in test/functional. For example, if you create a post controller:
Now if you take a look at the file posts_controller_test.rb in the test/functional directory, you should see:
-
-
-
require'test_helper'
-
-class PostsControllerTest < ActionController::TestCase
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
-
-
Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
+
Now that we have used Rails scaffold generator for our Post resource, it has already created the controller code and functional tests. You can take look at the file posts_controller_test.rb in the test/functional directory.
+
Let me take you through one such test, test_should_get_index from the file posts_controller_test.rb.
get(:view,{'id'=>'12'},nil,{'message'=>'booya!'})
+
+
+
+
+
+
If you try running test_should_create_post test from posts_controller_test.rb it will fail on account of the newly added model level validation and rightly so.
+
+
+
Let us modify test_should_create_post test in posts_controller_test.rb so that all our test pass:
+
+
+
def test_should_create_post
+ assert_difference('Post.count')do
+ post :create,:post =>{:title =>'Some title'}
+ end
+
+ assert_redirected_to post_path(assigns(:post))
+end
+
+
Now you can try running all the tests and they should pass.
4.2. Available Request Types for Functional Tests
If you're familiar with the HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails functional tests:
@@ -1564,10 +1568,159 @@ http://www.gnu.org/software/src-highlite -->
end
-
6. Testing Your Mailers
+
6. Rake Tasks for Running your Tests
+
+
You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
++rake test:units+ Runs all the unit tests from +test/unit+
++rake test:functionals+ Runs all the functional tests from +test/functional+
++rake test:integration+ Runs all the integration tests from +test/integration+
++rake test:recent+ Tests recent changes
++rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
++rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
+
+
+
7. Brief Note About Test::Unit
+
+
Ruby ships with a boat load of libraries. One little gem of a library is Test::Unit, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in Test::Unit::Assertions. The class ActiveSupport::TestCase which we have been using in our unit and functional tests extends Test::Unit::TestCase that it is how we can use all the basic assertions in our tests.
If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in Posts controller:
+
+
+
require'test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ def setup
+ @post= posts(:one)
+ end
+
+ # called after every single test
+ def teardown
+ # as we are re-initializing @post before every test
+ # setting it to nil here is not essential but I hope
+ # you understand how you can use the teardown method
+ @post=nil
+ end
+
+ def test_should_show_post
+ get :show,:id =>@post.id
+ assert_response :success
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count',-1)do
+ delete :destroy,:id =>@post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+end
+
+
Above, the setup method is called before each test and so @post is available for each of the tests. Rails implements setup and teardown as ActiveSupport::Callbacks. Which essentially means you need not only use setup and teardown as methods in your tests. You could specify them by using:
+
+
+
+a block
+
+
+
+
+a method (like in the earlier example)
+
+
+
+
+a method name as a symbol
+
+
+
+
+a lambda
+
+
+
+
Let's see the earlier example by specifying setup callback by specifying a method name as a symbol:
+
+
+
require'../test_helper'
+
+class PostsControllerTest < ActionController::TestCase
+
+ # called before every single test
+ setup :initialize_post
+
+ # called after every single test
+ def teardown
+ @post=nil
+ end
+
+ def test_should_show_post
+ get :show,:id =>@post.id
+ assert_response :success
+ end
+
+ def test_should_update_post
+ put :update,:id =>@post.id,:post =>{}
+ assert_redirected_to post_path(assigns(:post))
+ end
+
+ def test_should_destroy_post
+ assert_difference('Post.count',-1)do
+ delete :destroy,:id =>@post.id
+ end
+
+ assert_redirected_to posts_path
+ end
+
+ private
+
+ def initialize_post
+ @post= posts(:one)
+ end
+
+end
+
+
+
9. Testing Routes
+
+
Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default show action of Posts controller above should look like:
Testing mailer classes requires some specific tools to do a thorough job.
-
6.1. Keeping the Postman in Check
+
10.1. Keeping the Postman in Check
Your ActionMailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.
The goals of testing your ActionMailer classes are to ensure that:
@@ -1587,14 +1740,14 @@ the right emails are being sent at the right times
-
6.1.1. From All Sides
+
10.1.1. From All Sides
There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture — yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.
-
6.2. Unit Testing
+
10.2. Unit Testing
In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.
-
6.2.1. Revenge of the Fixtures
+
10.2.1. Revenge of the Fixtures
For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output should look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within test/fixtures directly corresponds to the name of the mailer. So, for a mailer named UserMailer, the fixtures should reside in test/fixtures/user_mailer directory.
When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.
-
6.2.2. The Basic Test case
+
10.2.2. The Basic Test case
Here's a unit test to test a mailer named UserMailer whose action invite is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an invite action.
end
-
7. Rake Tasks for Testing
-
-
You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
+rake test+ Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
-+rake test:units+ Runs all the unit tests from +test/unit+
-+rake test:functionals+ Runs all the functional tests from +test/functional+
-+rake test:integration+ Runs all the integration tests from +test/integration+
-+rake test:recent+ Tests recent changes
-+rake test:uncommitted+ Runs all the tests which are uncommitted. Only supports Subversion
-+rake test:plugins+ Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
-+rake db:test:clone+ Recreate the test database from the current environment's database schema
-+rake db:test:clone_structure+ Recreate the test databases from the development structure
-+rake db:test:load+ Recreate the test database from the current +schema.rb+
-+rake db:test:prepare+ Check for pending migrations and load the test schema
-+rake db:test:purge+ Empty the test database.
-
-
-
-
-
-
-
You can see all these rake task and their descriptions by running rake —tasks —describe
-
-
-
-
8. Other Testing Approaches
+
11. Other Testing Approaches
The built-in test/unit based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
@@ -1707,18 +1831,23 @@ link: RSpec, a behavior-driven development fram
+November 13, 2008: Revised based on feedback from Pratik Naik by Akshay Surve (not yet approved for publication)
+
+
+
+
October 14, 2008: Edit and formatting pass by Mike Gunderloy (not yet approved for publication)
-October 12, 2008: First draft by Akashay Surve (not yet approved for publication)
+October 12, 2008: First draft by Akshay Surve (not yet approved for publication)
diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
new file mode 100644
index 0000000000..33d3dc8ce7
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -0,0 +1,126 @@
+== 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
+
+
+=== Working with init.rb ===
+
+When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script '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' itself, 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`.
+
+If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`:
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+Hash.class_eval do
+ 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/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+class ::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
+
+=== Creating the test ===
+
+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*
+
+[source, ruby]
+--------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class CoreExtTest < Test::Unit::TestCase
+ 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`:
+
+--------------------------------------------------------
+cd vendor/plugins/yaffle
+rake test
+--------------------------------------------------------
+
+The test above should fail with the message:
+
+--------------------------------------------------------
+ 1) Error:
+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.
+
+=== Organize your files ===
+
+A common pattern in rails plugins is to set up the file structure something like this:
+
+--------------------------------------------------------
+|-- init.rb
+|-- lib
+| |-- yaffle
+| | `-- core_ext.rb
+| `-- yaffle.rb
+--------------------------------------------------------
+
+The first thing we need to to is to require our 'lib/yaffle.rb' file from 'init.rb':
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require 'yaffle'
+--------------------------------------------------------
+
+Then in 'lib/yaffle.rb' require 'lib/core_ext.rb':
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+--------------------------------------------------------
+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*
+
+[source, ruby]
+--------------------------------------------------------
+String.class_eval do
+ 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:
+
+--------------------------------------------------------
+$ ./script/console
+>> "Hello World".to_squawk
+=> "squawk! Hello World"
+--------------------------------------------------------
+
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index d3042f8d56..91d7027323 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -29,9 +29,9 @@ 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::preparation.txt[]
+include::test_setup.txt[]
-include::string_to_squawk.txt[]
+include::core_ext.txt[]
include::acts_as_yaffle.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
index 88cd4fe9ed..a52e1c8fdb 100644
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -1,39 +1,5 @@
== Odds and ends ==
-=== Work with init.rb ===
-
-The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
-
-If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem.
-
-A better alternative is to reopen the class in a different file, and require that file from `init.rb`.
-
-If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`:
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
----------------------------------------------------
-Hash.class_eval do
- 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/init.rb*
-
-[source, ruby]
----------------------------------------------------
-class ::Hash
- def is_a_special_hash?
- true
- end
-end
----------------------------------------------------
-
=== 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.
diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt
deleted file mode 100644
index dc9ef6bc29..0000000000
--- a/railties/doc/guides/source/creating_plugins/preparation.txt
+++ /dev/null
@@ -1,222 +0,0 @@
-== Preparation ==
-
-=== 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
-----------------------------------------------
-
-
-=== Setup the plugin for testing ===
-
-In this guide you will learn how to test your plugin against multiple different 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:
-
- * A 'database.yml' file with all of your connection strings.
- * A 'schema.rb' file with your table definitions.
- * A test helper that sets up the database before your tests.
-
-*vendor/plugins/yaffle/test/database.yml:*
-
-----------------------------------------------
-sqlite:
- :adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
-
-sqlite3:
- :adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
-
-postgresql:
- :adapter: postgresql
- :username: postgres
- :password: postgres
- :database: yaffle_plugin_test
- :min_messages: ERROR
-
-mysql:
- :adapter: mysql
- :host: localhost
- :username: rails
- :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
-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'))
-
-config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
-ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
-
-db_adapter = ENV['DB']
-
-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__) + '/../init.rb'
-
-class Hickwall < ActiveRecord::Base
-end
-
-class Wickwall < ActiveRecord::Base
-end
-----------------------------------------------
-
-=== 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
-
- def test_active_record_classes_from_test_helper
- assert_kind_of Hickwall, Hickwall.new
- assert_kind_of Wickwall, Wickwall.new
- 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!
diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
deleted file mode 100644
index 63f1131442..0000000000
--- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
+++ /dev/null
@@ -1,102 +0,0 @@
-== Add a `to_squawk` method to String ==
-
-To update a core class you will have to:
-
- * Write tests for the desired functionality.
- * Create a file for the code you wish to use.
- * Require that file from your 'init.rb'.
-
-Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'.
-
-First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
-
-*vendor/plugins/yaffle/test/core_ext_test.rb*
-
-[source, ruby]
---------------------------------------------------------
-require 'test/unit'
-
-class CoreExtTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk
- end
-end
---------------------------------------------------------
-
-Start off by removing the default test, and adding a require statement for your test helper.
-
-*vendor/plugins/yaffle/test/core_ext_test.rb*
-
-[source, ruby]
---------------------------------------------------------
-require File.dirname(__FILE__) + '/test_helper.rb'
-
-class CoreExtTest < Test::Unit::TestCase
-end
---------------------------------------------------------
-
-Navigate to your plugin directory and run `rake test`:
-
---------------------------------------------------------
-cd vendor/plugins/yaffle
-rake test
---------------------------------------------------------
-
-Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message:
-
---------------------------------------------------------
-1.) Failure ...
-No tests were specified
---------------------------------------------------------
-
-Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this:
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
---------------------------------------------------------
-class CoreExtTest < Test::Unit::TestCase
- def test_string_should_respond_to_squawk
- assert_equal true, "".respond_to?(:to_squawk)
- end
-
- def test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal "squawk!", "".to_squawk
- end
-
- def test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal "squawk! Hello World", "Hello World".to_squawk
- end
-end
---------------------------------------------------------
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
---------------------------------------------------------
-require "core_ext"
---------------------------------------------------------
-
-*vendor/plugins/yaffle/lib/core_ext.rb*
-
-[source, ruby]
---------------------------------------------------------
-String.class_eval do
- def to_squawk
- "squawk! #{self}".strip
- end
-end
---------------------------------------------------------
-
-When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
-
-To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
-
---------------------------------------------------------
-$ ./script/console
->> "Hello World".to_squawk
-=> "squawk! Hello World"
---------------------------------------------------------
-
-If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
new file mode 100644
index 0000000000..dc9ef6bc29
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -0,0 +1,222 @@
+== Preparation ==
+
+=== 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
+----------------------------------------------
+
+
+=== Setup the plugin for testing ===
+
+In this guide you will learn how to test your plugin against multiple different 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:
+
+ * A 'database.yml' file with all of your connection strings.
+ * A 'schema.rb' file with your table definitions.
+ * A test helper that sets up the database before your tests.
+
+*vendor/plugins/yaffle/test/database.yml:*
+
+----------------------------------------------
+sqlite:
+ :adapter: sqlite
+ :dbfile: yaffle_plugin.sqlite.db
+
+sqlite3:
+ :adapter: sqlite3
+ :dbfile: yaffle_plugin.sqlite3.db
+
+postgresql:
+ :adapter: postgresql
+ :username: postgres
+ :password: postgres
+ :database: yaffle_plugin_test
+ :min_messages: ERROR
+
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: rails
+ :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
+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'))
+
+config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+
+db_adapter = ENV['DB']
+
+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__) + '/../init.rb'
+
+class Hickwall < ActiveRecord::Base
+end
+
+class Wickwall < ActiveRecord::Base
+end
+----------------------------------------------
+
+=== 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
+
+ def test_active_record_classes_from_test_helper
+ assert_kind_of Hickwall, Hickwall.new
+ assert_kind_of Wickwall, Wickwall.new
+ 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!
--
cgit v1.2.3
From 41d0dbcb8661a866ddf4b3534b8b1efd724ecba1 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Thu, 13 Nov 2008 01:44:34 -0500
Subject: Plugin guide: update acts_as section
---
railties/doc/guides/html/creating_plugins.html | 207 ++++++++++-----------
.../source/creating_plugins/acts_as_yaffle.txt | 121 ++++++------
.../guides/source/creating_plugins/core_ext.txt | 66 ++++---
.../guides/source/creating_plugins/test_setup.txt | 18 +-
4 files changed, 197 insertions(+), 215 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index bbb4719b0f..793cd2b7a7 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -216,16 +216,23 @@ ul#navMain {
Extending core classes
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:
@@ -548,9 +549,15 @@ http://www.gnu.org/software/src-highlite -->
class YaffleTest < Test::Unit::TestCase
- def test_active_record_classes_from_test_helper
- assert_kind_of Hickwall, Hickwall.new
- assert_kind_of Wickwall, Wickwall.new
+ class Hickwall < ActiveRecord::Base
+ end
+
+ class Wickwall < ActiveRecord::Base
+ end
+
+ def test_schema_has_loaded_correctly
+ assert_equal [], Hickwall.all
+ assert_equal [], Wickwall.all
endend
@@ -605,36 +612,7 @@ Creating and requiring the correct files
-
2.1. Working with init.rb
-
When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 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 itself, 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.
-
If you must reopen a class in init.rb you can use module_eval or class_eval:
-
vendor/plugins/yaffle/init.rb
-
-
-
Hash.class_eval do
- 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/init.rb
-
-
-
class::Hash
- def is_a_special_hash?
- true
- end
-end
-
-
2.2. Creating the test
+
2.1. Creating the test
In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:
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:
+
vendor/plugins/yaffle/init.rb
+
+
+
Hash.class_eval do
+ 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/init.rb
+
+
+
class::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+
-
3. Add an acts_as_yaffle method to ActiveRecord
+
3. Add an acts_as_yaffle 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 keep things clean, create a new test file called acts_as_yaffle_test.rb in your plugin's test directory and require your test helper.
+
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 Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
-
class ActsAsYaffleTest < Test::Unit::TestCase
end
One of the most common plugin patterns for acts_as_yaffle plugins is to structure your file like so:
-
vendor/plugins/lib/acts_as_yaffle.rb
+
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:
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).
-
Let's add class method named acts_as_yaffle - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
-
Back in your acts_as_yaffle file, update ClassMethods like so:
Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
+
3.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:
Now you can add tests for the instance methods, and the instance method itself:
+
3.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:
diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
index 06878543e4..41ffa61537 100644
--- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -1,8 +1,8 @@
-== Add an `acts_as_yaffle` method to ActiveRecord ==
+== Add an `acts_as_yaffle` 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.
+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 keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
+To begin, set up your files so that you have:
*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
@@ -10,25 +10,31 @@ To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in
------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
-class Hickwall < ActiveRecord::Base
- acts_as_yaffle
-end
-
class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
-*vendor/plugins/lib/acts_as_yaffle.rb*
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+------------------------------------------------------
+require 'yaffle/acts_as_yaffle'
+------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
module Yaffle
+ # your code will go here
end
------------------------------------------------------
-One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
+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/lib/acts_as_yaffle.rb*
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
@@ -52,20 +58,11 @@ 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`).
-Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
+=== Add a class method ===
-Back in your `acts_as_yaffle` file, update ClassMethods like so:
+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'.
-[source, ruby]
-------------------------------------------------------
-module ClassMethods
- def acts_as_yaffle(options = {})
- send :include, InstanceMethods
- end
-end
-------------------------------------------------------
-
-Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
+To start out, write a failing test that shows the behavior you'd like:
*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
@@ -73,28 +70,28 @@ Now that test should pass. Since your plugin is going to work with field names,
------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
-
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
-
- def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
end
------------------------------------------------------
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
-*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
+*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
@@ -105,19 +102,20 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
+ cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
end
end
-
- module InstanceMethods
- end
end
+
+ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
-Now you can add tests for the instance methods, and the instance method itself:
+=== 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*
@@ -125,47 +123,40 @@ Now you can add tests for the instance methods, and the instance method itself:
------------------------------------------------------
require File.dirname(__FILE__) + '/test_helper.rb'
-class ActsAsYaffleTest < Test::Unit::TestCase
+class Hickwall < ActiveRecord::Base
+ acts_as_yaffle
+end
+
+class Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+end
+class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
- def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
+ def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
- def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
-
+
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
- end
- def test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal Date.today, hickwall.last_squawked_at
- end
-
- def test_wickwalls_squawk_should_populate_last_tweet
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
+ end
+
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
- assert_equal Date.today, wickwall.last_tweeted_at
- end
+ assert_equal "squawk! Hello World", wickwall.last_tweet
+ end
end
------------------------------------------------------
-*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
+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*
[source, ruby]
------------------------------------------------------
@@ -176,9 +167,8 @@ module Yaffle
module ClassMethods
def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
+ cattr_accessor :yaffle_text_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
@@ -186,10 +176,11 @@ module Yaffle
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
- write_attribute(self.class.yaffle_date_field, Date.today)
end
end
end
+
+ActiveRecord::Base.send :include, Yaffle
------------------------------------------------------
.Editor's note:
diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
index 33d3dc8ce7..9bb7691b83 100644
--- a/railties/doc/guides/source/creating_plugins/core_ext.txt
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -5,39 +5,6 @@ This section will explain how to add a method to String that will be available a
* Writing tests for the desired behavior
* Creating and requiring the correct files
-
-=== Working with init.rb ===
-
-When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script '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' itself, 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`.
-
-If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`:
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
----------------------------------------------------
-Hash.class_eval do
- 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/init.rb*
-
-[source, ruby]
----------------------------------------------------
-class ::Hash
- def is_a_special_hash?
- true
- end
-end
----------------------------------------------------
-
=== Creating the test ===
In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
@@ -75,7 +42,7 @@ Great - now you are ready to start development.
=== Organize your files ===
-A common pattern in rails plugins is to set up the file structure something like this:
+A common pattern in rails plugins is to set up the file structure like this:
--------------------------------------------------------
|-- init.rb
@@ -124,3 +91,34 @@ $ ./script/console
=> "squawk! Hello World"
--------------------------------------------------------
+=== 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.
+
+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*
+
+[source, ruby]
+---------------------------------------------------
+Hash.class_eval do
+ 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/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+class ::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
index dc9ef6bc29..583d058494 100644
--- a/railties/doc/guides/source/creating_plugins/test_setup.txt
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -155,12 +155,6 @@ ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init.rb'
-
-class Hickwall < ActiveRecord::Base
-end
-
-class Wickwall < ActiveRecord::Base
-end
----------------------------------------------
=== Run the plugin tests ===
@@ -175,9 +169,15 @@ require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
- def test_active_record_classes_from_test_helper
- assert_kind_of Hickwall, Hickwall.new
- assert_kind_of Wickwall, Wickwall.new
+ 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
--
cgit v1.2.3
From 4146efc380255319768031f26e63210fd4158e99 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Thu, 13 Nov 2008 23:29:46 -0500
Subject: Plugin guide: update generator guide to include tests
---
railties/doc/guides/html/creating_plugins.html | 231 ++++--
.../source/creating_plugins/acts_as_yaffle.txt | 4 +
.../guides/source/creating_plugins/basics.markdown | 861 ---------------------
.../creating_plugins/migration_generator.txt | 120 ++-
.../guides/source/creating_plugins/test_setup.txt | 58 +-
5 files changed, 289 insertions(+), 985 deletions(-)
delete mode 100644 railties/doc/guides/source/creating_plugins/basics.markdown
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 793cd2b7a7..5589971ec5 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -239,6 +239,17 @@ ul#navMain {
In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
+
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:
-A database.yml file with all of your connection strings.
+A database.yml file with all of your connection strings
-A schema.rb file with your table definitions.
+A schema.rb file with your table definitions
-A test helper that sets up the database before your tests.
+A test helper method that sets up the database
@@ -457,11 +468,11 @@ A test helper that sets up the database before your tests.
For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
@@ -509,34 +520,38 @@ ENV['RAILS_ROOT
require'test/unit'require File.expand_path(File.join(ENV['RAILS_ROOT'],'config/environment.rb'))
-config = YAML::load(IO.read(File.dirname(__FILE__)+'/database.yml'))
-ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__)+"/debug.log")
+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']
+ db_adapter = ENV['DB']
-db_adapter ||=
- begin
- require'rubygems'
- require'sqlite'
- 'sqlite'
- rescue MissingSourceFile
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=begin
- require'sqlite3'
- 'sqlite3'
+ require'rubygems'
+ require'sqlite'
+ 'sqlite'rescue MissingSourceFile
+ begin
+ require'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ endend
- end
-if db_adapter.nil?
- raise"No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
-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])
+ ActiveRecord::Base.establish_connection(config[db_adapter])
-load(File.dirname(__FILE__)+"/schema.rb")
+ load(File.dirname(__FILE__)+"/schema.rb")
-require File.dirname(__FILE__)+'/../init.rb'
+ require File.dirname(__FILE__)+'/../init.rb'
+end
+
Now whenever you write a test that requires the database, you can call load_schema.
1.4. 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:
When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in your plugin.
-
We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
-
Type:
-
-
-
script/generate
-
-
You should see the line:
-
-
-
Plugins (vendor/plugins): yaffle
-
-
When you run script/generate yaffle you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
+
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
+
+
+
+
5.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:
+
+
+
+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:
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.
+
5.2. 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:
Note that you need to be aware of whether or not table names are pluralized.
-
This does a few things:
-
-
-
-Reuses the built in rails migration_template method.
-
-
-
-
-Reuses the built-in rails migration template.
-
-
-
-
When you run the generator like
+
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.
+
5.3. Manually test the generator
+
To run the generator, type the following at the command line:
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
+
6. Add a custom generator command
diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
index 41ffa61537..de116af7db 100644
--- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -79,6 +79,8 @@ class Wickwall < ActiveRecord::Base
end
class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
+
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
@@ -132,6 +134,8 @@ class Wickwall < ActiveRecord::Base
end
class ActsAsYaffleTest < Test::Unit::TestCase
+ load_schema
+
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
diff --git a/railties/doc/guides/source/creating_plugins/basics.markdown b/railties/doc/guides/source/creating_plugins/basics.markdown
deleted file mode 100644
index f59e8728d7..0000000000
--- a/railties/doc/guides/source/creating_plugins/basics.markdown
+++ /dev/null
@@ -1,861 +0,0 @@
-Creating Plugin Basics
-====================
-
-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.
-
-In this tutorial you will learn how to create a plugin that includes:
-
-Core Extensions - extending String:
-
- # Anywhere
- "hello".squawk # => "squawk! hello! squawk!"
-
-An `acts_as_yaffle` method for Active Record models that adds a "squawk" method:
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_sang_at
- end
-
- Hickwall.new.squawk("Hello World")
-
-A view helper that will print out squawking info:
-
- squawk_info_for(@hickwall)
-
-A generator that creates a migration to add squawk columns to a model:
-
- script/generate yaffle hickwall
-
-A custom generator command:
-
- class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
- end
- end
-
-A custom route method:
-
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
-
-In addition you'll learn how to:
-
-* test your plugins
-* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins
-* create documentation for your plugin.
-* write custom rake tasks in your plugin
-
-Create the basic app
----------------------
-
-In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
-
-> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
-
- rails plugin_demo
- cd plugin_demo
- script/generate scaffold bird name:string
- rake db:migrate
- script/server
-
-Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing.
-
-Create the plugin
------------------------
-
-The built-in Rails plugin generator stubs out a new plugin. 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 BrowserFilters
- ./script/generate plugin BrowserFilters --with-generator
-
-Later in the plugin we will create a generator, so go ahead and add 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
-
-For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that.
-
- rm vendor/plugins/yaffle/lib/yaffle.rb
-
-> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`
-> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
-
-Setup the plugin for testing
-------------------------
-
-Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial 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:
-
-* A database.yml file with all of your connection strings
-* A schema.rb file with your table definitions
-* A test helper that sets up the database before your tests
-
-For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
-
- # File: vendor/plugins/yaffle/test/database.yml
-
- sqlite:
- :adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
- sqlite3:
- :adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
- postgresql:
- :adapter: postgresql
- :username: postgres
- :password: postgres
- :database: yaffle_plugin_test
- :min_messages: ERROR
- mysql:
- :adapter: mysql
- :host: localhost
- :username: rails
- :password:
- :database: yaffle_plugin_test
-
- # File: vendor/plugins/yaffle/test/test_helper.rb
-
- 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
- end
-
- # File: vendor/plugins/yaffle/test/test_helper.rb
-
- 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'))
-
- 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__) + '/../init.rb'
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle
- end
-
- class Wickwall < ActiveRecord::Base
- acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
- end
-
-Add a `to_squawk` method to String
------------------------
-
-To update a core class you will have to:
-
-* Write tests for the desired functionality
-* Create a file for the code you wish to use
-* Require that file from your init.rb
-
-Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb`
-
-First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
-
- # File: vendor/plugins/yaffle/test/core_ext_test.rb
-
- require 'test/unit'
-
- class CoreExtTest < Test::Unit::TestCase
- # Replace this with your real tests.
- def test_this_plugin
- flunk
- end
- end
-
-Start off by removing the default test, and adding a require statement for your test helper.
-
- # File: vendor/plugins/yaffle/test/core_ext_test.rb
-
- require 'test/unit'
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class CoreExtTest < Test::Unit::TestCase
- end
-
-Navigate to your plugin directory and run `rake test`
-
- cd vendor/plugins/yaffle
- rake test
-
-Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message:
-
- 1.) Failure ...
- No tests were specified
-
-Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this:
-
- # File: vendor/plugins/yaffle/init.rb
-
- class CoreExtTest < Test::Unit::TestCase
- def test_string_should_respond_to_squawk
- assert_equal true, "".respond_to?(:to_squawk)
- end
- def test_string_prepend_empty_strings_with_the_word_squawk
- assert_equal "squawk!", "".to_squawk
- end
- def test_string_prepend_non_empty_strings_with_the_word_squawk
- assert_equal "squawk! Hello World", "Hello World".to_squawk
- end
- end
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "core_ext"
-
- # File: vendor/plugins/yaffle/lib/core_ext.rb
-
- String.class_eval do
- def to_squawk
- "squawk! #{self}".strip
- end
- end
-
-When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
-
-To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
-
- script/console
- >> "Hello World".to_squawk
- => "squawk! Hello World"
-
-If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.
-
-Add an `acts_as_yaffle` method to ActiveRecord
------------------------
-
-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 keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper.
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class Hickwall < ActiveRecord::Base
- acts_as_yaffle
- end
-
- class ActsAsYaffleTest < Test::Unit::TestCase
- end
-
- # File: vendor/plugins/lib/acts_as_yaffle.rb
-
- module Yaffle
- end
-
-One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- # any method placed here will apply to classes, like Hickwall
- def acts_as_something
- send :include, InstanceMethods
- end
- end
-
- 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`).
-
-Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
-
-Back in your `acts_as_yaffle` file, update ClassMethods like so:
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- send :include, InstanceMethods
- end
- end
-
-Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class ActsAsYaffleTest < Test::Unit::TestCase
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
- def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
- def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
- end
-
-To make these tests pass, you could modify your `acts_as_yaffle` file like so:
-
- # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- end
- end
-
-Now you can add tests for the instance methods, and the instance method itself:
-
- # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
-
- class ActsAsYaffleTest < Test::Unit::TestCase
-
- def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_squawk", Hickwall.yaffle_text_field
- end
- def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_squawked_at", Hickwall.yaffle_date_field
- end
-
- def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
- assert_equal "last_tweet", Wickwall.yaffle_text_field
- end
- def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
- assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
- end
-
- def test_hickwalls_squawk_should_populate_last_squawk
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", hickwall.last_squawk
- end
- def test_hickwalls_squawk_should_populate_last_squawked_at
- hickwall = Hickwall.new
- hickwall.squawk("Hello World")
- assert_equal Date.today, hickwall.last_squawked_at
- end
-
- def test_wickwalls_squawk_should_populate_last_tweet
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal "squawk! Hello World", wickwall.last_tweet
- end
- def test_wickwalls_squawk_should_populate_last_tweeted_at
- wickwall = Wickwall.new
- wickwall.squawk("Hello World")
- assert_equal Date.today, wickwall.last_tweeted_at
- end
- end
-
- # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
- module Yaffle
- def self.included(base)
- base.send :extend, ClassMethods
- end
-
- module ClassMethods
- def acts_as_yaffle(options = {})
- cattr_accessor :yaffle_text_field, :yaffle_date_field
- self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
- self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
- send :include, InstanceMethods
- end
- end
-
- module InstanceMethods
- def squawk(string)
- write_attribute(self.class.yaffle_text_field, string.to_squawk)
- write_attribute(self.class.yaffle_date_field, Date.today)
- end
- end
- end
-
-Note the use of write_attribute to write to the field in model.
-
-Create a view helper
------------------------
-
-Creating a view helper is a 3-step process:
-
-* Add an appropriately named file to the lib directory
-* Require the file and hooks in init.rb
-* Write the tests
-
-First, create the test to define the functionality you want:
-
- # File: vendor/plugins/yaffle/test/view_helpers_test.rb
-
- require File.dirname(__FILE__) + '/test_helper.rb'
- include YaffleViewHelper
-
- class ViewHelpersTest < Test::Unit::TestCase
- def test_squawk_info_for_should_return_the_text_and_date
- time = Time.now
- hickwall = Hickwall.new
- hickwall.last_squawk = "Hello World"
- hickwall.last_squawked_at = time
- assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
- end
- end
-
-Then add the following statements to init.rb:
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "view_helpers"
- ActionView::Base.send :include, YaffleViewHelper
-
-Then add the view helpers file and
-
- # File: vendor/plugins/yaffle/lib/view_helpers.rb
-
- module YaffleViewHelper
- def squawk_info_for(yaffle)
- returning "" do |result|
- result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
- result << ", "
- result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
- end
- end
- end
-
-You can also test this in script/console by using the "helper" method:
-
- script/console
- >> helper.squawk_info_for(@some_yaffle_instance)
-
-Create a migration generator
------------------------
-
-When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
-
-We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
-
-Type:
-
- script/generate
-
-You should see the line:
-
- Plugins (vendor/plugins): yaffle
-
-When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, 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
-
-Now you can add code to your generator:
-
- # File: 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")]
- assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
- end
- end
- end
-
-Note that you need to be aware of whether or not table names are pluralized.
-
-This does a few things:
-
-* Reuses the built in rails migration_template method
-* Reuses the built-in rails migration template
-
-When you run the generator like
-
- script/generate yaffle bird
-
-You will see a new file:
-
- # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
-
- class AddYaffleFieldsToBirds < ActiveRecord::Migration
- def self.up
- add_column :birds, :last_squawk, :string
- add_column :birds, :last_squawked_at, :datetime
- end
-
- def self.down
- remove_column :birds, :last_squawked_at
- remove_column :birds, :last_squawk
- end
- end
-
-Add a custom generator command
-------------------------
-
-You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
-
-1. Add the require and hook statements to init.rb
-2. Create the commands - creating 3 sets, Create, Destroy, List
-3. Add the method to your generator
-
-Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "commands"
- 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
-
- # File: 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
- end
- end
- end
-
- # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
-
- Yaffle is a bird
-
- # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
- class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
- end
- end
-
-This example just uses the built-in "file" method, but you could do anything that ruby allows.
-
-Add a Custom Route
-------------------------
-
-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](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2)
-
- # File: vendor/plugins/yaffle/test/routing_test.rb
-
- require "#{File.dirname(__FILE__)}/test_helper"
-
- class RoutingTest < Test::Unit::TestCase
-
- def setup
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
- end
-
- def test_yaffles_route
- assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
- end
-
- 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
- end
- end
-
- # File: vendor/plugins/yaffle/init.rb
-
- require "routing"
- ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
-
- # File: vendor/plugins/yaffle/lib/routing.rb
-
- module Yaffle #:nodoc:
- module Routing #:nodoc:
- module MapperExtensions
- def yaffles
- @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
- end
- end
- end
- end
-
- # File: 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.
-
-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
-
-Work with init.rb
-------------------------
-
-The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior.
-
-If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
-
-The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash
-
- # File: vendor/plugins/yaffle/init.rb
-
- class ::Hash
- def is_a_special_hash?
- true
- end
- end
-
-OR you can use `module_eval` or `class_eval`
-
- # File: vendor/plugins/yaffle/init.rb
-
- Hash.class_eval do
- def is_a_special_hash?
- true
- end
- end
-
-Store models, views, helpers, and controllers in your plugins
-------------------------
-
-You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
-
- # File: vendor/plugins/yaffle/init.rb
-
- %w{ models controllers helpers }.each do |dir|
- path = File.join(directory, 'lib', dir)
- $LOAD_PATH << path
- Dependencies.load_paths << path
- 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.
-
-Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
-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:
-
- # File: vendor/plugins/yaffle/tasks/yaffle.rake
-
- 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..."
-
-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!
-
- 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`, which will generate the spec folder and database for you.
-
-[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master)
-
-References
-------------------------
-
-* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](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/2006/05/09/the-complete-guide-to-rails-plugins-part-ii)
-* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master)
-* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html)
-
-Appendices
-------------------------
-
-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
diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
index 1a477a69ab..743d512132 100644
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt
@@ -1,35 +1,68 @@
== Create a migration generator ==
-When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
+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'.
-We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
+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.
-Type:
+To create a generator you must:
-------------------------------------------------------------------
-script/generate
-------------------------------------------------------------------
+ * 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
-You should see the line:
+=== Testing generators ===
-------------------------------------------------------------------
-Plugins (vendor/plugins): yaffle
-------------------------------------------------------------------
+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:
-When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
+*vendor/plugins/yaffle/test/yaffle_generator_test.rb*
+[source, ruby]
------------------------------------------------------------------
-Description:
- Creates a migration that adds yaffle squawk fields to the given model
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+require 'rails_generator/scripts/destroy'
-Example:
- ./script/generate yaffle hickwall
+class YaffleTest < Test::Unit::TestCase
- This will create:
- db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
+ 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
------------------------------------------------------------------
-Now you can add code to your generator:
+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*
@@ -40,7 +73,7 @@ class YaffleGenerator < Rails::Generator::NamedBase
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
@@ -56,26 +89,24 @@ class YaffleGenerator < Rails::Generator::NamedBase
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")]
- assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
end
end
end
------------------------------------------------------------------
-Note that you need to be aware of whether or not table names are pluralized.
+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.
-This does a few things:
+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.
- * Reuses the built in rails `migration_template` method.
- * Reuses the built-in rails migration template.
+=== Manually test the generator ===
-When you run the generator like
+To run the generator, type the following at the command line:
------------------------------------------------------------------
-script/generate yaffle bird
+./script/generate yaffle bird
------------------------------------------------------------------
-You will see a new file:
+and you will see a new file:
*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
@@ -84,12 +115,43 @@ You will see a new file:
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
- add_column :birds, :last_squawked_at, :datetime
end
def self.down
- remove_column :birds, :last_squawked_at
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
+------------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
index 583d058494..4bcb2d5c2b 100644
--- a/railties/doc/guides/source/creating_plugins/test_setup.txt
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -64,24 +64,24 @@ create vendor/plugins/yaffle/generators/yaffle/USAGE
=== Setup the plugin for testing ===
-In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.
+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:
- * A 'database.yml' file with all of your connection strings.
- * A 'schema.rb' file with your table definitions.
- * A test helper that sets up the database before your tests.
+ * 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
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
sqlite:
:adapter: sqlite
- :dbfile: yaffle_plugin.sqlite.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
- :dbfile: yaffle_plugin.sqlite3.db
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
@@ -93,8 +93,8 @@ postgresql:
mysql:
:adapter: mysql
:host: localhost
- :username: rails
- :password:
+ :username: root
+ :password: password
:database: yaffle_plugin_test
----------------------------------------------
@@ -128,35 +128,40 @@ ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
-config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
-ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+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']
+ db_adapter = ENV['DB']
-db_adapter ||=
- begin
- require 'rubygems'
- require 'sqlite'
- 'sqlite'
- rescue MissingSourceFile
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=
begin
- require 'sqlite3'
- 'sqlite3'
+ require 'rubygems'
+ require 'sqlite'
+ 'sqlite'
rescue MissingSourceFile
+ begin
+ require 'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ end
end
- end
-if db_adapter.nil?
- raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
-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])
+ ActiveRecord::Base.establish_connection(config[db_adapter])
-load(File.dirname(__FILE__) + "/schema.rb")
+ load(File.dirname(__FILE__) + "/schema.rb")
-require File.dirname(__FILE__) + '/../init.rb'
+ require File.dirname(__FILE__) + '/../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:
@@ -168,6 +173,7 @@ Once you have these files in place, you can write your first test to ensure that
require File.dirname(__FILE__) + '/test_helper.rb'
class YaffleTest < Test::Unit::TestCase
+ load_schema
class Hickwall < ActiveRecord::Base
end
--
cgit v1.2.3
From 8a9bd56ca0d43c703f330e378474ddbdca2acd8e Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Fri, 14 Nov 2008 00:38:52 -0500
Subject: Plugin Guide: updated test setup and generator sections
---
railties/doc/guides/html/creating_plugins.html | 65 ++++++++--------
.../source/creating_plugins/custom_generator.txt | 69 -----------------
.../source/creating_plugins/generator_method.txt | 89 ++++++++++++++++++++++
.../doc/guides/source/creating_plugins/index.txt | 2 +-
.../guides/source/creating_plugins/test_setup.txt | 2 -
5 files changed, 125 insertions(+), 102 deletions(-)
delete mode 100644 railties/doc/guides/source/creating_plugins/custom_generator.txt
create mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 5589971ec5..3e67c34b4f 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -1178,35 +1178,34 @@ Example:
6. Add a custom generator command
-
You may have noticed above that you can used one of the built-in rails migration commands m.migration_template. You can create your own commands for these, using the following steps:
-
-
-
-Add the require and hook statements to init.rb.
-
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
-
vendor/plugins/yaffle/init.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 routes.rb. This example creates a very simple method that adds or removes a text file.
This example just uses the built-in "file" method, but you could do anything that Ruby allows.
7. Add a Custom Route
diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt
deleted file mode 100644
index a8cf1b48ce..0000000000
--- a/railties/doc/guides/source/creating_plugins/custom_generator.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-== Add a custom generator command ==
-
-You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
-
- 1. Add the require and hook statements to init.rb.
- 2. Create the commands - creating 3 sets, Create, Destroy, List.
- 3. Add the method to your generator.
-
-Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
------------------------------------------------------------
-require "commands"
-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
------------------------------------------------------------
-
-*vendor/plugins/yaffle/lib/commands.rb*
-
-[source, ruby]
------------------------------------------------------------
-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
- end
- end
-end
------------------------------------------------------------
-
-*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
------------------------------------------------------------
-Yaffle is a bird
------------------------------------------------------------
-
-*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
-
-[source, ruby]
------------------------------------------------------------
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
------------------------------------------------------------
-
-This example just uses the built-in "file" method, but you could do anything that Ruby allows.
diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt
new file mode 100644
index 0000000000..126692f2c4
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/generator_method.txt
@@ -0,0 +1,89 @@
+== Add a custom generator command ==
+
+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*
+
+[source, ruby]
+-----------------------------------------------------------
+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*
+
+[source, ruby]
+-----------------------------------------------------------
+require "yaffle/commands"
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/commands.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+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*
+
+[source, ruby]
+-----------------------------------------------------------
+class YaffleGenerator < Rails::Generator::NamedBase
+ def manifest
+ m.yaffle_definition
+ end
+end
+-----------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index 91d7027323..bd7dfe65c3 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -39,7 +39,7 @@ include::view_helper.txt[]
include::migration_generator.txt[]
-include::custom_generator.txt[]
+include::generator_method.txt[]
include::custom_route.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
index 4bcb2d5c2b..9e6763bc30 100644
--- a/railties/doc/guides/source/creating_plugins/test_setup.txt
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -153,9 +153,7 @@ def load_schema
end
ActiveRecord::Base.establish_connection(config[db_adapter])
-
load(File.dirname(__FILE__) + "/schema.rb")
-
require File.dirname(__FILE__) + '/../init.rb'
end
----------------------------------------------
--
cgit v1.2.3
From 7eb249291d1c8a8af14c52de4767a36ba8f924e3 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Fri, 14 Nov 2008 02:29:12 -0500
Subject: Plugin guide: added model and controller sections
---
railties/doc/guides/html/creating_plugins.html | 355 ++++++++++++++-------
.../guides/source/creating_plugins/controllers.txt | 59 ++++
.../doc/guides/source/creating_plugins/index.txt | 8 +-
.../creating_plugins/migration_generator.txt | 5 +-
.../doc/guides/source/creating_plugins/models.txt | 76 +++++
.../source/creating_plugins/odds_and_ends.txt | 22 --
.../guides/source/creating_plugins/test_setup.txt | 3 +
7 files changed, 384 insertions(+), 144 deletions(-)
create mode 100644 railties/doc/guides/source/creating_plugins/controllers.txt
create mode 100644 railties/doc/guides/source/creating_plugins/models.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 3e67c34b4f..3fa7bff260 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -235,10 +235,7 @@ ul#navMain {
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.
@@ -1032,7 +963,7 @@ Update the USAGE file to add helpful documentation for your generator
-
5.1. Testing generators
+
4.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:
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.
-
5.2. Adding to the manifest
+
4.2. 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:
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.
-
5.3. Manually test the generator
+
4.3. Manually test the generator
To run the generator, type the following at the command line:
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.
@@ -1265,7 +1196,215 @@ http://www.gnu.org/software/src-highlite -->
end
-
7. Add a Custom Route
+
6. Add a model
+
+
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:
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.
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.
+
+
7. Add a controller
+
+
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:
class WoodpeckersController < ActionController::Base
+
+ def index
+ 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.
+
+
8. Create a squawk_info_for view helper
+
+
Creating a view helper is a 3-step process:
+
+
+
+Add an appropriately named file to the lib directory.
+
+
+
+
+Require the file and hooks in init.rb.
+
+
+
+
+Write the tests.
+
+
+
+
First, create the test to define the functionality you want:
You can also see if your routes work by running rake routes from your app directory.
-
8. Odds and ends
+
10. Odds and ends
-
8.1. Generate RDoc Documentation
+
10.1. 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:
@@ -1372,25 +1511,7 @@ Warning, gotchas or tips that might help save users time.
rake rdoc
-
8.2. Store models, views, helpers, and controllers in your plugins
-
You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
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.
-
Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
8.3. Write custom Rake tasks in your plugin
+
10.2. 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:
8.5. Create your own Plugin Loaders and Plugin Locators
+
10.4. 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.
The final plugin should have a directory structure that looks something like this:
diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
new file mode 100644
index 0000000000..ee408adb1d
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -0,0 +1,59 @@
+== Add a controller ==
+
+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:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'woodpeckers_controller'
+require 'action_controller/test_process'
+
+class WoodpeckersController; def rescue_action(e) raise e end; end
+
+class WoodpeckersControllerTest < Test::Unit::TestCase
+ def setup
+ @controller = WoodpeckersController.new
+ @request = ActionController::TestRequest.new
+ @response = ActionController::TestResponse.new
+ end
+
+ def test_index
+ 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:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models controllers }.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
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:*
+
+[source, ruby]
+----------------------------------------------
+class WoodpeckersController < ActionController::Base
+
+ def index
+ 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.
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index bd7dfe65c3..67e6aec39c 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -35,12 +35,16 @@ include::core_ext.txt[]
include::acts_as_yaffle.txt[]
-include::view_helper.txt[]
-
include::migration_generator.txt[]
include::generator_method.txt[]
+include::models.txt[]
+
+include::controllers.txt[]
+
+include::view_helper.txt[]
+
include::custom_route.txt[]
include::odds_and_ends.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
index 743d512132..f4fc32481c 100644
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt
@@ -1,4 +1,4 @@
-== Create a migration generator ==
+== 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'.
@@ -30,7 +30,7 @@ require 'rails_generator'
require 'rails_generator/scripts/generate'
require 'rails_generator/scripts/destroy'
-class YaffleTest < Test::Unit::TestCase
+class GeneratorTest < Test::Unit::TestCase
def fake_rails_root
File.join(File.dirname(__FILE__), 'rails_root')
@@ -124,7 +124,6 @@ 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:
diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt
new file mode 100644
index 0000000000..458edec80a
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/models.txt
@@ -0,0 +1,76 @@
+== Add a model ==
+
+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/
+|-- lib
+| |-- app
+| | |-- controllers
+| | |-- helpers
+| | |-- models
+| | | `-- woodpecker.rb
+| | `-- views
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | `-- core_ext.rb
+| `-- yaffle.rb
+---------------------------------------------------------
+
+As always, start with a test:
+
+*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class WoodpeckerTest < Test::Unit::TestCase
+ load_schema
+
+ 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:*
+
+[source, ruby]
+----------------------------------------------
+%w{ models }.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
+----------------------------------------------
+
+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:*
+
+[source, ruby]
+----------------------------------------------
+class Woodpecker < ActiveRecord::Base
+end
+----------------------------------------------
+
+Finally, add the following to your plugin's 'schema.rb':
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+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.
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
index a52e1c8fdb..e328c04a79 100644
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
@@ -19,28 +19,6 @@ Once your comments are good to go, navigate to your plugin directory and run:
rake rdoc
-
-=== Store models, views, helpers, and controllers in your plugins ===
-
-You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
-
-[source, ruby]
----------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-%w{ models controllers helpers }.each do |dir|
- path = File.join(directory, 'lib', dir)
- $LOAD_PATH << path
- Dependencies.load_paths << path
- 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.
-
-Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
-
-
=== 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.
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
index 9e6763bc30..6ea2a37fa7 100644
--- a/railties/doc/guides/source/creating_plugins/test_setup.txt
+++ b/railties/doc/guides/source/creating_plugins/test_setup.txt
@@ -115,6 +115,9 @@ 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
----------------------------------------------
--
cgit v1.2.3
From 88a13fad4fae2c2088188008248e15498a2ca466 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Fri, 14 Nov 2008 03:02:05 -0500
Subject: Rails plugin: Expanded helpers section
---
railties/doc/guides/html/creating_plugins.html | 75 ++++++++--------------
.../doc/guides/source/creating_plugins/helpers.txt | 51 +++++++++++++++
.../doc/guides/source/creating_plugins/index.txt | 2 +-
.../guides/source/creating_plugins/view_helper.txt | 61 ------------------
4 files changed, 78 insertions(+), 111 deletions(-)
create mode 100644 railties/doc/guides/source/creating_plugins/helpers.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/view_helper.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 3fa7bff260..023a4ddbab 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -258,7 +258,7 @@ ul#navMain {
Add a controller
Add a Custom Route
@@ -1330,79 +1330,56 @@ http://www.gnu.org/software/src-highlite -->
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.
-
8. Create a squawk_info_for view helper
+
8. Add a helper
-
Creating a view helper is a 3-step process:
-
-
-
-Add an appropriately named file to the lib directory.
-
-
-
-
-Require the file and hooks in init.rb.
-
-
-
-
-Write the tests.
-
-
-
-
First, create the test to define the functionality you want:
-
vendor/plugins/yaffle/test/view_helpers_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:
Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
9. Add a Custom Route
diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt
new file mode 100644
index 0000000000..51b4cebb01
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -0,0 +1,51 @@
+== Add a helper ==
+
+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*
+
+[source, ruby]
+---------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+include WoodpeckersHelper
+
+class WoodpeckersHelperTest < Test::Unit::TestCase
+ 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:*
+
+[source, ruby]
+----------------------------------------------
+%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
+
+ActionView::Base.send :include, WoodpeckersHelper
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+module WoodpeckersHelper
+
+ def tweet(text)
+ "Tweet! #{text}"
+ end
+
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpeckers helper in your app.
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index 67e6aec39c..19484e2830 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -43,7 +43,7 @@ include::models.txt[]
include::controllers.txt[]
-include::view_helper.txt[]
+include::helpers.txt[]
include::custom_route.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt
deleted file mode 100644
index 4eaec93824..0000000000
--- a/railties/doc/guides/source/creating_plugins/view_helper.txt
+++ /dev/null
@@ -1,61 +0,0 @@
-== Create a `squawk_info_for` view helper ==
-
-Creating a view helper is a 3-step process:
-
- * Add an appropriately named file to the 'lib' directory.
- * Require the file and hooks in 'init.rb'.
- * Write the tests.
-
-First, create the test to define the functionality you want:
-
-*vendor/plugins/yaffle/test/view_helpers_test.rb*
-
-[source, ruby]
----------------------------------------------------------------
-require File.dirname(__FILE__) + '/test_helper.rb'
-include YaffleViewHelper
-
-class ViewHelpersTest < Test::Unit::TestCase
- def test_squawk_info_for_should_return_the_text_and_date
- time = Time.now
- hickwall = Hickwall.new
- hickwall.last_squawk = "Hello World"
- hickwall.last_squawked_at = time
- assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
- end
-end
----------------------------------------------------------------
-
-Then add the following statements to init.rb:
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
----------------------------------------------------------------
-require "view_helpers"
-ActionView::Base.send :include, YaffleViewHelper
----------------------------------------------------------------
-
-Then add the view helpers file and
-
-*vendor/plugins/yaffle/lib/view_helpers.rb*
-
-[source, ruby]
----------------------------------------------------------------
-module YaffleViewHelper
- def squawk_info_for(yaffle)
- returning "" do |result|
- result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
- result << ", "
- result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
- end
- end
-end
----------------------------------------------------------------
-
-You can also test this in script/console by using the `helper` method:
-
----------------------------------------------------------------
-$ ./script/console
->> helper.squawk_info_for(@some_yaffle_instance)
----------------------------------------------------------------
--
cgit v1.2.3
From fa9ea057d1252a578f8e056defef41b93853bc8b Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Fri, 14 Nov 2008 03:14:09 -0500
Subject: Plugin guide: updated to start working with GemPlugin
---
railties/doc/guides/html/creating_plugins.html | 10 +++++-----
railties/doc/guides/source/creating_plugins/core_ext.txt | 5 ++---
railties/doc/guides/source/creating_plugins/gem.txt | 1 +
railties/doc/guides/source/creating_plugins/test_setup.txt | 3 ++-
4 files changed, 10 insertions(+), 9 deletions(-)
create mode 100644 railties/doc/guides/source/creating_plugins/gem.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 023a4ddbab..375d216b4a 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -447,6 +447,7 @@ create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
+
To begin just change one thing - move init.rb to rails/init.rb.
1.3. Setup the plugin for testing
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:
The first thing we need to to is to require our lib/yaffle.rb file from init.rb:
-
vendor/plugins/yaffle/init.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
end
-
7. Changelog
+
7. Using the errors collection
+
+
You can do more than just call valid? upon your objects based on the existance of the errors collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.
+
+
+
+add_to_base lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. add_to_base receives a string with the message.
+
+
+
+
+
+
class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors.add_to_base("This person is invalid because ...")
+ end
+end
+
+
+
+
+add lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. add receives a symbol with the name of the attribute that you want to add the message to and the message itself.
+
+
+
+
+
+
class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors.add(:name,"can't have the characters !@#$%*()_-+=")
+ end
+end
+
+
+
+
+invalid? is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check.
+
+
+
+
+
+
class Person < ActiveRecord::Base
+ validates_presence_of :name,:email
+end
+
+person = Person.new(:name =>"John Doe")
+person.invalid?(:email)# => true
+
+
+
+
+on is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the errors collection for the given attribute. If there are no errors related to the attribute, on will return nil. If there is just one errors message for this attribute, on will return a string with the message. When errors holds two or more error messages for the attribute, on will return an array of strings, each one with one error message.
+
+
+
+
+
+
class Person < ActiveRecord::Base
+ validates_presence_of :name
+ validates_length_of :name,:minimum =>3
+end
+
+person = Person.new(:name =>"John Doe")
+person.valid? # => true
+person.errors.on(:name)# => nil
+
+person = Person.new(:name =>"JD")
+person.valid? # => false
+person.errors.on(:name)# => "is too short (minimum is 3 characters)"
+
+person = Person.new
+person.valid? # => false
+person.errors.on(:name)# => ["can't be blank", "is too short (minimum is 3 characters)"]
+
+
+
+
+clear is used when you intentionally wants to clear all the messages in the errors collection.
+
+
+
+
+
+
class Person < ActiveRecord::Base
+ validates_presence_of :name
+ validates_length_of :name,:minimum =>3
+end
+
+person = Person.new
+puts person.valid? # => false
+person.errors.on(:name)# => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.errors.clear
+person.errors # => nil
+
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index fd6eb86b0b..87f3392551 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -399,6 +399,83 @@ class Invoice < ActiveRecord::Base
end
------------------------------------------------------------------
+== Using the +errors+ collection
+
+You can do more than just call +valid?+ upon your objects based on the existance of the +errors+ collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.
+
+* +add_to_base+ lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. +add_to_base+ receives a string with the message.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors.add_to_base("This person is invalid because ...")
+ end
+end
+------------------------------------------------------------------
+
+* +add+ lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. +add+ receives a symbol with the name of the attribute that you want to add the message to and the message itself.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ def a_method_used_for_validation_purposes
+ errors.add(:name, "can't have the characters !@#$%*()_-+=")
+ end
+end
+------------------------------------------------------------------
+
+* +invalid?+ is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :name, :email
+end
+
+person = Person.new(:name => "John Doe")
+person.invalid?(:email) # => true
+------------------------------------------------------------------
+
+* +on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :name
+ validates_length_of :name, :minimum => 3
+end
+
+person = Person.new(:name => "John Doe")
+person.valid? # => true
+person.errors.on(:name) # => nil
+
+person = Person.new(:name => "JD")
+person.valid? # => false
+person.errors.on(:name) # => "is too short (minimum is 3 characters)"
+
+person = Person.new
+person.valid? # => false
+person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+------------------------------------------------------------------
+
+* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection.
+
+[source, ruby]
+------------------------------------------------------------------
+class Person < ActiveRecord::Base
+ validates_presence_of :name
+ validates_length_of :name, :minimum => 3
+end
+
+person = Person.new
+puts person.valid? # => false
+person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
+person.errors.clear
+person.errors # => nil
+------------------------------------------------------------------
+
+
== Changelog
http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks
--
cgit v1.2.3
From 097b4678f6d52e86a9d46ba6c862e6eb6ef7bbdd Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Sun, 16 Nov 2008 20:30:42 -0500
Subject: Plugin Guide: added section on migrations, updated generator section,
tightened up spacing of P's inside LI's
---
railties/doc/guides/html/configuring.html | 119 ++-
railties/doc/guides/html/creating_plugins.html | 952 +++++++++++++--------
railties/doc/guides/html/migrations.html | 3 +-
.../source/creating_plugins/acts_as_yaffle.txt | 2 +-
.../guides/source/creating_plugins/appendix.txt | 73 +-
.../guides/source/creating_plugins/controllers.txt | 2 +-
.../source/creating_plugins/custom_route.txt | 69 --
.../doc/guides/source/creating_plugins/gem.txt | 2 +
.../source/creating_plugins/generator_commands.txt | 140 +++
.../source/creating_plugins/generator_method.txt | 89 --
.../guides/source/creating_plugins/generators.txt | 103 +++
.../doc/guides/source/creating_plugins/helpers.txt | 2 +-
.../doc/guides/source/creating_plugins/index.txt | 16 +-
.../creating_plugins/migration_generator.txt | 156 ----
.../guides/source/creating_plugins/migrations.txt | 209 +++++
.../doc/guides/source/creating_plugins/models.txt | 2 +-
.../doc/guides/source/creating_plugins/routes.txt | 69 ++
.../doc/guides/source/creating_plugins/setup.txt | 64 ++
.../guides/source/creating_plugins/test_setup.txt | 230 -----
.../doc/guides/source/creating_plugins/tests.txt | 165 ++++
railties/doc/guides/source/stylesheets/base.css | 4 +
21 files changed, 1505 insertions(+), 966 deletions(-)
delete mode 100644 railties/doc/guides/source/creating_plugins/custom_route.txt
create mode 100644 railties/doc/guides/source/creating_plugins/generator_commands.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt
create mode 100644 railties/doc/guides/source/creating_plugins/generators.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/migration_generator.txt
create mode 100644 railties/doc/guides/source/creating_plugins/migrations.txt
create mode 100644 railties/doc/guides/source/creating_plugins/routes.txt
create mode 100644 railties/doc/guides/source/creating_plugins/setup.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt
create mode 100644 railties/doc/guides/source/creating_plugins/tests.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html
index 4aa3a0f545..ea5f162cb7 100644
--- a/railties/doc/guides/html/configuring.html
+++ b/railties/doc/guides/html/configuring.html
@@ -205,6 +205,9 @@ ul#navMain {
Using a Preinitializer
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.
+
4.2. Configuring Action Controller
+
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
Odds and ends
@@ -388,7 +401,7 @@ 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.
-
1. Preparation
+
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:
To begin just change one thing - move init.rb to rails/init.rb.
-
1.3. Setup the plugin for testing
+
+
2. Tests
+
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:
@@ -558,7 +573,7 @@ ENV['RAILS_ROOT
end
Now whenever you write a test that requires the database, you can call load_schema.
-
1.4. Run the plugin tests
+
2.1. 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:
@@ -619,7 +634,7 @@ rake DB=postgresql
Now you are ready to test-drive your plugin!
-
2. Extending core classes
+
3. Extending core classes
This section will explain how to add a method to String that will be available anywhere in your rails app by:
@@ -634,7 +649,7 @@ Creating and requiring the correct files
-
2.1. Creating the test
+
3.1. Creating the test
In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:
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:
@@ -742,7 +757,7 @@ http://www.gnu.org/software/src-highlite -->
end
-
3. Add an acts_as_yaffle method to Active Record
+
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:
@@ -801,7 +816,7 @@ http://www.gnu.org/software/src-highlite -->
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).
-
3.1. Add a class 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:
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
@@ -936,267 +951,7 @@ ActiveRecord::Base4. 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
-
-
-
-
4.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:
-
-
-
-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:
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.
-
4.2. 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:
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.
-
4.3. Manually test the generator
-
To run the generator, type the following at the command line:
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
-
-
-
5. Add a custom generator command
-
-
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.
class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
-
-
-
6. Add a model
+
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:
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.
-
7. Add a controller
+
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:
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.
-
8. Add a helper
+
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:
You can also see if your routes work by running rake routes from your app directory.
-
10. Odds and ends
+
9. Generators
-
10.1. 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:
+
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:
-
+
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:
+
+
+
+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:
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.
class YaffleDefinitionGenerator < Rails::Generator::Base
+ def manifest
+ record do|m|
+ m.file "definition.txt","definition.txt"
+ 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:
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
+
+
+
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.
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:
class CreateBirdhouses < ActiveRecord::Migration
+ defself.up
+ create_table :birdhouses,:force =>truedo|t|
+ t.string :name
+ t.timestamps
+ end
+ end
+
+ defself.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
+
+
11.2. Call plugin migrations from regular migrations
class CreateBirdhouses < ActiveRecord::Migration
+ defself.up
+ Yaffle::CreateBirdhouses.up
+ end
+
+ defself.down
+ Yaffle::CreateBirdhouses.down
+ end
+end
+
+
+
+
+
+
+
several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
+
+
+
+
12. Generating 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:
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:
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:
class AddYaffleFieldsToBirds < ActiveRecord::Migration
+ defself.up
+ add_column :birds,:last_squawk,:string
+ end
+
+ defself.down
+ remove_column :birds,:last_squawk
+ end
+end
+
+
+
13. Odds and ends
+
+
13.1. 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
-
10.2. Write custom Rake tasks in your plugin
+
13.2. 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:
10.4. Create your own Plugin Loaders and Plugin Locators
+
13.4. 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.
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:
@@ -699,6 +699,7 @@ displayed saying that it can't be done.
4. Running Migrations
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
diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
index de116af7db..674f086e17 100644
--- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
+++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
@@ -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.
diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt
index a78890ccd5..d890f861b5 100644
--- a/railties/doc/guides/source/creating_plugins/appendix.txt
+++ b/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -6,41 +6,54 @@
* http://nubyonrails.com/articles/2006/05/09/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
=== 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
+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
------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
index ee408adb1d..4f4417b416 100644
--- a/railties/doc/guides/source/creating_plugins/controllers.txt
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -1,4 +1,4 @@
-== 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.
diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt
deleted file mode 100644
index 1fce902a4e..0000000000
--- a/railties/doc/guides/source/creating_plugins/custom_route.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-== Add a Custom Route ==
-
-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*
-
-[source, ruby]
---------------------------------------------------------
-require "#{File.dirname(__FILE__)}/test_helper"
-
-class RoutingTest < Test::Unit::TestCase
-
- def setup
- ActionController::Routing::Routes.draw do |map|
- map.yaffles
- end
- end
-
- def test_yaffles_route
- assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
- end
-
- 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
- end
-end
---------------------------------------------------------
-
-*vendor/plugins/yaffle/init.rb*
-
-[source, ruby]
---------------------------------------------------------
-require "routing"
-ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
---------------------------------------------------------
-
-*vendor/plugins/yaffle/lib/routing.rb*
-
-[source, ruby]
---------------------------------------------------------
-module Yaffle #:nodoc:
- module Routing #:nodoc:
- module MapperExtensions
- def yaffles
- @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
- end
- end
- end
-end
---------------------------------------------------------
-
-*config/routes.rb*
-
-[source, ruby]
---------------------------------------------------------
-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.
diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt
index 93f5e0ee89..8a0bbb3bc0 100644
--- a/railties/doc/guides/source/creating_plugins/gem.txt
+++ b/railties/doc/guides/source/creating_plugins/gem.txt
@@ -1 +1,3 @@
+== Gems ==
+
http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt
new file mode 100644
index 0000000000..5cce81c8bd
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt
@@ -0,0 +1,140 @@
+== 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 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*
+
+[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.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*
+
+[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
+-----------------------------------------------------------
+
+NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually.
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt
deleted file mode 100644
index 126692f2c4..0000000000
--- a/railties/doc/guides/source/creating_plugins/generator_method.txt
+++ /dev/null
@@ -1,89 +0,0 @@
-== Add a custom generator command ==
-
-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*
-
-[source, ruby]
------------------------------------------------------------
-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*
-
-[source, ruby]
------------------------------------------------------------
-require "yaffle/commands"
------------------------------------------------------------
-
-*vendor/plugins/yaffle/lib/commands.rb*
-
-[source, ruby]
------------------------------------------------------------
-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*
-
-[source, ruby]
------------------------------------------------------------
-class YaffleGenerator < Rails::Generator::NamedBase
- def manifest
- m.yaffle_definition
- end
-end
------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt
new file mode 100644
index 0000000000..eb0fbb5ee9
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/generators.txt
@@ -0,0 +1,103 @@
+== 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: creating a generator that adds a time-stamped migration.
+
+To add a generator to a plugin:
+
+ * Write a test
+ * Add your instructions to the 'manifest' method of the generator
+ * Add any necessary template files to the templates directory
+ * 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
+ * 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 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*
+
+[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
+------------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt
index 51b4cebb01..c2273813dd 100644
--- a/railties/doc/guides/source/creating_plugins/helpers.txt
+++ b/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -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.
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index 19484e2830..5d10fa4f31 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -29,23 +29,27 @@ 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::generators.txt[]
+
+include::generator_commands.txt[]
+
+include::migrations.txt[]
include::odds_and_ends.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
deleted file mode 100644
index f4fc32481c..0000000000
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ /dev/null
@@ -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
-------------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt
new file mode 100644
index 0000000000..7154f0bc06
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/migrations.txt
@@ -0,0 +1,209 @@
+== 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/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
+----------------------------------------------
+
+
+*vendor/plugins/yaffle/tasks/yaffle.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 plugin migrations from regular migrations ===
+
+*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
+----------------------------------------------
+
+NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
+
+== Generating 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'
+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
+------------------------------------------------------------------
+
+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*
+
+[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.
+
+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
+------------------------------------------------------------------
+
diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt
index 458edec80a..dfe11f9c4e 100644
--- a/railties/doc/guides/source/creating_plugins/models.txt
+++ b/railties/doc/guides/source/creating_plugins/models.txt
@@ -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:
diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt
new file mode 100644
index 0000000000..cdc20e998e
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/routes.txt
@@ -0,0 +1,69 @@
+== 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.
+
+*vendor/plugins/yaffle/test/routing_test.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "#{File.dirname(__FILE__)}/test_helper"
+
+class RoutingTest < Test::Unit::TestCase
+
+ def setup
+ ActionController::Routing::Routes.draw do |map|
+ map.yaffles
+ end
+ end
+
+ def test_yaffles_route
+ assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
+ end
+
+ 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
+ end
+end
+--------------------------------------------------------
+
+*vendor/plugins/yaffle/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require "routing"
+ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
+--------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/routing.rb*
+
+[source, ruby]
+--------------------------------------------------------
+module Yaffle #:nodoc:
+ module Routing #:nodoc:
+ module MapperExtensions
+ def yaffles
+ @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
+ end
+ end
+ end
+end
+--------------------------------------------------------
+
+*config/routes.rb*
+
+[source, ruby]
+--------------------------------------------------------
+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.
diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt
new file mode 100644
index 0000000000..fcf5b459e6
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/setup.txt
@@ -0,0 +1,64 @@
+== 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
+----------------------------------------------
+
+To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt
deleted file mode 100644
index 64236ff110..0000000000
--- a/railties/doc/guides/source/creating_plugins/test_setup.txt
+++ /dev/null
@@ -1,230 +0,0 @@
-== Preparation ==
-
-=== 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
-----------------------------------------------
-
-To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
-
-=== Setup the plugin for testing ===
-
-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:
-
- * 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
-
-*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!
diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt
new file mode 100644
index 0000000000..ef6dab2f9f
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/tests.txt
@@ -0,0 +1,165 @@
+== Tests ==
+
+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:
+
+ * 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
+
+*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!
diff --git a/railties/doc/guides/source/stylesheets/base.css b/railties/doc/guides/source/stylesheets/base.css
index 76ee6e2ca9..1cf0a3de98 100644
--- a/railties/doc/guides/source/stylesheets/base.css
+++ b/railties/doc/guides/source/stylesheets/base.css
@@ -97,6 +97,10 @@ ul li {
background-position: 0 0.55em;
}
+ul li p {
+ margin-bottom: 0.5em;
+}
+
/* ----------------------------------------------------------------------------
Structure
---------------------------------------------------------------------------- */
--
cgit v1.2.3
From 80f5f265471e8d53b66f432c203206c1a4197121 Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
Date: Sun, 16 Nov 2008 20:46:03 -0600
Subject: Added Action View and Action Mailer documentation to the Config
guide.
---
railties/doc/guides/source/configuring.txt | 18 ++++++++++++++++++
1 file changed, 18 insertions(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt
index dde04ffb05..1fb73abbb8 100644
--- a/railties/doc/guides/source/configuring.txt
+++ b/railties/doc/guides/source/configuring.txt
@@ -101,8 +101,26 @@ The Active Record session store can also be configured:
=== Configuring Action View
+There are only a few configuration options for Action View, starting with four on +ActionView::Base+:
+
++debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+.
+
++warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+.
+
++field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is +Proc.new{ |html_tag, instance| "
#{html_tag}
" }+
+
++default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+.
+
+The ERB template handler supplies one additional option:
+
++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+.
+
=== Configuring Action Mailer
+There are a number of settings available on +ActionMailer::Base+:
+
+
+
=== Configuring Active Resource
=== Configuring Active Support
--
cgit v1.2.3
From 6b8500ce48f45f18696f6215b8a01f5cf0e328b5 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Sun, 16 Nov 2008 22:27:08 -0500
Subject: Rails guide: Added PluginGem section, reorganized the odds and ends.
---
railties/doc/guides/html/authors.html | 5 +
railties/doc/guides/html/creating_plugins.html | 190 +++++++++++++--------
railties/doc/guides/html/routing_outside_in.html | 2 +-
railties/doc/guides/source/authors.txt | 6 +
.../guides/source/creating_plugins/appendix.txt | 26 ++-
.../guides/source/creating_plugins/controllers.txt | 2 +-
.../doc/guides/source/creating_plugins/gem.txt | 3 -
.../doc/guides/source/creating_plugins/gems.txt | 50 ++++++
.../doc/guides/source/creating_plugins/index.txt | 6 +-
.../guides/source/creating_plugins/migrations.txt | 4 +-
.../source/creating_plugins/odds_and_ends.txt | 69 --------
.../doc/guides/source/creating_plugins/rdoc.txt | 18 ++
.../doc/guides/source/creating_plugins/tasks.txt | 29 ++++
13 files changed, 254 insertions(+), 156 deletions(-)
delete mode 100644 railties/doc/guides/source/creating_plugins/gem.txt
create mode 100644 railties/doc/guides/source/creating_plugins/gems.txt
delete mode 100644 railties/doc/guides/source/creating_plugins/odds_and_ends.txt
create mode 100644 railties/doc/guides/source/creating_plugins/rdoc.txt
create mode 100644 railties/doc/guides/source/creating_plugins/tasks.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html
index a54135b14d..6fd556d2cd 100644
--- a/railties/doc/guides/html/authors.html
+++ b/railties/doc/guides/html/authors.html
@@ -231,6 +231,11 @@ Heiko has rarely looked back.
Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
and unobtrusive JavaScript. His home on the internet is his blog Sneaky Abstractions.
+
+
+
Jeff Dean
+
Jeff Dean is a software engineer with Pivotal Labs.
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:
11.2. Call plugin migrations from regular migrations
+
11.2. Call migrations directly
vendor/plugins/yaffle/lib/yaffle.rb:
several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
-
-
12. Generating migrations
-
+
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:
@@ -1709,41 +1699,8 @@ http://www.gnu.org/software/src-highlite -->
end
-
13. Odds and ends
+
12. Rake tasks
-
13.1. 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
-
-
13.2. 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:
When you run rake -T from your plugin you will see:
-
yaffle:squawk # Prints out the word 'Yaffle'
+
...
+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.
-
13.3. 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!
+
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:
13.4. 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.
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.
-
14. Appendix
+
14. RDoc Documentation
-
14.1. References
+
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
+
+
+
15. Appendix
+
+
If you prefer to use RSpec instead of tets, you may be interested in the RSpec Plugin Generator.
If your application has many RESTful routes, using :only and :accept to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
+
If your application has many RESTful routes, using :only and :except to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
3.8. Nested Resources
diff --git a/railties/doc/guides/source/authors.txt b/railties/doc/guides/source/authors.txt
index 94dfc4db08..987238eb4c 100644
--- a/railties/doc/guides/source/authors.txt
+++ b/railties/doc/guides/source/authors.txt
@@ -37,3 +37,9 @@ Heiko has rarely looked back.
Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails
and unobtrusive JavaScript. His home on the internet is his blog http://tore.darell.no/[Sneaky Abstractions].
***********************************************************
+
+.Jeff Dean
+[[zilkey]]
+***********************************************************
+Jeff Dean is a software engineer with http://pivotallabs.com/[Pivotal Labs].
+***********************************************************
diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt
index d890f861b5..19f677c5fd 100644
--- a/railties/doc/guides/source/creating_plugins/appendix.txt
+++ b/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -1,5 +1,7 @@
== Appendix ==
+If you prefer to use RSpec instead of tets, 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
@@ -13,16 +15,23 @@
The final plugin should have a directory structure that looks something like this:
------------------------------------------------
-vendor/plugins/yaffle/
|-- MIT-LICENSE
|-- README
|-- Rakefile
|-- generators
-| `-- yaffle
+| |-- yaffle_definition
+| | |-- USAGE
+| | |-- templates
+| | | `-- definition.txt
+| | `-- yaffle_definition_generator.rb
+| |-- yaffle_migration
+| | |-- USAGE
+| | |-- templates
+| | `-- yaffle_migration_generator.rb
+| `-- yaffle_route
| |-- USAGE
| |-- templates
-| | `-- definition.txt
-| `-- yaffle_generator.rb
+| `-- yaffle_route_generator.rb
|-- install.rb
|-- lib
| |-- app
@@ -32,11 +41,16 @@ vendor/plugins/yaffle/
| | | `-- woodpeckers_helper.rb
| | `-- models
| | `-- woodpecker.rb
+| |-- db
+| | `-- migrate
+| | `-- 20081116181115_create_birdhouses.rb
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
| | `-- core_ext.rb
| `-- yaffle.rb
+|-- pkg
+| `-- yaffle-0.0.1.gem
|-- rails
| `-- init.rb
|-- tasks
@@ -46,7 +60,9 @@ vendor/plugins/yaffle/
| |-- core_ext_test.rb
| |-- database.yml
| |-- debug.log
-| |-- generator_test.rb
+| |-- definition_generator_test.rb
+| |-- migration_generator_test.rb
+| |-- route_generator_test.rb
| |-- schema.rb
| |-- test_helper.rb
| |-- woodpecker_test.rb
diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
index 4f4417b416..e38cf8251e 100644
--- a/railties/doc/guides/source/creating_plugins/controllers.txt
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -4,7 +4,7 @@ This section describes how to add a controller named 'woodpeckers' to your plugi
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]
----------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt
deleted file mode 100644
index 8a0bbb3bc0..0000000000
--- a/railties/doc/guides/source/creating_plugins/gem.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-== Gems ==
-
-http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/gems.txt b/railties/doc/guides/source/creating_plugins/gems.txt
new file mode 100644
index 0000000000..67d55adb3a
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/gems.txt
@@ -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.
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt
index 5d10fa4f31..0607bc7487 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -51,6 +51,10 @@ include::generator_commands.txt[]
include::migrations.txt[]
-include::odds_and_ends.txt[]
+include::tasks.txt[]
+
+include::gems.txt[]
+
+include::rdoc.txt[]
include::appendix.txt[]
diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt
index 7154f0bc06..4dd932734d 100644
--- a/railties/doc/guides/source/creating_plugins/migrations.txt
+++ b/railties/doc/guides/source/creating_plugins/migrations.txt
@@ -63,7 +63,7 @@ namespace :db do
end
----------------------------------------------
-=== Call plugin migrations from regular migrations ===
+=== Call migrations directly ===
*vendor/plugins/yaffle/lib/yaffle.rb:*
@@ -91,7 +91,7 @@ end
NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
-== Generating migrations ==
+=== 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:
diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
deleted file mode 100644
index e328c04a79..0000000000
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ /dev/null
@@ -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.
-
diff --git a/railties/doc/guides/source/creating_plugins/rdoc.txt b/railties/doc/guides/source/creating_plugins/rdoc.txt
new file mode 100644
index 0000000000..0f6f843c42
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/rdoc.txt
@@ -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
+---------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt
new file mode 100644
index 0000000000..c71ba42bb0
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/tasks.txt
@@ -0,0 +1,29 @@
+== 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*
+
+[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.
\ No newline at end of file
--
cgit v1.2.3
From e08af7219795d28fe9e9eb5f0dc2e7488541382e Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Sun, 16 Nov 2008 23:09:12 -0500
Subject: Rails guide: Misc reorganization
---
railties/doc/guides/html/creating_plugins.html | 84 ++++++++++------------
.../guides/source/creating_plugins/core_ext.txt | 27 +------
.../source/creating_plugins/generator_commands.txt | 1 +
.../guides/source/creating_plugins/migrations.txt | 2 +
.../doc/guides/source/creating_plugins/setup.txt | 22 +++++-
.../doc/guides/source/creating_plugins/tests.txt | 6 +-
6 files changed, 65 insertions(+), 77 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index 1762bd95d2..8f32f72458 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -206,12 +206,16 @@ ul#navMain {
To begin just change one thing - move init.rb to rails/init.rb.
+
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:
Now you can add any require statements to lib/yaffle.rb and keep init.rb clean.
2. Tests
-
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:
+
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:
@@ -475,6 +493,7 @@ A test helper method that sets up the database
+
2.1. Test Setup
vendor/plugins/yaffle/test/database.yml:
@@ -565,7 +584,7 @@ ENV['RAILS_ROOT
end
Now whenever you write a test that requires the database, you can call load_schema.
-
2.1. Run the plugin tests
+
2.2. 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:
@@ -628,20 +647,7 @@ rake DB=postgresql
3. 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
-
-
-
-
3.1. 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:
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:
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.
+
+
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:
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.
+
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:
@@ -1800,8 +1791,7 @@ 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 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:
diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
index ca8efc3df1..efef0e1f70 100644
--- a/railties/doc/guides/source/creating_plugins/core_ext.txt
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -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*
diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt
index 5cce81c8bd..3ace3c7318 100644
--- a/railties/doc/guides/source/creating_plugins/generator_commands.txt
+++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt
@@ -137,4 +137,5 @@ To see this work, type:
./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.
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt
index 4dd932734d..d158004ea3 100644
--- a/railties/doc/guides/source/creating_plugins/migrations.txt
+++ b/railties/doc/guides/source/creating_plugins/migrations.txt
@@ -89,6 +89,7 @@ class CreateBirdhouses < ActiveRecord::Migration
end
----------------------------------------------
+.Editor's note:
NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
=== Generate migrations ===
@@ -146,6 +147,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase
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:
diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt
index fcf5b459e6..cd4b6ecb04 100644
--- a/railties/doc/guides/source/creating_plugins/setup.txt
+++ b/railties/doc/guides/source/creating_plugins/setup.txt
@@ -61,4 +61,24 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
-To begin just change one thing - move 'init.rb' to 'rails/init.rb'.
+=== 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.
\ No newline at end of file
diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt
index ef6dab2f9f..47611542cb 100644
--- a/railties/doc/guides/source/creating_plugins/tests.txt
+++ b/railties/doc/guides/source/creating_plugins/tests.txt
@@ -1,13 +1,13 @@
== Tests ==
-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:
+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:*
----------------------------------------------
--
cgit v1.2.3
From eda282f85743961e2910e4e493a2690fa633b94f Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Sun, 16 Nov 2008 23:11:40 -0500
Subject: Re-ran rake guides
---
railties/doc/guides/html/configuring.html | 8 ++++++++
1 file changed, 8 insertions(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html
index ea5f162cb7..55f5d48554 100644
--- a/railties/doc/guides/html/configuring.html
+++ b/railties/doc/guides/html/configuring.html
@@ -326,7 +326,15 @@ after-initializer
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
4.3. Configuring Action View
+
There are only a few configuration options for Action View, starting with four on ActionView::Base:
+
debug_rjs specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is false.
+
warn_cache_misses tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is false.
+
+
default_form_builder tells Rails which form builder to use by default. The default is ActionView::Helpers::FormBuilder.
+
The ERB template handler supplies one additional option:
+
ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -.
4.4. Configuring Action Mailer
+
There are a number of settings available on ActionMailer::Base:
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
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
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
-
create_table :woodpeckers,:force =>truedo|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.
@@ -1141,26 +1143,21 @@ http://www.gnu.org/software/src-highlite -->
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
endend
@@ -1183,7 +1181,6 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
ActionController::Routing::Routes.draw do|map|
- ...
map.yaffles
end
@@ -1253,14 +1250,6 @@ http://www.gnu.org/software/src-highlite -->
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
@@ -1276,6 +1265,16 @@ http://www.gnu.org/software/src-highlite -->
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.
The final plugin should have a directory structure that looks something like this:
@@ -1865,7 +1892,8 @@ Warning, gotchas or tips that might help save users time
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
-| | `-- core_ext.rb
+| | |-- core_ext.rb
+| | `-- routing.rb
| `-- yaffle.rb
|-- pkg
| `-- yaffle-0.0.1.gem
@@ -1881,6 +1909,7 @@ Warning, gotchas or tips that might help save users time
| |-- definition_generator_test.rb
| |-- migration_generator_test.rb
| |-- route_generator_test.rb
+| |-- routes_test.rb
| |-- schema.rb
| |-- test_helper.rb
| |-- woodpecker_test.rb
diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt
index 19f677c5fd..5c3bd20a1b 100644
--- a/railties/doc/guides/source/creating_plugins/appendix.txt
+++ b/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -10,6 +10,32 @@ If you prefer to use RSpec instead of tets, you may be interested in the http://
* 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
+=== 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:
@@ -47,7 +73,8 @@ The final plugin should have a directory structure that looks something like thi
| |-- yaffle
| | |-- acts_as_yaffle.rb
| | |-- commands.rb
-| | `-- core_ext.rb
+| | |-- core_ext.rb
+| | `-- routing.rb
| `-- yaffle.rb
|-- pkg
| `-- yaffle-0.0.1.gem
@@ -63,6 +90,7 @@ The final plugin should have a directory structure that looks something like thi
| |-- definition_generator_test.rb
| |-- migration_generator_test.rb
| |-- route_generator_test.rb
+| |-- routes_test.rb
| |-- schema.rb
| |-- test_helper.rb
| |-- woodpecker_test.rb
diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
index e38cf8251e..7afdef032d 100644
--- a/railties/doc/guides/source/creating_plugins/controllers.txt
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -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
diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
index efef0e1f70..cbedb9eaf2 100644
--- a/railties/doc/guides/source/creating_plugins/core_ext.txt
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -67,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]
---------------------------------------------------
@@ -86,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]
---------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt
index 3ace3c7318..f60ea3d8f1 100644
--- a/railties/doc/guides/source/creating_plugins/generator_commands.txt
+++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt
@@ -17,14 +17,6 @@ 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
@@ -43,13 +35,13 @@ class RouteGeneratorTest < Test::Unit::TestCase
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)
+ assert_match /map\.yaffles/, File.read(routes_path)
end
def test_destroys_route
content = <<-END
ActionController::Routing::Routes.draw do |map|
- map.yaffle
+ map.yaffles
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
@@ -57,8 +49,19 @@ class RouteGeneratorTest < Test::Unit::TestCase
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)
+ 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
-----------------------------------------------------------
@@ -86,7 +89,7 @@ module Yaffle #:nodoc:
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"}
+ gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"}
end
end
end
@@ -94,7 +97,7 @@ module Yaffle #:nodoc:
module Destroy
def yaffle_route
logger.route "map.yaffle"
- gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, ''
+ gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, ''
end
end
diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt
index eb0fbb5ee9..8ef46561d1 100644
--- a/railties/doc/guides/source/creating_plugins/generators.txt
+++ b/railties/doc/guides/source/creating_plugins/generators.txt
@@ -32,14 +32,6 @@ 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
@@ -54,6 +46,16 @@ class DefinitionGeneratorTest < Test::Unit::TestCase
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
------------------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt
index c2273813dd..fa4227be41 100644
--- a/railties/doc/guides/source/creating_plugins/helpers.txt
+++ b/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -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
----------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt
index d158004ea3..e7d2e09069 100644
--- a/railties/doc/guides/source/creating_plugins/migrations.txt
+++ b/railties/doc/guides/source/creating_plugins/migrations.txt
@@ -108,29 +108,21 @@ This example will demonstrate how to use one of the built-in generator methods n
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
+ 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", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
+ 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)
@@ -138,12 +130,21 @@ class MigrationGeneratorTest < Test::Unit::TestCase
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)
+ 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
------------------------------------------------------------------
@@ -156,7 +157,7 @@ After running the test with 'rake' you can make it pass with:
[source, ruby]
------------------------------------------------------------------
-class YaffleGenerator < Rails::Generator::NamedBase
+class YaffleMigrationGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
@@ -169,6 +170,7 @@ class YaffleGenerator < Rails::Generator::NamedBase
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
diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt
index dfe11f9c4e..8b66de0f99 100644
--- a/railties/doc/guides/source/creating_plugins/models.txt
+++ b/railties/doc/guides/source/creating_plugins/models.txt
@@ -66,10 +66,8 @@ 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
----------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt
index cdc20e998e..249176729c 100644
--- a/railties/doc/guides/source/creating_plugins/routes.txt
+++ b/railties/doc/guides/source/creating_plugins/routes.txt
@@ -22,10 +22,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 +29,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 +51,8 @@ module Yaffle #:nodoc:
end
end
end
+
+ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
*config/routes.rb*
@@ -61,7 +60,6 @@ end
[source, ruby]
--------------------------------------------------------
ActionController::Routing::Routes.draw do |map|
- ...
map.yaffles
end
--------------------------------------------------------
diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt
index c71ba42bb0..d848c2cfa1 100644
--- a/railties/doc/guides/source/creating_plugins/tasks.txt
+++ b/railties/doc/guides/source/creating_plugins/tasks.txt
@@ -19,9 +19,7 @@ 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.
--
cgit v1.2.3
From f22b686ebb8b8606e752188aa072b40700f01f54 Mon Sep 17 00:00:00 2001
From: Jeff Dean
Date: Mon, 17 Nov 2008 00:17:15 -0500
Subject: Plugin guide: re-ran rake guides
---
railties/doc/guides/html/creating_plugins.html | 2 ++
1 file changed, 2 insertions(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html
index ba7962d9ca..0fa9822c0c 100644
--- a/railties/doc/guides/html/creating_plugins.html
+++ b/railties/doc/guides/html/creating_plugins.html
@@ -1149,6 +1149,7 @@ http://www.gnu.org/software/src-highlite -->
endend
+
Once you see the tests fail by running rake, you can make them pass with:
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
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: creating a generator that adds a time-stamped migration.
-
To add a generator to a plugin:
-
-
-
-Write a test
-
-
-
-
-Add your instructions to the manifest method of the generator
-
-
-
-
-Add any necessary template files to the templates directory
-
-
-
-
-Update the USAGE file to add helpful documentation for your generator
-
-
-
+
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:
@@ -1804,7 +1782,7 @@ Warning, gotchas or tips that might help save users time
15. Appendix
-
If you prefer to use RSpec instead of tets, you may be interested in the RSpec Plugin Generator.
+
If you prefer to use RSpec instead of Test::Unit, you may be interested in the RSpec Plugin Generator.
diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt
index 5c3bd20a1b..340c03dd4e 100644
--- a/railties/doc/guides/source/creating_plugins/appendix.txt
+++ b/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -1,6 +1,6 @@
== Appendix ==
-If you prefer to use RSpec instead of tets, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator].
+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 ===
@@ -9,6 +9,7 @@ If you prefer to use RSpec instead of tets, you may be interested in the http://
* 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' ===
diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt
index 8ef46561d1..f856bec7a2 100644
--- a/railties/doc/guides/source/creating_plugins/generators.txt
+++ b/railties/doc/guides/source/creating_plugins/generators.txt
@@ -2,14 +2,7 @@
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:
-
- * Write a test
- * Add your instructions to the 'manifest' method of the generator
- * Add any necessary template files to the templates directory
- * Update the USAGE file to add helpful documentation for your generator
+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 ===
diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt
index 249176729c..dc1bf09fd1 100644
--- a/railties/doc/guides/source/creating_plugins/routes.txt
+++ b/railties/doc/guides/source/creating_plugins/routes.txt
@@ -1,6 +1,8 @@
== 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*
--
cgit v1.2.3
From 896cff4ffb2bb72c0c7d8bbf90fb27817f8c0e5c Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
Date: Mon, 17 Nov 2008 06:41:32 -0600
Subject: Fix bad link in Getting Started guide
---
railties/doc/guides/html/getting_started_with_rails.html | 2 +-
railties/doc/guides/source/getting_started_with_rails.txt | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html
index 5111d0c645..2912bae98d 100644
--- a/railties/doc/guides/html/getting_started_with_rails.html
+++ b/railties/doc/guides/html/getting_started_with_rails.html
@@ -1990,7 +1990,7 @@ http://www.gnu.org/software/src-highlite -->
diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt
index bae8f9a4fd..00c6d52eef 100644
--- a/railties/doc/guides/source/getting_started_with_rails.txt
+++ b/railties/doc/guides/source/getting_started_with_rails.txt
@@ -1219,7 +1219,7 @@ Note that each post has its own individual comments collection, accessible as +@
Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources:
-* The link:http://manuals.rubyonrails.org/[Ruby On Rails guides]
+* The link:http://guides.rubyonrails.org/[Ruby On Rails guides]
* The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list]
* The #rubyonrails channel on irc.freenode.net
* The link:http://wiki.rubyonrails.org/rails[Rails wiki]
--
cgit v1.2.3
From 74569f3e204b92e7c96a920b9bfde785323c61f4 Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
Date: Mon, 17 Nov 2008 08:37:59 -0600
Subject: Structure change to AR Associations Guide
---
railties/doc/guides/html/association_basics.html | 7 +++++--
railties/doc/guides/source/association_basics.txt | 10 ++++++++--
2 files changed, 13 insertions(+), 4 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html
index 9159eaab2a..e8cad6c220 100644
--- a/railties/doc/guides/html/association_basics.html
+++ b/railties/doc/guides/html/association_basics.html
@@ -742,7 +742,9 @@ customer.orders
3.2. Avoiding Name Collisions
You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.
3.3. Updating the Schema
-
Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
+
Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For belongs_to associations you need to create foreign keys, and for has_and_belongs_to_many associations you need to create the appropriate join table.
+
3.3.1. Creating Foreign Keys for belongs_to Associations
+
When you declare a belongs_to association, you need to create foreign keys as appropriate. For example, consider this model:
end
If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.
-
Second, if you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+
3.3.2. Creating Join Tables for has_and_belongs_to_many Associations
+
If you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt
index 5ba616642b..e0c9ee35d3 100644
--- a/railties/doc/guides/source/association_basics.txt
+++ b/railties/doc/guides/source/association_basics.txt
@@ -396,7 +396,11 @@ You are not free to use just any name for your associations. Because creating an
=== Updating the Schema
-Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:
+Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table.
+
+==== Creating Foreign Keys for +belongs_to+ Associations
+
+When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model:
[source, ruby]
-------------------------------------------------------
@@ -426,7 +430,9 @@ end
If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key.
-Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
+==== Creating Join Tables for +has_and_belongs_to_many+ Associations
+
+If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.
WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers".
--
cgit v1.2.3
From e1e0c126176cd7d3537c42df10e1ea6622a9ea14 Mon Sep 17 00:00:00 2001
From: Tore Darell
Date: Mon, 17 Nov 2008 22:16:42 +0100
Subject: Fix various typos, add note about X-Sendfile to AC guide
---
railties/doc/guides/source/actioncontroller_basics/cookies.txt | 2 +-
railties/doc/guides/source/actioncontroller_basics/filters.txt | 4 ++--
.../guides/source/actioncontroller_basics/parameter_filtering.txt | 4 ++--
.../source/actioncontroller_basics/request_response_objects.txt | 6 +++---
railties/doc/guides/source/actioncontroller_basics/streaming.txt | 2 +-
railties/doc/guides/source/actioncontroller_basics/verification.txt | 2 +-
6 files changed, 10 insertions(+), 10 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/railties/doc/guides/source/actioncontroller_basics/cookies.txt
index 88b99de3ee..9c30d29db4 100644
--- a/railties/doc/guides/source/actioncontroller_basics/cookies.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/cookies.txt
@@ -31,4 +31,4 @@ class CommentsController < ApplicationController
end
-----------------------------------------
-Note that while for session values, you set the key to `nil`, to delete a cookie value, you should use `cookies.delete(:key)`.
+Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`.
diff --git a/railties/doc/guides/source/actioncontroller_basics/filters.txt b/railties/doc/guides/source/actioncontroller_basics/filters.txt
index df67977efd..09a4bdf4f6 100644
--- a/railties/doc/guides/source/actioncontroller_basics/filters.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/filters.txt
@@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base
end
---------------------------------
-In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter` :
+In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter`:
[source, ruby]
---------------------------------
@@ -49,7 +49,7 @@ class LoginsController < Application
end
---------------------------------
-Now, the +LoginsController+'s "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+Now, the LoginsController's `new` and `create` actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
=== After Filters and Around Filters ===
diff --git a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
index e29f631038..0013492b73 100644
--- a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt
@@ -1,6 +1,6 @@
== Parameter Filtering ==
-Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+Rails keeps a log file for each environment (development, test and production) in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
[source, ruby]
-------------------------
@@ -11,4 +11,4 @@ class ApplicationController < ActionController::Base
end
-------------------------
-The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
+The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
diff --git a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
index 07a8ec2574..846c24052d 100644
--- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt
@@ -7,13 +7,13 @@ In every controller there are two accessor methods pointing to the request and t
The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are:
* host - The hostname used for this request.
- * domain - The hostname without the first segment (usually "www").
+ * domain(n=2) - The hostname's first `n` segments, starting from the right (the TLD)
* format - The content type requested by the client.
* method - The HTTP method used for the request.
- * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
+ * get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD.
* headers - Returns a hash containing the headers associated with the request.
* port - The port number (integer) used for the request.
- * protocol - The protocol used for the request.
+ * protocol - Returns a string containing the prototol used plus "://", for example "http://"
* query_string - The query string part of the URL - everything after "?".
* remote_ip - The IP address of the client.
* url - The entire URL used for the request.
diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt
index dc8ebe6d55..2a930835ee 100644
--- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt
@@ -52,7 +52,7 @@ This will read and stream the file 4Kb at the time, avoiding loading the entire
WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
-TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the `:x_sendfile` option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the `X-Sendfile` header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.
=== RESTful Downloads ===
diff --git a/railties/doc/guides/source/actioncontroller_basics/verification.txt b/railties/doc/guides/source/actioncontroller_basics/verification.txt
index 5d8ee6117e..a4522a0102 100644
--- a/railties/doc/guides/source/actioncontroller_basics/verification.txt
+++ b/railties/doc/guides/source/actioncontroller_basics/verification.txt
@@ -25,7 +25,7 @@ class LoginsController < ApplicationController
end
---------------------------------------
-Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter:
+Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the `new` action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter:
[source, ruby]
---------------------------------------
--
cgit v1.2.3
From 047657cdfb7ad63ede151d84fbb922d63f641437 Mon Sep 17 00:00:00 2001
From: Sven Fuchs
Date: Tue, 18 Nov 2008 00:41:06 +0100
Subject: initial draft for i18n guide
---
railties/doc/guides/source/i18n.txt | 541 +++++++++++++++++++++++++++++++++++
railties/doc/guides/source/index.txt | 10 +
2 files changed, 551 insertions(+)
create mode 100644 railties/doc/guides/source/i18n.txt
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt
new file mode 100644
index 0000000000..c9867ba0ac
--- /dev/null
+++ b/railties/doc/guides/source/i18n.txt
@@ -0,0 +1,541 @@
+The Rails Internationalization API
+==================================
+
+The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.
+
+== How I18n in Ruby on Rails works
+
+Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on:
+
+* providing support for English and similar languages out of the box
+* making it easy to customize and extend everything for other languages
+
+=== The overall architecture of the library
+
+To solve this the Ruby I18n gem is split into two parts:
+
+* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
+* A shipped backend (which is intentionally named the Simple backend) that implements these methods.
+
+As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one.
+
+=== The public I18n API
+
+We will go into more detail about the public methods later but here's a quick overview. The most important methods are:
+
+[source, ruby]
+-------------------------------------------------------
+translate # lookup translations
+localize # localize Date and Time objects to local formats
+-------------------------------------------------------
+
+There are also attribute readers and writers for the following attributes:
+
+[source, ruby]
+-------------------------------------------------------
+load_path # announce your custom translation files
+locale # get and set the current locale
+default_locale # get and set the default locale
+exception_handler # use a different exception_handler
+backend # use a different backend
+-------------------------------------------------------
+
+== Walkthrough: setup a simple I18n'ed Rails application
+
+There are just a few, simple steps to get up and running with a I18n support for your application.
+
+=== Configure the I18n module
+
+First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.
+
+You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:
+
+[source, ruby]
+-------------------------------------------------------
+# in config/initializer/locale.rb
+
+# tell the I18n library where to find your translations
+I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
+
+# you can omit this if you're happy with English as a default locale
+I18n.default_locale = :"pt-BR"
+-------------------------------------------------------
+
+I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
+
+=== Set the locale in each request
+
+By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English).
+
+If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
+
+[source, ruby]
+-------------------------------------------------------
+before_filter :set_locale
+def set_locale
+ # if this is nil then I18n.default_locale will be used
+ I18n.locale = params[:locale]
+end
+-------------------------------------------------------
+
+This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).
+
+Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.
+
+=== Internationalize your application
+
+The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.
+
+So, let's internationalize something. You most probably have something like this in one of your applications:
+
+[source, ruby]
+-------------------------------------------------------
+# config/routes.rb
+ActionController::Routing::Routes.draw do |map|
+ map.root :controller => 'home', :action => 'index'
+end
+
+# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+ def index
+ flash[:notice] = "Hello flash!"
+ end
+end
+
+# app/views/home/index.html.erb
+
Hello world!
+
<%= flash[:notice] %>
+-------------------------------------------------------
+
+TODO screenshot
+
+Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
+
+[source, ruby]
+-------------------------------------------------------
+# app/controllers/home_controller.rb
+class HomeController < ApplicationController
+ def index
+ flash[:notice] = t(:hello_flash)
+ end
+end
+
+# app/views/home/index.html.erb
+
<%=t :hello_world %>
+
<%= flash[:notice] %>
+-------------------------------------------------------
+
+TODO insert note about #t helper compared to I18n.t
+
+TODO insert note/reference about structuring translation keys
+
+When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.
+
+TODO screenshot
+
+So let's add the missing translations (i.e. do the "localization" part):
+
+[source, ruby]
+-------------------------------------------------------
+# lib/locale/en-US.yml
+en-US:
+ hello_world: Hello World
+ hello_flash: Hello Flash
+
+# lib/locale/pirate.yml
+pirate:
+ hello_world: Ahoy World
+ hello_flash: Ahoy Flash
+-------------------------------------------------------
+
+There you go. Your application now shows:
+
+TODO screenshot
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'store.title'
+I18n.l Time.now
+-------------------------------------------------------
+
+
+== Overview of the I18n API features
+
+The following purposes are covered:
+
+* lookup translations
+* interpolate data into translations
+* pluralize translations
+* localize dates, numbers, currency etc.
+
+=== Looking up translations
+
+==== Basic lookup, scopes and nested keys
+
+Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :message
+I18n.t 'message'
+-------------------------------------------------------
+
+translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :invalid, :scope => [:active_record, :error_messages]
+-------------------------------------------------------
+
+This looks up the :invalid message in the ActiveRecord error messages.
+
+Additionally, both the key and scopes can be specified as dot separated keys as in:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.translate :"active_record.error_messages.invalid"
+-------------------------------------------------------
+
+Thus the following calls are equivalent:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'active_record.error_messages.invalid'
+I18n.t 'error_messages.invalid', :scope => :active_record
+I18n.t :invalid, :scope => 'active_record.error_messages'
+I18n.t :invalid, :scope => [:active_record, :error_messages]
+-------------------------------------------------------
+
+==== Defaults
+
+When a default option is given its value will be returned if the translation is missing:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :missing, :default => 'Not here'
+# => 'Not here'
+-------------------------------------------------------
+
+If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
+
+E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :missing, :default => [:also_missing, 'Not here']
+# => 'Not here'
+-------------------------------------------------------
+
+==== Bulk and namespace lookup
+
+To lookup multiple translations at once an array of keys can be passed:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t [:odd, :even], :scope => 'active_record.error_messages'
+# => ["must be odd", "must be even"]
+-------------------------------------------------------
+
+Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all ActiveRecord error messages as a Hash with:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'active_record.error_messages'
+# => { :inclusion => "is not included in the list", :exclusion => ... }
+-------------------------------------------------------
+
+=== Interpolation
+
+TODO explain what this is good for
+
+All options besides :default and :scope that are passed to #translate will be interpolated to the translation:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.backend.store_translations 'en-US', :thanks => 'Thanks {{name}}!'
+I18n.translate :thanks, :name => 'Jeremy'
+# => 'Thanks Jeremy!'
+-------------------------------------------------------
+
+If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.
+
+=== Pluralization
+
+TODO explain what this is good for
+
+The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.backend.store_translations 'en-US', :inbox => { # TODO change this
+ :one => '1 message',
+ :other => '{{count}} messages'
+}
+I18n.translate :inbox, :count => 2
+# => '2 messages'
+-------------------------------------------------------
+
+The algorithm for pluralizations in en-US is as simple as:
+
+[source, ruby]
+-------------------------------------------------------
+entry[count == 1 ? 0 : 1]
+-------------------------------------------------------
+
+I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).
+
+If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.
+
+=== Setting and passing a locale
+
+The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.
+
+If no locale is passed I18n.locale is used:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.locale = :'de-DE'
+I18n.t :foo
+I18n.l Time.now
+-------------------------------------------------------
+
+Explicitely passing a locale:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t :foo, :locale => :'de-DE'
+I18n.l Time.now, :locale => :'de-DE'
+-------------------------------------------------------
+
+I18n.locale defaults to I18n.default_locale which defaults to :'en-US'. The default locale can be set like this:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.default_locale = :'de-DE'
+-------------------------------------------------------
+
+== How to store your custom translations
+
+The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2)
+
+For example a Ruby Hash providing translations can look like this:
+
+[source, ruby]
+-------------------------------------------------------
+{
+ :'pt-BR' => {
+ :foo => {
+ :bar => "baz"
+ }
+ }
+}
+-------------------------------------------------------
+
+The equivalent YAML file would look like this:
+
+[source, ruby]
+-------------------------------------------------------
+"pt-BR":
+ foo:
+ bar: baz
+-------------------------------------------------------
+
+As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz".
+
+Here is a "real" example from the ActiveSupport en-US translations YAML file:
+
+[source, ruby]
+-------------------------------------------------------
+"en-US":
+ date:
+ formats:
+ default: "%Y-%m-%d"
+ short: "%b %d"
+ long: "%B %d, %Y"
+-------------------------------------------------------
+
+So, all of the following equivalent lookups will return the :short date format "%B %d":
+
+[source, ruby]
+-------------------------------------------------------
+I18n.t 'date.formats.short'
+I18n.t 'formats.short', :scope => :date
+I18n.t :short, :scope => 'date.formats'
+I18n.t :short, :scope => [:date, :formats]
+-------------------------------------------------------
+
+=== Translations for ActiveRecord models
+
+You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.
+
+For example when you add the following translations:
+
+en-US:
+ activerecord:
+ models:
+ user: Dude
+ attributes:
+ user:
+ login: "Handle"
+ # will translate User attribute "login" as "Handle"
+
+Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
+
+==== Error message scopes
+
+ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.
+
+This gives you quite powerful means to flexibly adjust your messages to your application's needs.
+
+Consider a User model with a validates_presence_of validation for the name attribute like this:
+
+[source, ruby]
+-------------------------------------------------------
+class User < ActiveRecord::Base
+ validates_presence_of :name
+end
+-------------------------------------------------------
+
+The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:
+
+[source, ruby]
+-------------------------------------------------------
+activerecord.errors.messages.models.user.attributes.name.blank
+-------------------------------------------------------
+
+If it's not there it will try:
+
+[source, ruby]
+-------------------------------------------------------
+activerecord.errors.messages.models.user.blank
+-------------------------------------------------------
+
+If this is also not there it will use the default message from:
+
+[source, ruby]
+-------------------------------------------------------
+activerecord.errors.messages.blank
+-------------------------------------------------------
+
+When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up.
+
+For example, you might have an Admin model inheriting from User:
+
+[source, ruby]
+-------------------------------------------------------
+class Admin < User
+ validates_presence_of :name
+end
+-------------------------------------------------------
+
+Then ActiveRecord will look for messages in this order:
+
+[source, ruby]
+-------------------------------------------------------
+activerecord.errors.models.admin.attributes.title.blank
+activerecord.errors.models.admin.blank
+activerecord.errors.models.user.attributes.title.blank
+activerecord.errors.models.user.blank
+activerecord.errors.messages.blank
+-------------------------------------------------------
+
+This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes.
+
+==== Error message interpolation
+
+The translated model name and translated attribute name are always available for interpolation.
+
+So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}".
+
+Count and/or value are available where applicable. Count can be used for pluralization if present:
+
+[grid="all"]
+`---------------------------`----------------`---------------`----------------
+validation with option message interpolation
+validates_confirmation_of - :confirmation -
+validates_acceptance_of - :accepted -
+validates_presence_of - :blank -
+validates_length_of :within, :in :too_short count
+validates_length_of :within, :in :too_long count
+validates_length_of :is :wrong_length count
+validates_length_of :minimum :too_short count
+validates_length_of :maximum :too_long count
+validates_uniqueness_of - :taken value
+validates_format_of - :invalid value
+validates_inclusion_of - :inclusion value
+validates_exclusion_of - :exclusion value
+validates_associated - :invalid value
+validates_numericality_of - :not_a_number value
+validates_numericality_of :odd :odd value
+validates_numericality_of :even :even value
+------------------------------------------------------------------------------
+
+
+==== Translations for the ActiveRecord error_messages_for helper
+
+If you are using the ActiveRecord error_messages_for helper you will want to add translations for it.
+
+Rails ships with the following translations:
+
+[source, ruby]
+-------------------------------------------------------
+"en-US":
+ activerecord:
+ errors:
+ template:
+ header:
+ one: "1 error prohibited this {{model}} from being saved"
+ other: "{{count}} errors prohibited this {{model}} from being saved"
+ body: "There were problems with the following fields:"
+-------------------------------------------------------
+
+
+=== Other translations and localizations
+
+Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers.
+
+TODO list helpers and available keys
+
+== Customize your I18n setup
+
+=== Using different backends
+
+For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
+
+That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
+
+[source, ruby]
+-------------------------------------------------------
+I18n.backend = Globalize::Backend::Static.new
+-------------------------------------------------------
+
+TODO expand this ...? list some backends and their features?
+
+=== Using different exception handlers
+
+TODO
+
+* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
+* Explain the default behaviour.
+* Explain the :raise option
+
+* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
+* Example 2: for tests you might want a handler that just raises all exceptions all the time
+* Example 3: a handler
+
+
+== Resources
+
+
+== Footnotes
+
+(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
+
+(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
+
+== Credits
+
+== NOTES
+
+How to contribute?
+
diff --git a/railties/doc/guides/source/index.txt b/railties/doc/guides/source/index.txt
index 8828e1d313..a5648fb757 100644
--- a/railties/doc/guides/source/index.txt
+++ b/railties/doc/guides/source/index.txt
@@ -113,6 +113,16 @@ This guide covers ways to analyze and optimize your running Rails code.
This guide covers how to build a plugin to extend the functionality of Rails.
***********************************************************
+.link:i18n.html[The Rails Internationalization API]
+***********************************************************
+CAUTION: still a basic draft
+
+This guide introduces you to the basic concepts and features of the Rails I18n API and shows you how to localize your application.
+***********************************************************
+
+
+
+
Authors who have contributed to complete guides are listed link:authors.html[here].
This work is licensed under a link:http://creativecommons.org/licenses/by-nc-sa/3.0/[Creative Commons Attribution-Noncommercial-Share Alike 3.0 License]
--
cgit v1.2.3
From 90a1a9a2253381ba0799848beadf29232affb8d5 Mon Sep 17 00:00:00 2001
From: Xavier Noria
Date: Tue, 18 Nov 2008 00:41:20 +0100
Subject: adding a config file for asciidoc, needs latest mizuho to take effect
---
railties/doc/guides/asciidoc.conf | 26 ++++++++++++++++++++++++++
1 file changed, 26 insertions(+)
create mode 100644 railties/doc/guides/asciidoc.conf
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/asciidoc.conf b/railties/doc/guides/asciidoc.conf
new file mode 100644
index 0000000000..f8e0c0a32c
--- /dev/null
+++ b/railties/doc/guides/asciidoc.conf
@@ -0,0 +1,26 @@
+# Asciidoc substitutes some characters by default, those are called
+# "replacements" in the docs. For example => becomes a unicode arrow.
+#
+# We override replacements to allow copy & paste of source code.
+
+[replacements]
+
+# Ellipsis
+(? right arrow
+(? right double arrow
+(?
Date: Tue, 18 Nov 2008 10:50:21 -0600
Subject: FIx minor errors in Getting Started & Associations guides
---
railties/doc/guides/source/association_basics.txt | 8 ++++----
railties/doc/guides/source/getting_started_with_rails.txt | 8 ++++----
2 files changed, 8 insertions(+), 8 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt
index e0c9ee35d3..39d92be2d2 100644
--- a/railties/doc/guides/source/association_basics.txt
+++ b/railties/doc/guides/source/association_basics.txt
@@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re
[source, ruby]
-------------------------------------------------------
class Employee < ActiveRecord::Base
- has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
- belongs_to :manager, :class_name => "User"
+ has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
+ belongs_to :manager, :class_name => "Employee"
end
-------------------------------------------------------
@@ -1336,7 +1336,7 @@ end
===== +:offset+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
===== +:order+
@@ -1704,7 +1704,7 @@ end
===== +:offset+
-The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records.
+The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records.
===== +:order+
diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt
index 00c6d52eef..9adcc729a3 100644
--- a/railties/doc/guides/source/getting_started_with_rails.txt
+++ b/railties/doc/guides/source/getting_started_with_rails.txt
@@ -1021,7 +1021,7 @@ class CommentsController < ApplicationController
def show
@post = Post.find(params[:post_id])
- @comment = Comment.find(params[:id])
+ @comment = @post.comments.find(params[:id])
end
def new
@@ -1033,7 +1033,7 @@ class CommentsController < ApplicationController
@post = Post.find(params[:post_id])
@comment = @post.comments.build(params[:comment])
if @comment.save
- redirect_to post_comment_path(@post, @comment)
+ redirect_to post_comment_url(@post, @comment)
else
render :action => "new"
end
@@ -1041,14 +1041,14 @@ class CommentsController < ApplicationController
def edit
@post = Post.find(params[:post_id])
- @comment = Comment.find(params[:id])
+ @comment = @post.comments.find(params[:id])
end
def update
@post = Post.find(params[:post_id])
@comment = Comment.find(params[:id])
if @comment.update_attributes(params[:comment])
- redirect_to post_comment_path(@post, @comment)
+ redirect_to post_comment_url(@post, @comment)
else
render :action => "edit"
end
--
cgit v1.2.3
From 24bc0b267d1c313d78424eeffda6d8eaa5be0c24 Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
Date: Tue, 18 Nov 2008 10:50:42 -0600
Subject: Regenerate Guide HTML
---
.../doc/guides/html/actioncontroller_basics.html | 20 +-
railties/doc/guides/html/association_basics.html | 8 +-
.../guides/html/getting_started_with_rails.html | 8 +-
railties/doc/guides/html/i18n.html | 1079 ++++++++++++++++++++
railties/doc/guides/html/index.html | 13 +
5 files changed, 1110 insertions(+), 18 deletions(-)
create mode 100644 railties/doc/guides/html/i18n.html
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html
index 66563bf1a3..4af157d4f7 100644
--- a/railties/doc/guides/html/actioncontroller_basics.html
+++ b/railties/doc/guides/html/actioncontroller_basics.html
@@ -723,7 +723,7 @@ http://www.gnu.org/software/src-highlite -->
end
-
Note that while for session values, you set the key to nil, to delete a cookie value, you should use cookies.delete(:key).
+
Note that while for session values you set the key to nil, to delete a cookie value you should use cookies.delete(:key).
6. Filters
@@ -767,7 +767,7 @@ http://www.gnu.org/software/src-highlite -->
end
-
In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter :
+
In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter:
end
-
Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
+
Now, the LoginsController's new and create actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.
6.1. After Filters and Around Filters
In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.
@@ -872,7 +872,7 @@ http://www.gnu.org/software/src-highlite -->
end
-
Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:
+
Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the new action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:
-
It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
+
It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the :x_sendfile option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the X-Sendfile header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.
Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The filter_parameter_logging method can be used to filter out sensitive information from the log. It works by replacing certain values in the params hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
+
Rails keeps a log file for each environment (development, test and production) in the log folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The filter_parameter_logging method can be used to filter out sensitive information from the log. It works by replacing certain values in the params hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password":
end
-
The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.
+
The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.
13. Rescue
diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html
index e8cad6c220..3eea8b421f 100644
--- a/railties/doc/guides/html/association_basics.html
+++ b/railties/doc/guides/html/association_basics.html
@@ -687,8 +687,8 @@ by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
With this setup, you can retrieve @employee.subordinates and @employee.manager.
@@ -1941,7 +1941,7 @@ http://www.gnu.org/software/src-highlite -->
end
:offset
-
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
+
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.
:order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
@@ -2412,7 +2412,7 @@ http://www.gnu.org/software/src-highlite -->
end
:offset
-
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.
+
The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.
:order
The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).
The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application.
+
+
+
1. How I18n in Ruby on Rails works
+
+
Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on:
+
+
+
+providing support for English and similar languages out of the box
+
+
+
+
+making it easy to customize and extend everything for other languages
+
+
+
+
1.1. The overall architecture of the library
+
To solve this the Ruby I18n gem is split into two parts:
+
+
+
+The public API which is just a Ruby module with a bunch of public methods and definitions how the library works.
+
+
+
+
+A shipped backend (which is intentionally named the Simple backend) that implements these methods.
+
+
+
+
As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one.
+
1.2. The public I18n API
+
We will go into more detail about the public methods later but here's a quick overview. The most important methods are:
+
+
+
translate # lookup translations
+localize # localize Date and Time objects to local formats
+
+
There are also attribute readers and writers for the following attributes:
+
+
+
load_path # announce your custom translation files
+locale # get and set the current locale
+default_locale # get and set the default locale
+exception_handler # use a different exception_handler
+backend # use a different backend
+
+
+
2. Walkthrough: setup a simple I18n'ed Rails application
+
+
There are just a few, simple steps to get up and running with a I18n support for your application.
+
2.1. Configure the I18n module
+
First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.
+
You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:
+
+
+
# in config/initializer/locale.rb
+
+# tell the I18n library where to find your translations
+I18n.load_path += Dir[ File.join(RAILS_ROOT,'lib','locale','*.{rb,yml}')]
+
+# you can omit this if you're happy with English as a default locale
+I18n.default_locale =:"pt-BR"
+
+
I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
+
2.2. Set the locale in each request
+
By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English).
+
If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
+
+
+
before_filter :set_locale
+def set_locale
+ # if this is nil then I18n.default_locale will be used
+ I18n.locale = params[:locale]
+end
+
+
This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).
+
Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.
+
2.3. Internationalize your application
+
The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.
+
So, let's internationalize something. You most probably have something like this in one of your applications:
Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation:
TODO insert note about #t helper compared to I18n.t
+
TODO insert note/reference about structuring translation keys
+
When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing.
+
TODO screenshot
+
So let's add the missing translations (i.e. do the "localization" part):
Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
+
+
+
I18n.t :message
+I18n.t 'message'
+
+
translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:
If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
+
E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned:
If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised.
+
3.3. Pluralization
+
TODO explain what this is good for
+
The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:
The algorithm for pluralizations in en-US is as simple as:
+
+
+
entry[count ==1?0:1]
+
+
I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).
+
If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.
+
3.4. Setting and passing a locale
+
The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.
You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names.
+
For example when you add the following translations:
+
en-US:
+ activerecord:
+ models:
+ user: Dude
+ attributes:
+ user:
+ login: "Handle"
+ # will translate User attribute "login" as "Handle"
+
Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle".
+
4.1.1. Error message scopes
+
ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.
+
This gives you quite powerful means to flexibly adjust your messages to your application's needs.
+
Consider a User model with a validates_presence_of validation for the name attribute like this:
+
+
+
class User < ActiveRecord::Base
+ validates_presence_of :name
+end
+
+
The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:
This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes.
+
4.1.2. Error message interpolation
+
The translated model name and translated attribute name are always available for interpolation.
+
+
Count and/or value are available where applicable. Count can be used for pluralization if present:
+
+
+
+
+
+
+
+
+
+ validation
+
+
+ with option
+
+
+ message
+
+
+ interpolation
+
+
+
+
+ validates_confirmation_of
+
+
+ -
+
+
+ :confirmation
+
+
+ -
+
+
+
+
+ validates_acceptance_of
+
+
+ -
+
+
+ :accepted
+
+
+ -
+
+
+
+
+ validates_presence_of
+
+
+ -
+
+
+ :blank
+
+
+ -
+
+
+
+
+ validates_length_of
+
+
+ :within, :in
+
+
+ :too_short
+
+
+ count
+
+
+
+
+ validates_length_of
+
+
+ :within, :in
+
+
+ :too_long
+
+
+ count
+
+
+
+
+ validates_length_of
+
+
+ :is
+
+
+ :wrong_length
+
+
+ count
+
+
+
+
+ validates_length_of
+
+
+ :minimum
+
+
+ :too_short
+
+
+ count
+
+
+
+
+ validates_length_of
+
+
+ :maximum
+
+
+ :too_long
+
+
+ count
+
+
+
+
+ validates_uniqueness_of
+
+
+ -
+
+
+ :taken
+
+
+ value
+
+
+
+
+ validates_format_of
+
+
+ -
+
+
+ :invalid
+
+
+ value
+
+
+
+
+ validates_inclusion_of
+
+
+ -
+
+
+ :inclusion
+
+
+ value
+
+
+
+
+ validates_exclusion_of
+
+
+ -
+
+
+ :exclusion
+
+
+ value
+
+
+
+
+ validates_associated
+
+
+ -
+
+
+ :invalid
+
+
+ value
+
+
+
+
+ validates_numericality_of
+
+
+ -
+
+
+ :not_a_number
+
+
+ value
+
+
+
+
+ validates_numericality_of
+
+
+ :odd
+
+
+ :odd
+
+
+ value
+
+
+
+
+ validates_numericality_of
+
+
+ :even
+
+
+ :even
+
+
+ value
+
+
+
+
+
+
4.1.3. Translations for the ActiveRecord error_messages_for helper
+
If you are using the ActiveRecord error_messages_for helper you will want to add translations for it.
+
Rails ships with the following translations:
+
+
+
"en-US":
+ activerecord:
+ errors:
+ template:
+ header:
+ one:"1 error prohibited this {{model}} from being saved"
+ other:"{{count}} errors prohibited this {{model}} from being saved"
+ body:"There were problems with the following fields:"
+
+
4.2. Other translations and localizations
+
Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers.
+
TODO list helpers and available keys
+
+
5. Customize your I18n setup
+
+
5.1. Using different backends
+
For several reasons the shipped Simple backend only does the "simplest thing that ever could work" for Ruby on Rails (1) … which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.
+
That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:
+
+
+
I18n.backend = Globalize::Backend::Static.new
+
+
TODO expand this …? list some backends and their features?
+
5.2. Using different exception handlers
+
TODO
+
+
+
+Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend.
+
+
+
+
+Explain the default behaviour.
+
+
+
+
+Explain the :raise option
+
+
+
+
+Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing"
+
+
+
+
+Example 2: for tests you might want a handler that just raises all exceptions all the time
+
+
+
+
+Example 3: a handler
+
+
+
+
+
6. Resources
+
+
+
7. Footnotes
+
+
(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.
+
(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.
+
+
8. Credits
+
+
+
9. NOTES
+
+
How to contribute?
+
+
+
+
+
+
diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html
index 991b10c7e8..45e131012e 100644
--- a/railties/doc/guides/html/index.html
+++ b/railties/doc/guides/html/index.html
@@ -338,6 +338,19 @@ of your code.
default_form_builder tells Rails which form builder to use by default. The default is ActionView::Helpers::FormBuilder.
The ERB template handler supplies one additional option:
-
ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -.
+
ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -. See the ERB documentation for more information.
4.4. Configuring Action Mailer
There are a number of settings available on ActionMailer::Base:
+
template_root gives the root folder for Action Mailer templates.
+
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 Mailer. Set to nil to disable logging.
+
smtp_settings allows detailed configuration for the :smtp delivery method. It accepts a hash of options, which can include any of these options:
+
+
+
+<tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
+
+
+
+
+<tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it.
+
+
+
+
+<tt>:domain</tt> - If you need to specify a HELO domain, you can do it here.
+
+
+
+
+<tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting.
+
+
+
+
+<tt>:password</tt> - If your mail server requires authentication, set the password in this setting.
+
+
+
+
+<tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>.
+
+
+
+
sendmail_settings allows detailed configuration for the sendmail delivery method. It accepts a hash of options, which can include any of these options:
+
+
+
+<tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>.
+
+
+
+
+<tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>.
+
+
+
+
raise_delivery_errors specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
+
delivery_method defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.
+
perform_deliveries specifies whether mail will actually be delivered. By default this is true; it can be convenient to set it to false for testing.
+
default_charset tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to utf-8.
+
default_content_type specifies the default content type used for the main part of the message. It defaults to "text/plain"
+
default_mime_version is the default MIME version for the message. It defaults to 1.0.
+
default_implicit_parts_order - When a message is built implicitly (i.e. multiple parts are assembled from templates
+which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
+<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client
+and appear last in the mime encoded message.
4.5. Configuring Active Resource
+
There is a single configuration setting available on ActiveResource::Base:
+
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 Active Resource. Set to nil to disable logging.
4.6. Configuring Active Support
+
There are a few configuration options available in Active Support:
+
ActiveSupport::BufferedLogger.silencer is set to false to disable the ability to silence logging in a block. The default is true.
+
ActiveSupport::Cache::Store.logger specifies the logger to use within cache store operations.
+
ActiveSupport::Logger.silencer is set to false to disable the ability to silence logging in a block. The default is true.
+
4.7. Configuring Active Model
+
Active Model currently has a single configuration setting:
+
+ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages.
Rakefile
-32: rdoc.options << -A cattr_accessor=object
@@ -475,6 +436,8 @@ need to look for def self. ?
+
+
diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt
index 1fb73abbb8..945e48cd45 100644
--- a/railties/doc/guides/source/configuring.txt
+++ b/railties/doc/guides/source/configuring.txt
@@ -113,172 +113,82 @@ There are only a few configuration options for Action View, starting with four o
The ERB template handler supplies one additional option:
-+ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+.
++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the link:http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/[ERB documentation] for more information.
=== Configuring Action Mailer
There are a number of settings available on +ActionMailer::Base+:
++template_root+ gives the root folder for Action Mailer templates.
++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 Mailer. Set to nil to disable logging.
-=== Configuring Active Resource
-
-=== Configuring Active Support
-
-== Using Initializers
- organization, controlling load order
-
-== Using an After-Initializer
++smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options:
-== Rails Environment Settings
-
-ENV
-
-== Changelog ==
-
-http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket]
+* :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting.
+* :port - On the off chance that your mail server doesn't run on port 25, you can change it.
+* :domain - If you need to specify a HELO domain, you can do it here.
+* :user_name - If your mail server requires authentication, set the username in this setting.
+* :password - If your mail server requires authentication, set the password in this setting.
+* :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5.
-* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy]
++sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options:
+* :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail.
+* :arguments - The command line arguments. Defaults to -i -t.
-actionmailer/lib/action_mailer/base.rb
-257: cattr_accessor :logger
-267: cattr_accessor :smtp_settings
-273: cattr_accessor :sendmail_settings
-276: cattr_accessor :raise_delivery_errors
-282: cattr_accessor :perform_deliveries
-285: cattr_accessor :deliveries
-288: cattr_accessor :default_charset
-291: cattr_accessor :default_content_type
-294: cattr_accessor :default_mime_version
-297: cattr_accessor :default_implicit_parts_order
-299: cattr_reader :protected_instance_variables
-
-actionmailer/Rakefile
-36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
-
-actionpack/lib/action_controller/base.rb
-263: cattr_reader :protected_instance_variables
-273: cattr_accessor :asset_host
-279: cattr_accessor :consider_all_requests_local
-285: cattr_accessor :allow_concurrency
-317: cattr_accessor :param_parsers
-321: cattr_accessor :default_charset
-325: cattr_accessor :logger
-329: cattr_accessor :resource_action_separator
-333: cattr_accessor :resources_path_names
-337: cattr_accessor :request_forgery_protection_token
-341: cattr_accessor :optimise_named_routes
-351: cattr_accessor :use_accept_header
-361: cattr_accessor :relative_url_root
++raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+.
-actionpack/lib/action_controller/caching/pages.rb
-55: cattr_accessor :page_cache_directory
-58: cattr_accessor :page_cache_extension
++delivery_method+ defines the delivery method. The allowed values are :smtp (default), :sendmail, and :test.
-actionpack/lib/action_controller/caching.rb
-37: cattr_reader :cache_store
-48: cattr_accessor :perform_caching
++perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing.
-actionpack/lib/action_controller/dispatcher.rb
-98: cattr_accessor :error_file_path
++default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+.
-actionpack/lib/action_controller/mime_type.rb
-24: cattr_reader :html_types, :unverifiable_types
++default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain"
-actionpack/lib/action_controller/rescue.rb
-36: base.cattr_accessor :rescue_responses
-40: base.cattr_accessor :rescue_templates
++default_mime_version+ is the default MIME version for the message. It defaults to +1.0+.
-actionpack/lib/action_controller/session/active_record_store.rb
-60: cattr_accessor :data_column_name
-170: cattr_accessor :connection
-173: cattr_accessor :table_name
-177: cattr_accessor :session_id_column
-181: cattr_accessor :data_column
-282: cattr_accessor :session_class
++default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates
+which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to
+["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client
+and appear last in the mime encoded message.
-actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
-44: cattr_accessor :included_tags, :instance_writer => false
-
-actionpack/lib/action_view/base.rb
-189: cattr_accessor :debug_rjs
-193: cattr_accessor :warn_cache_misses
-
-actionpack/lib/action_view/helpers/active_record_helper.rb
-7: cattr_accessor :field_error_proc
-
-actionpack/lib/action_view/helpers/form_helper.rb
-805: cattr_accessor :default_form_builder
-
-actionpack/lib/action_view/template_handlers/erb.rb
-47: cattr_accessor :erb_trim_mode
-
-actionpack/test/active_record_unit.rb
-5: cattr_accessor :able_to_connect
-6: cattr_accessor :connected
+=== Configuring Active Resource
-actionpack/test/controller/filters_test.rb
-286: cattr_accessor :execution_log
+There is a single configuration setting available on +ActiveResource::Base+:
-actionpack/test/template/form_options_helper_test.rb
-3:TZInfo::Timezone.cattr_reader :loaded_zones
++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 Active Resource. Set to nil to disable logging.
-activemodel/lib/active_model/errors.rb
-28: cattr_accessor :default_error_messages
+=== Configuring Active Support
-activemodel/Rakefile
-19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
+There are a few configuration options available in Active Support:
-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
++ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
++ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations.
-activeresource/lib/active_resource/base.rb
-206: cattr_accessor :logger
++ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+.
-activeresource/Rakefile
-43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
-
-activesupport/lib/active_support/buffered_logger.rb
-17: cattr_accessor :silencer
-
-activesupport/lib/active_support/cache.rb
-81: cattr_accessor :logger
+=== Configuring Active Model
-activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
-5:# cattr_accessor :hair_colors
-10: def cattr_reader(*syms)
-29: def cattr_writer(*syms)
-50: def cattr_accessor(*syms)
-51: cattr_reader(*syms)
-52: cattr_writer(*syms)
+Active Model currently has a single configuration setting:
-activesupport/lib/active_support/core_ext/logger.rb
-34: cattr_accessor :silencer
++ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages.
-activesupport/test/core_ext/class/attribute_accessor_test.rb
-6: cattr_accessor :foo
-7: cattr_accessor :bar, :instance_writer => false
+== Using Initializers
+ organization, controlling load order
-activesupport/test/core_ext/module/synchronization_test.rb
-6: @target.cattr_accessor :mutex, :instance_writer => false
+== Using an After-Initializer
-railties/doc/guides/html/creating_plugins.html
-786: cattr_accessor :yaffle_text_field,:yaffle_date_field
-860: cattr_accessor :yaffle_text_field,:yaffle_date_field
+== Rails Environment Settings
-railties/lib/rails_generator/base.rb
-93: cattr_accessor :logger
+ENV
-railties/Rakefile
-265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object'
+== Changelog ==
-railties/test/rails_info_controller_test.rb
-12: cattr_accessor :local_request
+http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket]
-Rakefile
-32: rdoc.options << '-A cattr_accessor=object'
+* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy]
need to look for def self. ???
--
cgit v1.2.3
From b60971ad6b19a3cd72a972b459e94059d24c0848 Mon Sep 17 00:00:00 2001
From: CassioMarques
Date: Tue, 18 Nov 2008 19:14:51 -0200
Subject: Added note about update_attribute not triggering validation
---
.../doc/guides/html/activerecord_validations_callbacks.html | 10 +++++++++-
.../doc/guides/source/activerecord_validations_callbacks.txt | 5 ++++-
2 files changed, 13 insertions(+), 2 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index b6cb481eab..097ef706ca 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -362,6 +362,14 @@ http://www.gnu.org/software/src-highlite -->
=> false
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+
+
+
+
+
+
There are four methods that when called will trigger validation: save, save!, update_attributes and update_attributes!. There is one method left, which is update_attribute. This method will update the value of an attribute without triggering any validation, so be careful when using update_attribute, since it can let you save your objects in an invalid state.
+
+
2.2. The meaning of valid
For verifying if an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The proccess is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.
If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.
+
If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.
+
class User < ActiveRecord::Base
+ validates_presence_of :login,:email
+
+ protected
+ def before_validation
+ ifself.login.nil?
+ self.login = email unless email.blank?
+ end
+ end
+end
+
+
8.3. Registering callbacks by using macro-style class methods
+
The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:
+
+
+
class User < ActiveRecord::Base
+ validates_presence_of :login,:email
+
+ before_validation :ensure_login_has_a_value
+
+ protected
+ def ensure_login_has_a_value
+ ifself.login.nil?
+ self.login = email unless email.blank?
+ end
+ end
+end
+
+
The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.
+
+
+
class User < ActiveRecord::Base
+ validates_presence_of :login,:email
+
+ before_create {|user| user.name = user.login.capitalize if user.name.blank?}
+end
+
+
In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are:
+
+
+
+You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered.
+
+
+
+
+Readability, since your callback declarations will live at the beggining of your models' files.
+
+
+
+
+
+
+
+
+
Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
+
+
+
+
9. Callbacks that get triggered when an objects is saved
+
+
+
+
+before_validation will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid.
+
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index cbd914405e..a369a66bd3 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -477,6 +477,79 @@ person.errors.clear
person.errors # => nil
------------------------------------------------------------------
+== Callbacks
+
+Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database.
+
+=== Callbacks registration
+
+In order to use the available callbacks, you need to registrate them. There are two ways of doing that.
+
+=== Registering callbacks by overriding the callback methods
+
+You can specify the callback method direcly, by overriding it. Let's see how it works using the +before_validation+ callback, which will surprisingly run right before any validation is done.
+
+[source, ruby]
+------------------------------------------------------------------
+class User < ActiveRecord::Base
+ validates_presence_of :login, :email
+
+ protected
+ def before_validation
+ if self.login.nil?
+ self.login = email unless email.blank?
+ end
+ end
+end
+------------------------------------------------------------------
+
+=== Registering callbacks by using macro-style class methods
+
+The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:
+
+[source, ruby]
+------------------------------------------------------------------
+class User < ActiveRecord::Base
+ validates_presence_of :login, :email
+
+ before_validation :ensure_login_has_a_value
+
+ protected
+ def ensure_login_has_a_value
+ if self.login.nil?
+ self.login = email unless email.blank?
+ end
+ end
+end
+------------------------------------------------------------------
+
+The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.
+
+[source, ruby]
+------------------------------------------------------------------
+class User < ActiveRecord::Base
+ validates_presence_of :login, :email
+
+ before_create {|user| user.name = user.login.capitalize if user.name.blank?}
+end
+------------------------------------------------------------------
+
+In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are:
+
+* You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered.
+* Readability, since your callback declarations will live at the beggining of your models' files.
+
+CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
+
+== Callbacks that get triggered when an objects is saved
+
+* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid.
+
+
+
+
+
+
== Changelog
--
cgit v1.2.3
From 2b94b3437e819fbaffb7d5b7cd158efdcf903566 Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Wed, 19 Nov 2008 22:46:37 +1030
Subject: Fixed all points in
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11
---
railties/doc/guides/source/finders.txt | 48 ++++++++++++++++++----------------
1 file changed, 26 insertions(+), 22 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index ad41ef3bd5..6f1329d474 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -13,6 +13,8 @@ This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as
If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases.
+The SQL in your log may have some quoting, and that quoting depends on the backend (MySQL, for example, puts backticks around field and table names). Attempting to copy the raw SQL contained within this guide may not work in your database system. Please consult the database systems manual before attempting to execute any SQL.
+
== The Sample Models
This guide demonstrates finding using the following models:
@@ -52,16 +54,16 @@ Active Record will perform queries on the database for you and is compatible wit
[source, sql]
-------------------------------------------------------
-SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1)
+SELECT * FROM clients WHERE (clients.id = 1)
-------------------------------------------------------
-NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
+NOTE: Because this is a standard table created from a migration in Rails, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column.
If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as:
[source, sql]
-------------------------------------------------------
-SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
+SELECT * FROM clients WHERE (clients.id IN (1,2))
-------------------------------------------------------
-------------------------------------------------------
@@ -76,7 +78,7 @@ Note that if you pass in a list of numbers that the result will be returned as a
NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
-If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
+If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client created in your clients table:
-------------------------------------------------------
>> Client.first
@@ -84,7 +86,7 @@ If you wanted to find the first client you would simply type +Client.first+ and
created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
-------------------------------------------------------
-If you were running script/server you might see the following output:
+If you were reading your log file (the default is log/development.log) you may see something like this:
[source,sql]
-------------------------------------------------------
@@ -93,10 +95,10 @@ SELECT * FROM clients LIMIT 1
Indicating the query that Rails has performed on your database.
-To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
+To find the last Client object you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
-------------------------------------------------------
->> Client.find(:last)
+>> Client.last
=> # "Michael", locked: false, orders_count: 3,
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
-------------------------------------------------------
@@ -106,7 +108,7 @@ To find the last client you would simply type +Client.find(:last)+ and that woul
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
-------------------------------------------------------
-To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
+To find all the Client objects you would simply type +Client.all+ and that would find all the clients in your clients table:
-------------------------------------------------------
>> Client.all
@@ -116,9 +118,9 @@ To find all the clients you would simply type +Client.all+ and that would find a
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
-------------------------------------------------------
-As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
+You may see in Rails code that there are calls to methods such as +Client.find(:all)+, +Client.find(:first)+ and +Client.find(:last)+. These methods are just alternatives to +Client.all+, +Client.first+ and +Client.last+ respectively.
-Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also.
+Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to +find+ will do also.
== Conditions
@@ -132,19 +134,20 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t
=== Array Conditions ===
-Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field.
+Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with +false+ and this will find the first record in the table that has '2' as its value for the +orders_count+ field and +false+ for its locked field.
The reason for doing code like:
[source, ruby]
-------------------------------------------------------
-+Client.first(:conditions => ["orders_count = ?", params[:orders]])+
+Client.first(:conditions => ["orders_count = ?", params[:orders]])
-------------------------------------------------------
instead of:
+[source, ruby]
-------------------------------------------------------
-+Client.first(:conditions => "orders_count = #{params[:orders]}")+
+Client.first(:conditions => "orders_count = #{params[:orders]}")
-------------------------------------------------------
is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string.
@@ -163,7 +166,7 @@ This would generate the proper query which is great for small ranges but not so
[source, sql]
-------------------------------------------------------
-SELECT * FROM +users+ WHERE (created_at IN
+SELECT * FROM users WHERE (created_at IN
('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05',
'2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11',
'2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17',
@@ -183,7 +186,7 @@ Client.all(:conditions => ["created_at IN (?)",
[source, sql]
-------------------------------------------------------
-SELECT * FROM +users+ WHERE (created_at IN
+SELECT * FROM users WHERE (created_at IN
('2007-12-01 00:00:00', '2007-12-01 00:00:01' ...
'2007-12-01 23:59:59', '2007-12-02 00:00:00'))
-------------------------------------------------------
@@ -214,7 +217,7 @@ Client.all(:conditions =>
Just like in Ruby.
-=== Hash Conditions ===
+=== Placeholder Conditions ===
Similar to the array style of params you can also specify keys in your conditions:
@@ -277,7 +280,7 @@ The SQL that would be executed would be something like this:
[source, sql]
-------------------------------------------------------
-SELECT * FROM +orders+ GROUP BY date(created_at)
+SELECT * FROM orders GROUP BY date(created_at)
-------------------------------------------------------
== Read Only
@@ -363,9 +366,9 @@ There's another set of dynamic finders that let you find or create/initialize ob
[source,sql]
-------------------------------------------------------
-SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1
+SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
BEGIN
-INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+)
+INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0')
COMMIT
-------------------------------------------------------
@@ -571,7 +574,7 @@ Which will execute:
[source, sql]
-------------------------------------------------------
-SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1)
+SELECT count(*) AS count_all FROM clients WHERE (first_name = 1)
-------------------------------------------------------
You can also use +include+ or +joins+ for this to do something a little more complex:
@@ -585,8 +588,8 @@ Which will execute:
[source, sql]
-------------------------------------------------------
-SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+
- LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE
+SELECT count(DISTINCT clients.id) AS count_all FROM clients
+ LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE
(clients.first_name = 'name' AND orders.status = 'received')
-------------------------------------------------------
@@ -655,6 +658,7 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
+* Wednesday 16 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment]
* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
--
cgit v1.2.3
From 3e762e8a97d3dbb60e12f369d70f46e2b10e01a0 Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Fri, 21 Nov 2008 11:27:54 +1030
Subject: Updated finders guide based on:
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13
---
railties/doc/guides/source/finders.txt | 16 +++++++++++++---
1 file changed, 13 insertions(+), 3 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 6f1329d474..53de3093e1 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -78,7 +78,7 @@ Note that if you pass in a list of numbers that the result will be returned as a
NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception.
-If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client created in your clients table:
+If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table:
-------------------------------------------------------
>> Client.first
@@ -95,7 +95,7 @@ SELECT * FROM clients LIMIT 1
Indicating the query that Rails has performed on your database.
-To find the last Client object you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
+To find the last Client object you would simply type +Client.last+ and that would find the last client created in your clients table:
-------------------------------------------------------
>> Client.last
@@ -103,6 +103,15 @@ To find the last Client object you would simply type +Client.find(:last)+ and th
created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
-------------------------------------------------------
+If you were reading your log file (the default is log/development.log) you may see something like this:
+
+[source,sql]
+-------------------------------------------------------
+SELECT * FROM clients ORDER BY id DESC LIMIT 1
+-------------------------------------------------------
+
+NOTE: Please be aware that the syntax that Rails uses to find the first record in the table means that it may not be the actual first record. If you want the actual first record based on a field in your table (e.g. +created_at+) specify an order option in your find call. The last method call works differently: it finds the last record on your table based on the primary key column.
+
[source,sql]
-------------------------------------------------------
SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
@@ -658,7 +667,8 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
-* Wednesday 16 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment]
+* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment]
+* November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment]
* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg
* October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg
--
cgit v1.2.3
From 76018a16587611c64a852c4bb9662df56b5cd1f0 Mon Sep 17 00:00:00 2001
From: Mike Gunderloy
Date: Fri, 21 Nov 2008 10:20:21 -0600
Subject: Final changes for 2.2 release notes
---
railties/doc/guides/html/2_2_release_notes.html | 4 ++--
railties/doc/guides/source/2_2_release_notes.txt | 4 ++--
2 files changed, 4 insertions(+), 4 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html
index 1c44c1fcd9..778144b688 100644
--- a/railties/doc/guides/html/2_2_release_notes.html
+++ b/railties/doc/guides/html/2_2_release_notes.html
@@ -974,7 +974,7 @@ The addition of ActiveSupport::Rescuable allows any class to mix in the
-Array#second through Array#tenth as aliases for Array#[1] through Array#[9]
+Array#second through Array#fifth as aliases for Array#[1] through Array#[4]
@@ -994,7 +994,7 @@ The addition of ActiveSupport::Rescuable allows any class to mix in the
-The included TzInfo library has been upgraded to version 0.3.11.
+The included TzInfo library has been upgraded to version 0.3.12.
diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt
index 59701ca24c..6aa9fa19ce 100644
--- a/railties/doc/guides/source/2_2_release_notes.txt
+++ b/railties/doc/guides/source/2_2_release_notes.txt
@@ -365,11 +365,11 @@ Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck
* Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes.
* The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax.
* +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons.
-* +Array#second+ through +Array#tenth+ as aliases for +Array#[1]+ through +Array#[9]+
+* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+
* +Enumerable#many?+ to encapsulate +collection.size > 1+
* +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+.
* +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on.
-* The included TzInfo library has been upgraded to version 0.3.11.
+* The included TzInfo library has been upgraded to version 0.3.12.
* +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+
== Railties
--
cgit v1.2.3
From e04abd574120d80903e728913d37356468de6fbb Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Sun, 23 Nov 2008 21:09:58 +1030
Subject: Updated finders guide to include newcomers find_last_by and
find_by_bang!
---
railties/doc/guides/source/finders.txt | 12 ++++++++++--
1 file changed, 10 insertions(+), 2 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 53de3093e1..55ba744591 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -369,7 +369,14 @@ Client.first(:include => "orders", :conditions =>
== Dynamic finders
-For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+.
+For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+.
+
+You can do +find_last_by_*+ methods too which will find the last record matching your parameter.
+
+You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!('Ryan')+
+
+If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+.
+
There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+:
@@ -382,7 +389,7 @@ INSERT INTO clients (name, updated_at, created_at, orders_count, locked)
COMMIT
-------------------------------------------------------
-+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example:
++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the parameters you passed in. For example:
[source, ruby]
-------------------------------------------------------
@@ -391,6 +398,7 @@ client = Client.find_or_initialize_by_name('Ryan')
will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it.
+
== Finding By SQL
If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query:
--
cgit v1.2.3
From e95f5417e8c15dec4f51afeb69945fdc89f1f2e3 Mon Sep 17 00:00:00 2001
From: Ryan Bigg
Date: Sun, 23 Nov 2008 22:28:05 +1030
Subject: Was very naughty and did not add changelog message to guide.
---
railties/doc/guides/source/finders.txt | 1 +
1 file changed, 1 insertion(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
index 55ba744591..5fc77a5415 100644
--- a/railties/doc/guides/source/finders.txt
+++ b/railties/doc/guides/source/finders.txt
@@ -675,6 +675,7 @@ Thanks to Mike Gunderloy for his tips on creating this guide.
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket]
+* November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+
* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment]
* November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment]
* November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version.
--
cgit v1.2.3
From 490e02b17d26471e74bd9cbdc3ff368f88f6cccb Mon Sep 17 00:00:00 2001
From: CassioMarques
Date: Sun, 23 Nov 2008 16:31:10 -0200
Subject: Added some more text on Active Record callbacks
---
.../html/activerecord_validations_callbacks.html | 137 ++++++++++++++++++++-
.../source/activerecord_validations_callbacks.txt | 48 +++++++-
2 files changed, 177 insertions(+), 8 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index 4b860eeec0..1656cea492 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -282,7 +282,26 @@ ul#navMain {
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+
Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
@@ -952,17 +971,125 @@ Readability, since your callback declarations will live at the beggining of your
-
9. Callbacks that get triggered when an objects is saved
+
9. Available callbacks
+
Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.
+
9.1. Callbacks called both when creating or updating a record.
+
+
+
+before_validation
+
+
+
+
+after_validation
+
+
+
+
+before_save
+
+
+
+
+INSERT OR UPDATE OPERATION
+
+
+
+
+after_save
+
+
+
+
9.2. Callbacks called only when creating a new record.
+
+
+
+before_validation_on_create
+
+
+
+
+after_validation_on_create
+
+
+
+
+before_create
+
+
+
+
+INSERT OPERATION
+
+
+
+
+after_create
+
+
+
+
9.3. Callbacks called only when updating an existing record.
-before_validation will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid.
+before_validation_on_update
+
+
+
+
+after_validation_on_update
+
+
+
+
+before_update
+
+
+
+
+UPDATE OPERATION
+
+
+
+
+after_update
+
+
+
+
9.4. Callbacks called when removing a record from the database.
+
+
+
+before_destroy
+
+
+
+
+DELETE OPERATION
+
+
+
+
+after_destroy
+
The before_destroy and after_destroy callbacks will only be called if you delete the model using either the destroy instance method or one of the destroy or destroy_all class methods of your Active Record class. If you use delete or delete_all no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.
+
9.5. The after_initialize and after_find callbacks
+
The after_initialize callback will be called whenever an Active Record object is instantiated, either by direcly using new or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize method.
+
The after_find callback will be called whenever Active Record loads a record from the database. When used together with after_initialize it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
+
The after_initialize and after_find callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.
+
+
10. Halting Execution
+
+
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean false (not nil) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index a369a66bd3..02cdbcf146 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output:
=> false
------------------------------------------------------------------
-Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
+Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.
CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state.
@@ -541,14 +541,56 @@ In Rails, the preferred way of registering callbacks is by using macro-style cla
CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
-== Callbacks that get triggered when an objects is saved
+== Available callbacks
+
+Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.
-* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid.
+=== Callbacks called both when creating or updating a record.
+* +before_validation+
+* +after_validation+
+* +before_save+
+* *INSERT OR UPDATE OPERATION*
+* +after_save+
+=== Callbacks called only when creating a new record.
+* +before_validation_on_create+
+* +after_validation_on_create+
+* +before_create+
+* *INSERT OPERATION*
+* +after_create+
+=== Callbacks called only when updating an existing record.
+* +before_validation_on_update+
+* +after_validation_on_update+
+* +before_update+
+* *UPDATE OPERATION*
+* +after_update+
+
+=== Callbacks called when removing a record from the database.
+
+* +before_destroy+
+* *DELETE OPERATION*
+* +after_destroy+
+
+The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.
+
+=== The +after_initialize+ and +after_find+ callbacks
+
+The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by direcly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method.
+
+The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.
+
+The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries.
+
+== Halting Execution
+
+As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
+
+
+== Callback classes and objects
--
cgit v1.2.3
From 5df4a6779715859b3a0626b52ddb2e0874f78547 Mon Sep 17 00:00:00 2001
From: Aditya
Date: Sun, 23 Nov 2008 13:34:35 -0500
Subject: Fixed width font changes
---
railties/doc/guides/source/caching_with_rails.txt | 34 +++++++++++------------
1 file changed, 17 insertions(+), 17 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt
index e680b79d55..7a4074570e 100644
--- a/railties/doc/guides/source/caching_with_rails.txt
+++ b/railties/doc/guides/source/caching_with_rails.txt
@@ -10,8 +10,8 @@ need to return to those hungry web clients in the shortest time possible.
This is an introduction to the three types of caching techniques that Rails
provides by default without the use of any third party plugins.
-To get started make sure config.action_controller.perform_caching is set
-to true for your environment. This flag is normally set in the
+To get started make sure `config.action_controller.perform_caching` is set
+to `true` for your environment. This flag is normally set in the
corresponding config/environments/*.rb and caching is disabled by default
there for development and test, and enabled for production.
@@ -45,21 +45,21 @@ end
-----------------------------------------------------
The first time anyone requests products/index, Rails will generate a file
-called index.html and the webserver will then look for that file before it
+called `index.html` and the webserver will then look for that file before it
passes the next request for products/index to your Rails application.
By default, the page cache directory is set to Rails.public_path (which is
-usually set to RAILS_ROOT + "/public") and this can be configured by
-changing the configuration setting ActionController::Base.page_cache_directory. Changing the
-default from /public helps avoid naming conflicts, since you may want to
-put other static html in /public, but changing this will require web
-server reconfiguration to let the web server know where to serve the
-cached files from.
-
-The Page Caching mechanism will automatically add a .html exxtension to
+usually set to `RAILS_ROOT + "/public"`) and this can be configured by
+changing the configuration setting `config.action_controller.page_cache_directory`.
+Changing the default from /public helps avoid naming conflicts, since you may
+want to put other static html in /public, but changing this will require web
+server reconfiguration to let the web server know where to serve the cached
+files from.
+
+The Page Caching mechanism will automatically add a `.html` exxtension to
requests for pages that do not have an extension to make it easy for the
webserver to find those pages and this can be configured by changing the
-configuration setting ActionController::Base.page_cache_extension.
+configuration setting `config.action_controller.page_cache_extension`.
In order to expire this page when a new product is added we could extend our
example controler like this:
@@ -119,8 +119,8 @@ class ProductsController < ActionController
end
-----------------------------------------------------
-And you can also use :if (or :unless) to pass a Proc that specifies when the
-action should be cached. Also, you can use :layout => false to cache without
+And you can also use `:if` (or `:unless`) to pass a Proc that specifies when the
+action should be cached. Also, you can use `:layout => false` to cache without
layout so that dynamic information in the layout such as logged in user info
or the number of items in the cart can be left uncached. This feature is
available as of Rails 2.2.
@@ -164,7 +164,7 @@ could use this piece of code:
The cache block in our example will bind to the action that called it and is
written out to the same place as the Action Cache, which means that if you
-want to cache multiple fragments per action, you should provide an action_suffix to the cache call:
+want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call:
[source, ruby]
-----------------------------------------------------
@@ -172,7 +172,7 @@ want to cache multiple fragments per action, you should provide an action_suffix
All available products:
-----------------------------------------------------
-and you can expire it using the expire_fragment method, like so:
+and you can expire it using the `expire_fragment` method, like so:
[source, ruby]
-----------------------------------------------------
@@ -185,7 +185,7 @@ expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix =
Cache sweeping is a mechanism which allows you to get around having a ton of
expire_{page,action,fragment} calls in your code by moving all the work
-required to expire cached content into a ActionController::Caching::Sweeper
+required to expire cached content into a `ActionController::Caching::Sweeper`
class that is an Observer and looks for changes to an object via callbacks,
and when a change occurs it expires the caches associated with that object n
an around or after filter.
--
cgit v1.2.3
From 54f4be83035bba1e2f1ec44334efff7d7a6cb4fe Mon Sep 17 00:00:00 2001
From: Aditya
Date: Sun, 23 Nov 2008 14:09:36 -0500
Subject: Add config.cache_store blurb and note about Rails using the bundled
memcached-client gem
---
railties/doc/guides/source/caching_with_rails.txt | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt
index 7a4074570e..e29156d4e7 100644
--- a/railties/doc/guides/source/caching_with_rails.txt
+++ b/railties/doc/guides/source/caching_with_rails.txt
@@ -340,8 +340,7 @@ ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
-----------------------------------------------------
4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead.
- Requires the ruby-memcache library:
- gem install ruby-memcache.
+ Rails uses the bundled memcached-client gem by default.
[source, ruby]
-----------------------------------------------------
@@ -355,6 +354,10 @@ ActionController::Base.cache_store = :mem_cache_store, "localhost"
ActionController::Base.cache_store = MyOwnStore.new("parameter")
-----------------------------------------------------
++Note: config.cache_store can be used in place of
+ActionController::Base.cache_store in your Rails::Initializer.run block in
+environment.rb+
+
== Advanced Caching
Along with the built-in mechanisms outlined above, a number of excellent
--
cgit v1.2.3
From f3ac3fafbc6146337592c2dd4a37e5eb06912757 Mon Sep 17 00:00:00 2001
From: Aditya
Date: Sun, 23 Nov 2008 14:32:42 -0500
Subject: Updated with Conditional GET section lifted from Ryan's posts on the
topic
---
railties/doc/guides/source/caching_with_rails.txt | 58 +++++++++++++++++++++++
1 file changed, 58 insertions(+)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt
index e29156d4e7..7cef6bf060 100644
--- a/railties/doc/guides/source/caching_with_rails.txt
+++ b/railties/doc/guides/source/caching_with_rails.txt
@@ -358,6 +358,64 @@ ActionController::Base.cache_store = MyOwnStore.new("parameter")
ActionController::Base.cache_store in your Rails::Initializer.run block in
environment.rb+
+== Conditional GET support
+
+Conditional GETs are a facility of the HTTP spec that provide a way for web
+servers to tell browsers that the response to a GET request hasn’t changed
+since the last request and can be safely pulled from the browser cache.
+
+They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to
+pass back and forth both a unique content identifier and the timestamp of when
+the content was last changed. If the browser makes a request where the content
+identifier (etag) or last modified since timestamp matches the server’s version
+then the server only needs to send back an empty response with a not modified
+status.
+
+It is the server’s (i.e. our) responsibility to look for a last modified
+timestamp and the if-none-match header and determine whether or not to send
+back the full response. With conditional-get support in rails this is a pretty
+easy task:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ApplicationController
+
+ def show
+ @product = Product.find(params[:id])
+
+ # If the request is stale according to the given timestamp and etag value
+ # (i.e. it needs to be processed again) then execute this block
+ if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
+ respond_to do |wants|
+ # ... normal response processing
+ end
+ end
+
+ # If the request is fresh (i.e. it's not modified) then you don't need to do
+ # anything. The default render checks for this using the parameters
+ # used in the previous call to stale? and will automatically send a
+ # :not_modified. So that's it, you're done.
+end
+-----------------------------------------------------
+
+If you don’t have any special response processing and are using the default
+rendering mechanism (i.e. you’re not using respond_to or calling render
+yourself) then you’ve got an easy helper in fresh_when:
+
+[source, ruby]
+-----------------------------------------------------
+class ProductsController < ApplicationController
+
+ # This will automatically send back a :not_modified if the request is fresh,
+ # and will render the default template (product.*) if it's stale.
+
+ def show
+ @product = Product.find(params[:id])
+ fresh_when :last_modified => @product.published_at.utc, :etag => @article
+ end
+end
+-----------------------------------------------------
+
== Advanced Caching
Along with the built-in mechanisms outlined above, a number of excellent
--
cgit v1.2.3
From d67adf1e33b5ef93c7d414f87bdd68787297dd2f Mon Sep 17 00:00:00 2001
From: Aditya
Date: Sun, 23 Nov 2008 15:17:03 -0500
Subject: Update with globally keyed fragments
---
railties/doc/guides/source/caching_with_rails.txt | 20 +++++++++++++++++++-
1 file changed, 19 insertions(+), 1 deletion(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt
index 7cef6bf060..16dac19e08 100644
--- a/railties/doc/guides/source/caching_with_rails.txt
+++ b/railties/doc/guides/source/caching_with_rails.txt
@@ -176,7 +176,25 @@ and you can expire it using the `expire_fragment` method, like so:
[source, ruby]
-----------------------------------------------------
-expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products)
+expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products)
+-----------------------------------------------------
+
+If you don't want the cache block to bind to the action that called it, You can
+also use globally keyed fragments by calling the cache method with a key, like
+so:
+
+[source, ruby]
+-----------------------------------------------------
+<% cache(:key => ['all_available_products', @latest_product.created_at].join(':')) do %>
+ All available products:
+-----------------------------------------------------
+
+This fragment is then available to all actions in the ProductsController using
+the key and can be expired the same way:
+
+[source, ruby]
+-----------------------------------------------------
+expire_fragment(:key => ['all_available_products', @latest_product.created_at].join(':'))
-----------------------------------------------------
[More: more examples? description of fragment keys and expiration, etc? pagination?]
--
cgit v1.2.3
From c98bcfa55c8e61a0a956ebd2cc15b9e5216aa685 Mon Sep 17 00:00:00 2001
From: Yaroslav Markin
Date: Mon, 24 Nov 2008 12:28:29 +0300
Subject: I18n guide: changed to reflect new i18n locale naming, added a link
to rails-i18n.org
---
railties/doc/guides/source/i18n.txt | 25 +++++++++++++------------
1 file changed, 13 insertions(+), 12 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt
index c9867ba0ac..76f081e0bc 100644
--- a/railties/doc/guides/source/i18n.txt
+++ b/railties/doc/guides/source/i18n.txt
@@ -58,14 +58,14 @@ You can pick whatever directory and translation file naming scheme makes sense f
I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
# you can omit this if you're happy with English as a default locale
-I18n.default_locale = :"pt-BR"
+I18n.default_locale = :"pt"
-------------------------------------------------------
I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.
=== Set the locale in each request
-By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English).
+By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English).
If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:
@@ -137,7 +137,7 @@ So let's add the missing translations (i.e. do the "localization" part):
[source, ruby]
-------------------------------------------------------
-# lib/locale/en-US.yml
+# lib/locale/en.yml
en-US:
hello_world: Hello World
hello_flash: Hello Flash
@@ -252,7 +252,7 @@ All options besides :default and :scope that are passed to #translate will be in
[source, ruby]
-------------------------------------------------------
-I18n.backend.store_translations 'en-US', :thanks => 'Thanks {{name}}!'
+I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!'
I18n.translate :thanks, :name => 'Jeremy'
# => 'Thanks Jeremy!'
-------------------------------------------------------
@@ -294,7 +294,7 @@ If no locale is passed I18n.locale is used:
[source, ruby]
-------------------------------------------------------
-I18n.locale = :'de-DE'
+I18n.locale = :'de'
I18n.t :foo
I18n.l Time.now
-------------------------------------------------------
@@ -303,15 +303,15 @@ Explicitely passing a locale:
[source, ruby]
-------------------------------------------------------
-I18n.t :foo, :locale => :'de-DE'
-I18n.l Time.now, :locale => :'de-DE'
+I18n.t :foo, :locale => :'de'
+I18n.l Time.now, :locale => :'de'
-------------------------------------------------------
-I18n.locale defaults to I18n.default_locale which defaults to :'en-US'. The default locale can be set like this:
+I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this:
[source, ruby]
-------------------------------------------------------
-I18n.default_locale = :'de-DE'
+I18n.default_locale = :'de'
-------------------------------------------------------
== How to store your custom translations
@@ -346,7 +346,7 @@ Here is a "real" example from the ActiveSupport en-US translations YAML file:
[source, ruby]
-------------------------------------------------------
-"en-US":
+"en":
date:
formats:
default: "%Y-%m-%d"
@@ -370,7 +370,7 @@ You can use the methods Model.human_name and Model.human_attribute_name(attribut
For example when you add the following translations:
-en-US:
+en:
activerecord:
models:
user: Dude
@@ -479,7 +479,7 @@ Rails ships with the following translations:
[source, ruby]
-------------------------------------------------------
-"en-US":
+"en":
activerecord:
errors:
template:
@@ -526,6 +526,7 @@ TODO
== Resources
+* http://rails-i18n.org
== Footnotes
--
cgit v1.2.3
From 55d70f3a9848f5c3cafe99f9d3553418e4b6045f Mon Sep 17 00:00:00 2001
From: CassioMarques
Date: Tue, 25 Nov 2008 20:36:29 -0200
Subject: Added some text about callbacks classes
---
.../html/activerecord_validations_callbacks.html | 50 +++++++++++++++++++++-
.../source/activerecord_validations_callbacks.txt | 43 ++++++++++++++++++-
2 files changed, 90 insertions(+), 3 deletions(-)
(limited to 'railties/doc/guides')
diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
index 1656cea492..097ad76d1e 100644
--- a/railties/doc/guides/html/activerecord_validations_callbacks.html
+++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
@@ -301,7 +301,7 @@ ul#navMain {
Halting Execution
Changelog
@@ -1086,8 +1086,54 @@ Readability, since your callback declarations will live at the beggining of your
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean false (not nil) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
-
11. Callback classes and objects
+
11. Callback classes
+
Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
+
Here's an example where we create a class with a after_destroy callback for a PictureFile model.
+
+
+
class PictureFileCallbacks
+ def after_destroy(picture_file)
+ File.delete(picture_file.filepath)if File.exists?(picture_file.filepath)
+ end
+end
+
+
When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:
+
+
+
class PictureFile < ActiveRecord::Base
+ after_destroy PictureFileCallbacks.new
+end
+
+
Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
+
+
+
class PictureFileCallbacks
+ defself.after_destroy(picture_file)
+ File.delete(picture_file.filepath)if File.exists?(picture_file.filepath)
+ end
+end
+
+
If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.
+
+
+
class PictureFile < ActiveRecord::Base
+ after_destroy PictureFileCallbacks
+end
+
+
You can declare as many callbacks as you want inside your callback classes.
12. Changelog
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index 02cdbcf146..3db98027d2 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -589,10 +589,51 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o
As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.
+== Callback classes
-== Callback classes and objects
+Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.
+Here's an example where we create a class with a after_destroy callback for a PictureFile model.
+[source, ruby]
+------------------------------------------------------------------
+class PictureFileCallbacks
+ def after_destroy(picture_file)
+ File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
+ end
+end
+------------------------------------------------------------------
+
+When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:
+
+[source, ruby]
+------------------------------------------------------------------
+class PictureFile < ActiveRecord::Base
+ after_destroy PictureFileCallbacks.new
+end
+------------------------------------------------------------------
+
+Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.
+
+[source, ruby]
+------------------------------------------------------------------
+class PictureFileCallbacks
+ def self.after_destroy(picture_file)
+ File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
+ end
+end
+------------------------------------------------------------------
+
+If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.
+
+[source, ruby]
+------------------------------------------------------------------
+class PictureFile < ActiveRecord::Base
+ after_destroy PictureFileCallbacks
+end
+------------------------------------------------------------------
+
+You can declare as many callbacks as you want inside your callback classes.
== Changelog
--
cgit v1.2.3