aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/source
diff options
context:
space:
mode:
authorRyan Bigg <radarlistener@gmail.com>2008-11-18 10:40:50 +1030
committerRyan Bigg <radarlistener@gmail.com>2008-11-18 10:40:50 +1030
commit9dbb52d97e4ecc97fe793e3ac04a4fd285aa003b (patch)
treea88985f50190dad0f26044b2db0cf7b1a92355e5 /railties/doc/guides/source
parent451969f57a6dfee8537fb10d179514e011559111 (diff)
parentc62f973c749beac8947ff5119af43fbde2547eb1 (diff)
downloadrails-9dbb52d97e4ecc97fe793e3ac04a4fd285aa003b.tar.gz
rails-9dbb52d97e4ecc97fe793e3ac04a4fd285aa003b.tar.bz2
rails-9dbb52d97e4ecc97fe793e3ac04a4fd285aa003b.zip
Merge branch 'master' of git@github.com:lifo/docrails
Diffstat (limited to 'railties/doc/guides/source')
-rw-r--r--railties/doc/guides/source/2_2_release_notes.txt25
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/cookies.txt2
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/filters.txt4
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt4
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt6
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/streaming.txt2
-rw-r--r--railties/doc/guides/source/actioncontroller_basics/verification.txt2
-rw-r--r--railties/doc/guides/source/activerecord_validations_callbacks.txt107
-rw-r--r--railties/doc/guides/source/association_basics.txt10
-rw-r--r--railties/doc/guides/source/authors.txt6
-rw-r--r--railties/doc/guides/source/command_line.txt147
-rw-r--r--railties/doc/guides/source/configuring.txt141
-rw-r--r--railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt140
-rw-r--r--railties/doc/guides/source/creating_plugins/appendix.txt118
-rw-r--r--railties/doc/guides/source/creating_plugins/basics.markdown861
-rw-r--r--railties/doc/guides/source/creating_plugins/controllers.txt63
-rw-r--r--railties/doc/guides/source/creating_plugins/core_ext.txt98
-rw-r--r--railties/doc/guides/source/creating_plugins/custom_generator.txt69
-rw-r--r--railties/doc/guides/source/creating_plugins/gems.txt50
-rw-r--r--railties/doc/guides/source/creating_plugins/generator_commands.txt144
-rw-r--r--railties/doc/guides/source/creating_plugins/generators.txt98
-rw-r--r--railties/doc/guides/source/creating_plugins/helpers.txt49
-rw-r--r--railties/doc/guides/source/creating_plugins/index.txt120
-rw-r--r--railties/doc/guides/source/creating_plugins/migration_generator.txt89
-rw-r--r--railties/doc/guides/source/creating_plugins/migrations.txt213
-rw-r--r--railties/doc/guides/source/creating_plugins/models.txt74
-rw-r--r--railties/doc/guides/source/creating_plugins/odds_and_ends.txt122
-rw-r--r--railties/doc/guides/source/creating_plugins/preparation.txt169
-rw-r--r--railties/doc/guides/source/creating_plugins/rdoc.txt18
-rw-r--r--railties/doc/guides/source/creating_plugins/routes.txt (renamed from railties/doc/guides/source/creating_plugins/custom_route.txt)34
-rw-r--r--railties/doc/guides/source/creating_plugins/setup.txt84
-rw-r--r--railties/doc/guides/source/creating_plugins/string_to_squawk.txt103
-rw-r--r--railties/doc/guides/source/creating_plugins/tasks.txt27
-rw-r--r--railties/doc/guides/source/creating_plugins/tests.txt165
-rw-r--r--railties/doc/guides/source/creating_plugins/view_helper.txt61
-rw-r--r--railties/doc/guides/source/getting_started_with_rails.txt2
-rw-r--r--railties/doc/guides/source/i18n.txt541
-rw-r--r--railties/doc/guides/source/index.txt10
-rw-r--r--railties/doc/guides/source/migrations/index.txt2
-rw-r--r--railties/doc/guides/source/migrations/rakeing_around.txt2
-rw-r--r--railties/doc/guides/source/routing_outside_in.txt26
-rw-r--r--railties/doc/guides/source/stylesheets/base.css4
-rw-r--r--railties/doc/guides/source/testing_rails_applications.txt390
43 files changed, 2537 insertions, 1865 deletions
diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt
index c730f72748..59701ca24c 100644
--- a/railties/doc/guides/source/2_2_release_notes.txt
+++ b/railties/doc/guides/source/2_2_release_notes.txt
@@ -209,7 +209,7 @@ Active Record association proxies now respect the scope of methods on the proxie
== Action Controller
-On the controller side, there are a couple of changes that will help tidy up your routes.
+On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.
=== Shallow Route Nesting
@@ -250,16 +250,28 @@ map.resources :photos, :collection => { :search => [:get, :post] }
* Lead Contributor: link:http://brennandunn.com/[Brennan Dunn]
-Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions.
+=== Resources With Specific Actions
+
+By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources.
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+map.resources :products, :except => :destroy
+-------------------------------------------------------
+
+* Lead Contributor: link:http://experthuman.com/[Tom Stuart]
=== Other Action Controller Changes
* You can now easily link:http://m.onkey.org/2008/7/20/rescue-from-dispatching[show a custom error page] for exceptions raised while routing a request.
-* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.user_accept_header = true+.
+* The HTTP Accept header is disabled by default now. You should prefer the use of formatted URLs (such as +/customers/1.xml+) to indicate the format that you want. If you need the Accept headers, you can turn them back on with +config.action_controller.use_accept_header = true+.
* Benchmarking numbers are now reported in milliseconds rather than tiny fractions of seconds
* Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers.
* +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI).
* +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type.
+* Request forgery protection has been tightened up to apply to HTML-formatted content requests only.
+* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+.
== Action View
@@ -275,6 +287,8 @@ Action Mailer now supports mailer layouts. You can make your HTML emails as pret
* More information:
- link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts[What's New in Edge Rails: Mailer Layouts]
+Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.
+
== Active Support
Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods.
@@ -367,7 +381,7 @@ In Railties (the core code of Rails itself) the biggest changes are in the +conf
To avoid deployment issues and make Rails applications more self-contained, it's possible to place copies of all of the gems that your Rails application requires in +/vendor/gems+. This capability first appeared in Rails 2.1, but it's much more flexible and robust in Rails 2.2, handling complicated dependencies between gems. Gem management in Rails includes these commands:
* +config.gem _gem_name_+ in your +config/environment.rb+ file
-* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed or frozen
+* +rake gems+ to list all configured gems, as well as whether they (and their dependencies) are installed, frozen, or framework (framework gems are those loaded by Rails before the gem dependency code is executed; such gems cannot be frozen)
* +rake gems:install+ to install missing gems to the computer
* +rake gems:unpack+ to place a copy of the required gems into +/vendor/gems+
* +rake gems:unpack:dependencies+ to get copies of the required gems and their dependencies into +/vendor/gems+
@@ -380,6 +394,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the com
* More information:
- link:http://ryandaigle.com/articles/2008/4/1/what-s-new-in-edge-rails-gem-dependencies[What's New in Edge Rails: Gem Dependencies]
- link:http://afreshcup.com/2008/10/25/rails-212-and-22rc1-update-your-rubygems/[Rails 2.1.2 and 2.2RC1: Update Your RubyGems]
+ - link:http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/tickets/1128[Detailed discussion on Lighthouse]
=== Other Railties Changes
@@ -389,7 +404,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the com
* Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source
* +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations.
* Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+
-* +script/generate+ works without deprecation warnings when RubyGems 1.3.0 is present
+* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.
== Deprecated
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]
---------------------------------------
diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt
index 29be2182ce..87f3392551 100644
--- a/railties/doc/guides/source/activerecord_validations_callbacks.txt
+++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt
@@ -369,6 +369,113 @@ class Account < ActiveRecord::Base
end
------------------------------------------------------------------
+== Writing your own validation methods
+
+When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ def validate_on_create
+ errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
+ end
+end
+------------------------------------------------------------------
+
+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.
+
+[source, ruby]
+------------------------------------------------------------------
+class Invoice < ActiveRecord::Base
+ 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
+ end
+
+ def discount_cannot_be_greater_than_total_value
+ errors.add(:discount, "can't be greater than total value") unless discount <= total_value
+ end
+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
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".
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/command_line.txt b/railties/doc/guides/source/command_line.txt
new file mode 100644
index 0000000000..5f7c6ceff5
--- /dev/null
+++ b/railties/doc/guides/source/command_line.txt
@@ -0,0 +1,147 @@
+A Guide to The Rails Command Line
+=================================
+
+Rails comes with every command line tool you'll need to
+
+* Create a Rails application
+* Generate models, controllers, database migrations, and unit tests
+* Start a development server
+* Mess with objects through an interactive shell
+* Profile and benchmark your new creation
+
+... and much, much more! (Buy now!)
+
+This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide.
+
+== Command Line Basics ==
+
+There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
+
+* console
+* server
+* rake
+* generate
+* rails
+
+Let's create a simple Rails application to step through each of these commands in context.
+
+=== rails ===
+
+The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails.
+
+NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure.
+
+[source,shell]
+------------------------------------------------------
+$ rails commandsapp
+
+ create
+ create app/controllers
+ create app/helpers
+ create app/models
+ ...
+ ...
+ create log/production.log
+ create log/development.log
+ create log/test.log
+------------------------------------------------------
+
+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.
+
+NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing!
+
+=== 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.
+
+NOTE: 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:
+
+[source,shell]
+------------------------------------------------------
+$ 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-04 10:11:38] INFO WEBrick 1.3.1
+[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
+[2008-11-04 10: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.
+
+=== 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:
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate
+Usage: ./script/generate generator [options] [args]
+
+...
+...
+
+Installed Generators
+ Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
+
+...
+...
+------------------------------------------------------
+
+NOTE: 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:
+
+NOTE: 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`.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller
+Usage: ./script/generate controller ControllerName [options]
+
+...
+...
+
+Example:
+ `./script/generate controller CreditCard open debit credit close`
+
+ Credit card controller with URLs like /credit_card/debit.
+ Controller: app/controllers/credit_card_controller.rb
+ Views: app/views/credit_card/debit.html.erb [...]
+ Helper: app/helpers/credit_card_helper.rb
+ Test: test/functional/credit_card_controller_test.rb
+
+Modules Example:
+ `./script/generate controller 'admin/credit_card' suspend late_fee`
+
+ Credit card admin controller with URLs /admin/credit_card/suspend.
+ Controller: app/controllers/admin/credit_card_controller.rb
+ Views: app/views/admin/credit_card/debit.html.erb [...]
+ Helper: app/helpers/admin/credit_card_helper.rb
+ Test: test/functional/admin/credit_card_controller_test.rb
+------------------------------------------------------
+
+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.
+
+[source,shell]
+------------------------------------------------------
+$ ./script/generate controller Greeting hello
+ exists app/controllers/
+ exists app/helpers/
+ create app/views/greeting
+ exists test/functional/
+ create app/controllers/greetings_controller.rb
+ create test/functional/greetings_controller_test.rb
+ create app/helpers/greetings_helper.rb
+ create app/views/greetings/hello.html.erb
+------------------------------------------------------
+
+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!
+
diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt
index 07b630c59d..1fb73abbb8 100644
--- a/railties/doc/guides/source/configuring.txt
+++ b/railties/doc/guides/source/configuring.txt
@@ -16,16 +16,111 @@ after-initializer
== Using a Preinitializer
+== Initialization Process Settings
+
== Configuring Rails Components
=== Configuring Active Record
++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+.
+
=== 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'
+
=== 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| "<div class=\"fieldWithErrors\">#{html_tag}</div>" }+
+
++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
@@ -35,6 +130,10 @@ after-initializer
== Using an After-Initializer
+== Rails Environment Settings
+
+ENV
+
== Changelog ==
http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket]
@@ -135,47 +234,6 @@ activerecord/lib/active_record/attribute_methods.rb
9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false
11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false
-activerecord/lib/active_record/base.rb
-394: cattr_accessor :logger, :instance_writer => false
-443: cattr_accessor :configurations, :instance_writer => false
-450: cattr_accessor :primary_key_prefix_type, :instance_writer => false
-456: cattr_accessor :table_name_prefix, :instance_writer => false
-461: cattr_accessor :table_name_suffix, :instance_writer => false
-467: cattr_accessor :pluralize_table_names, :instance_writer => false
-473: cattr_accessor :colorize_logging, :instance_writer => false
-478: cattr_accessor :default_timezone, :instance_writer => false
-487: cattr_accessor :schema_format , :instance_writer => false
-491: cattr_accessor :timestamped_migrations , :instance_writer => false
-
-activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
-11: cattr_accessor :connection_handler, :instance_writer => false
-
-activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
-166: cattr_accessor :emulate_booleans
-
-activerecord/lib/active_record/fixtures.rb
-498: cattr_accessor :all_loaded_fixtures
-
-activerecord/lib/active_record/locking/optimistic.rb
-38: base.cattr_accessor :lock_optimistically, :instance_writer => false
-
-activerecord/lib/active_record/migration.rb
-259: cattr_accessor :verbose
-
-activerecord/lib/active_record/schema_dumper.rb
-13: cattr_accessor :ignore_tables
-
-activerecord/lib/active_record/serializers/json_serializer.rb
-4: base.cattr_accessor :include_root_in_json, :instance_writer => false
-
-activerecord/Rakefile
-142: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object'
-
-activerecord/test/cases/lifecycle_test.rb
-61: cattr_reader :last_inherited
-
-activerecord/test/cases/mixin_test.rb
-9: cattr_accessor :forced_now_time
activeresource/lib/active_resource/base.rb
206: cattr_accessor :logger
@@ -223,3 +281,4 @@ railties/test/rails_info_controller_test.rb
Rakefile
32: rdoc.options << '-A cattr_accessor=object'
+need to look for def self. ???
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..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,32 +1,40 @@
-== Add an `acts_as_yaffle` method to ActiveRecord ==
+== 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.
+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*
[source, ruby]
------------------------------------------------------
-# 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
------------------------------------------------------
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
[source, ruby]
------------------------------------------------------
-# File: vendor/plugins/lib/acts_as_yaffle.rb
+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/yaffle/lib/yaffle/acts_as_yaffle.rb*
[source, ruby]
------------------------------------------------------
@@ -50,52 +58,45 @@ 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
-------------------------------------------------------
+To start out, write a failing test that shows the behavior you'd like:
-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 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
+ load_schema
+
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/yaffle/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
@@ -103,70 +104,66 @@ 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*
[source, ruby]
------------------------------------------------------
-# 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 Wickwall < ActiveRecord::Base
+ acts_as_yaffle :yaffle_text_field => :last_tweet
+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
- 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
------------------------------------------------------
+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]
------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
-
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
@@ -174,9 +171,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
@@ -184,10 +180,12 @@ 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
------------------------------------------------------
-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/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt
index a78890ccd5..340c03dd4e 100644
--- a/railties/doc/guides/source/creating_plugins/appendix.txt
+++ b/railties/doc/guides/source/creating_plugins/appendix.txt
@@ -1,46 +1,104 @@
== Appendix ==
+If you prefer to use RSpec instead of Test::Unit, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator].
+
=== References ===
* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
* http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii
* http://github.com/technoweenie/attachment_fu/tree/master
* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
+ * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins
+ * http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+
+=== Contents of 'lib/yaffle.rb' ===
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+require "yaffle/core_ext"
+require "yaffle/acts_as_yaffle"
+require "yaffle/commands"
+require "yaffle/routing"
+
+%w{ models controllers helpers }.each do |dir|
+ path = File.join(File.dirname(__FILE__), 'app', dir)
+ $LOAD_PATH << path
+ ActiveSupport::Dependencies.load_paths << path
+ ActiveSupport::Dependencies.load_once_paths.delete(path)
+end
+
+# optionally:
+# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
+# require file
+# end
+
+----------------------------------------------
+
=== Final plugin directory structure ===
The final plugin should have a directory structure that looks something like this:
------------------------------------------------
- |-- MIT-LICENSE
- |-- README
- |-- Rakefile
- |-- generators
- | `-- yaffle
- | |-- USAGE
- | |-- templates
- | | `-- definition.txt
- | `-- yaffle_generator.rb
- |-- init.rb
- |-- install.rb
- |-- lib
- | |-- acts_as_yaffle.rb
- | |-- commands.rb
- | |-- core_ext.rb
- | |-- routing.rb
- | `-- view_helpers.rb
- |-- tasks
- | `-- yaffle_tasks.rake
- |-- test
- | |-- acts_as_yaffle_test.rb
- | |-- core_ext_test.rb
- | |-- database.yml
- | |-- debug.log
- | |-- routing_test.rb
- | |-- schema.rb
- | |-- test_helper.rb
- | `-- view_helpers_test.rb
- |-- uninstall.rb
- `-- yaffle_plugin.sqlite3.db
+|-- MIT-LICENSE
+|-- README
+|-- Rakefile
+|-- generators
+| |-- yaffle_definition
+| | |-- USAGE
+| | |-- templates
+| | | `-- definition.txt
+| | `-- yaffle_definition_generator.rb
+| |-- yaffle_migration
+| | |-- USAGE
+| | |-- templates
+| | `-- yaffle_migration_generator.rb
+| `-- yaffle_route
+| |-- USAGE
+| |-- templates
+| `-- yaffle_route_generator.rb
+|-- install.rb
+|-- lib
+| |-- app
+| | |-- controllers
+| | | `-- woodpeckers_controller.rb
+| | |-- helpers
+| | | `-- woodpeckers_helper.rb
+| | `-- models
+| | `-- woodpecker.rb
+| |-- db
+| | `-- migrate
+| | `-- 20081116181115_create_birdhouses.rb
+| |-- yaffle
+| | |-- acts_as_yaffle.rb
+| | |-- commands.rb
+| | |-- core_ext.rb
+| | `-- routing.rb
+| `-- yaffle.rb
+|-- pkg
+| `-- yaffle-0.0.1.gem
+|-- rails
+| `-- init.rb
+|-- tasks
+| `-- yaffle_tasks.rake
+|-- test
+| |-- acts_as_yaffle_test.rb
+| |-- core_ext_test.rb
+| |-- database.yml
+| |-- debug.log
+| |-- definition_generator_test.rb
+| |-- migration_generator_test.rb
+| |-- route_generator_test.rb
+| |-- routes_test.rb
+| |-- schema.rb
+| |-- test_helper.rb
+| |-- woodpecker_test.rb
+| |-- woodpeckers_controller_test.rb
+| |-- wookpeckers_helper_test.rb
+| |-- yaffle_plugin.sqlite3.db
+| `-- yaffle_test.rb
+`-- uninstall.rb
------------------------------------------------
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/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt
new file mode 100644
index 0000000000..7afdef032d
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/controllers.txt
@@ -0,0 +1,63 @@
+== Controllers ==
+
+This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.
+
+You can test your plugin's controller as you would test any other controller:
+
+*vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:*
+
+[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
+
+ ActionController::Routing::Routes.draw do |map|
+ map.resources :woodpeckers
+ end
+ 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/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt
new file mode 100644
index 0000000000..cbedb9eaf2
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/core_ext.txt
@@ -0,0 +1,98 @@
+== Extending core classes ==
+
+This section will explain how to add a method to String that will be available anywhere in your rails app.
+
+In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions:
+
+*vendor/plugins/yaffle/test/core_ext_test.rb*
+
+[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.
+
+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"
+--------------------------------------------------------
+
+=== Working with init.rb ===
+
+When rails loads plugins it looks for the file named 'init.rb' or 'rails/init.rb'. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
+
+Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above.
+
+If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues:
+
+*vendor/plugins/yaffle/rails/init.rb*
+
+[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/rails/init.rb*
+
+[source, ruby]
+---------------------------------------------------
+class ::Hash
+ def is_a_special_hash?
+ true
+ end
+end
+---------------------------------------------------
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 6d9613ea01..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:
-
-[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
------------------------------------------------------------
-
-[source, ruby]
------------------------------------------------------------
-# 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
------------------------------------------------------------
-
-[source, ruby]
------------------------------------------------------------
-# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
-
-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/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/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt
new file mode 100644
index 0000000000..f60ea3d8f1
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt
@@ -0,0 +1,144 @@
+== Generator Commands ==
+
+You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.
+
+This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'.
+
+To start, add the following test method:
+
+*vendor/plugins/yaffle/test/route_generator_test.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+require 'rails_generator/scripts/destroy'
+
+class RouteGeneratorTest < Test::Unit::TestCase
+
+ def setup
+ FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
+ end
+
+ def teardown
+ FileUtils.rm_r(fake_rails_root)
+ end
+
+ def test_generates_route
+ content = <<-END
+ ActionController::Routing::Routes.draw do |map|
+ map.connect ':controller/:action/:id'
+ map.connect ':controller/:action/:id.:format'
+ end
+ END
+ File.open(routes_path, 'wb') {|f| f.write(content) }
+
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
+ assert_match /map\.yaffles/, File.read(routes_path)
+ end
+
+ def test_destroys_route
+ content = <<-END
+ ActionController::Routing::Routes.draw do |map|
+ map.yaffles
+ map.connect ':controller/:action/:id'
+ map.connect ':controller/:action/:id.:format'
+ end
+ END
+ File.open(routes_path, 'wb') {|f| f.write(content) }
+
+ Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
+ assert_no_match /map\.yaffles/, File.read(routes_path)
+ end
+
+ private
+
+ def fake_rails_root
+ File.join(File.dirname(__FILE__), "rails_root")
+ end
+
+ def routes_path
+ File.join(fake_rails_root, "config", "routes.rb")
+ end
+
+end
+-----------------------------------------------------------
+
+Run `rake` to watch the test fail, then make the test pass add the following:
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+require "yaffle/commands"
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/lib/yaffle/commands.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+require 'rails_generator'
+require 'rails_generator/commands'
+
+module Yaffle #:nodoc:
+ module Generator #:nodoc:
+ module Commands #:nodoc:
+ module Create
+ def yaffle_route
+ logger.route "map.yaffle"
+ look_for = 'ActionController::Routing::Routes.draw do |map|'
+ unless options[:pretend]
+ gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"}
+ end
+ end
+ end
+
+ module Destroy
+ def yaffle_route
+ logger.route "map.yaffle"
+ gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, ''
+ end
+ end
+
+ module List
+ def yaffle_route
+ end
+ end
+
+ module Update
+ def yaffle_route
+ end
+ end
+ end
+ end
+end
+
+Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
+Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
+Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
+Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
+-----------------------------------------------------------
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb*
+
+[source, ruby]
+-----------------------------------------------------------
+class YaffleRouteGenerator < Rails::Generator::Base
+ def manifest
+ record do |m|
+ m.yaffle_route
+ end
+ end
+end
+-----------------------------------------------------------
+
+To see this work, type:
+
+-----------------------------------------------------------
+./script/generate yaffle_route
+./script/destroy yaffle_route
+-----------------------------------------------------------
+
+.Editor's note:
+NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. \ No newline at end of file
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..f856bec7a2
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/generators.txt
@@ -0,0 +1,98 @@
+== Generators ==
+
+Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'.
+
+Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.
+
+=== Testing generators ===
+
+Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following:
+
+ * Creates a new fake rails root directory that will serve as destination
+ * Runs the generator
+ * Asserts that the correct files were generated
+ * Removes the fake rails root
+
+This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:
+
+*vendor/plugins/yaffle/test/definition_generator_test.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+
+class DefinitionGeneratorTest < Test::Unit::TestCase
+
+ def setup
+ FileUtils.mkdir_p(fake_rails_root)
+ @original_files = file_list
+ end
+
+ def teardown
+ FileUtils.rm_r(fake_rails_root)
+ end
+
+ def test_generates_correct_file_name
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
+ new_file = (file_list - @original_files).first
+ assert_equal "definition.txt", File.basename(new_file)
+ end
+
+ private
+
+ def fake_rails_root
+ File.join(File.dirname(__FILE__), 'rails_root')
+ end
+
+ def file_list
+ Dir.glob(File.join(fake_rails_root, "*"))
+ end
+
+end
+------------------------------------------------------------------
+
+You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.
+
+To make it pass, create the generator:
+
+*vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+class YaffleDefinitionGenerator < Rails::Generator::Base
+ def manifest
+ record do |m|
+ m.file "definition.txt", "definition.txt"
+ end
+ end
+end
+------------------------------------------------------------------
+
+=== The USAGE file ===
+
+If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.
+
+Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:
+
+------------------------------------------------------------------
+./script/generate
+------------------------------------------------------------------
+
+You should see something like this:
+
+------------------------------------------------------------------
+Installed Generators
+ Plugins (vendor/plugins): yaffle_definition
+ Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
+------------------------------------------------------------------
+
+When you run `script/generate yaffle_definition -h` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'.
+
+For this plugin, update the USAGE file could look like this:
+
+------------------------------------------------------------------
+Description:
+ Adds a file with the definition of a Yaffle to the app's main directory
+------------------------------------------------------------------
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..fa4227be41
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/helpers.txt
@@ -0,0 +1,49 @@
+== Helpers ==
+
+This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.
+
+You can test your plugin's helper as you would test any other helper:
+
+*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb*
+
+[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
+----------------------------------------------
+
+
+*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 f2ed6ed8bb..0607bc7487 100644
--- a/railties/doc/guides/source/creating_plugins/index.txt
+++ b/railties/doc/guides/source/creating_plugins/index.txt
@@ -1,84 +1,60 @@
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.
-
-
-include::preparation.txt[]
-
-include::string_to_squawk.txt[]
+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::setup.txt[]
+
+include::tests.txt[]
+
+include::core_ext.txt[]
include::acts_as_yaffle.txt[]
-include::view_helper.txt[]
+include::models.txt[]
+
+include::controllers.txt[]
+
+include::helpers.txt[]
+
+include::routes.txt[]
+
+include::generators.txt[]
+
+include::generator_commands.txt[]
-include::migration_generator.txt[]
+include::migrations.txt[]
-include::custom_generator.txt[]
+include::tasks.txt[]
-include::custom_route.txt[]
+include::gems.txt[]
-include::odds_and_ends.txt[]
+include::rdoc.txt[]
include::appendix.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 598a0c8437..0000000000
--- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
+++ /dev/null
@@ -1,89 +0,0 @@
-== 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:
-
-[source, ruby]
-------------------------------------------------------------------
-# 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:
-
-[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
- add_column :birds, :last_squawked_at, :datetime
- end
-
- def self.down
- remove_column :birds, :last_squawked_at
- remove_column :birds, :last_squawk
- end
-end
-------------------------------------------------------------------
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..e7d2e09069
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/migrations.txt
@@ -0,0 +1,213 @@
+== 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 migrations directly ===
+
+*vendor/plugins/yaffle/lib/yaffle.rb:*
+
+[source, ruby]
+----------------------------------------------
+Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file|
+ require file
+end
+----------------------------------------------
+
+*db/migrate/20081116181115_create_birdhouses.rb:*
+
+[source, ruby]
+----------------------------------------------
+class CreateBirdhouses < ActiveRecord::Migration
+ def self.up
+ Yaffle::CreateBirdhouses.up
+ end
+
+ def self.down
+ Yaffle::CreateBirdhouses.down
+ end
+end
+----------------------------------------------
+
+.Editor's note:
+NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
+
+=== Generate migrations ===
+
+Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:
+
+ * call your script/generate script and pass in whatever options they need
+ * examine the generated migration, adding/removing columns or other options as necessary
+
+This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:
+
+*vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+require 'rails_generator'
+require 'rails_generator/scripts/generate'
+
+class MigrationGeneratorTest < Test::Unit::TestCase
+
+ def setup
+ FileUtils.mkdir_p(fake_rails_root)
+ @original_files = file_list
+ end
+
+ def teardown
+ ActiveRecord::Base.pluralize_table_names = true
+ FileUtils.rm_r(fake_rails_root)
+ end
+
+ def test_generates_correct_file_name
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
+ new_file = (file_list - @original_files).first
+ assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
+ assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file)
+ end
+
+ def test_pluralizes_properly
+ ActiveRecord::Base.pluralize_table_names = false
+ Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
+ new_file = (file_list - @original_files).first
+ assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
+ assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file)
+ end
+
+ private
+ def fake_rails_root
+ File.join(File.dirname(__FILE__), 'rails_root')
+ end
+
+ def file_list
+ Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
+ end
+
+end
+------------------------------------------------------------------
+
+.Editor's note:
+NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.
+
+After running the test with 'rake' you can make it pass with:
+
+*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+class YaffleMigrationGenerator < Rails::Generator::NamedBase
+ def manifest
+ record do |m|
+ m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
+ :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
+ }
+ end
+ end
+
+ private
+ def custom_file_name
+ custom_name = class_name.underscore.downcase
+ custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
+ custom_name
+ end
+
+ def yaffle_local_assigns
+ returning(assigns = {}) do
+ assigns[:migration_action] = "add"
+ assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
+ assigns[:table_name] = custom_file_name
+ assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
+ end
+ end
+end
+------------------------------------------------------------------
+
+The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template.
+
+It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.
+
+To run the generator, type the following at the command line:
+
+------------------------------------------------------------------
+./script/generate yaffle_migration bird
+------------------------------------------------------------------
+
+and you will see a new file:
+
+*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
+
+[source, ruby]
+------------------------------------------------------------------
+class AddYaffleFieldsToBirds < ActiveRecord::Migration
+ def self.up
+ add_column :birds, :last_squawk, :string
+ end
+
+ def self.down
+ remove_column :birds, :last_squawk
+ end
+end
+------------------------------------------------------------------
+
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..8b66de0f99
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/models.txt
@@ -0,0 +1,74 @@
+== 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:
+
+---------------------------------------------------------
+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]
+----------------------------------------------
+create_table :woodpeckers, :force => true do |t|
+ t.string :name
+end
+----------------------------------------------
+
+Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. \ 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
deleted file mode 100644
index eb127f73ca..0000000000
--- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
+++ /dev/null
@@ -1,122 +0,0 @@
-== 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. 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`:
-
-[source, ruby]
----------------------------------------------------
-# 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
----------------------------------------------------
-
-=== 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
-
-
-=== 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.
-
-Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
-
-[source, ruby]
----------------------------------------------------------
-# 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 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/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt
deleted file mode 100644
index 77e3a3561f..0000000000
--- a/railties/doc/guides/source/creating_plugins/preparation.txt
+++ /dev/null
@@ -1,169 +0,0 @@
-== Preparation ==
-
-=== 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:
-
-------------------------------------------------
-rails plugin_demo
-cd plugin_demo
-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.
-
-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 ===
-
-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:
-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:
-
-*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
-----------------------------------------------
-
-*vendor/plugins/yaffle/test/test_helper.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
-
-# 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
-----------------------------------------------
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/custom_route.txt b/railties/doc/guides/source/creating_plugins/routes.txt
index 7e399247ee..dc1bf09fd1 100644
--- a/railties/doc/guides/source/creating_plugins/custom_route.txt
+++ b/railties/doc/guides/source/creating_plugins/routes.txt
@@ -1,11 +1,13 @@
-== Add a Custom Route ==
+== Routes ==
-Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
+In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'.
+
+Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this:
+
+*vendor/plugins/yaffle/test/routing_test.rb*
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/test/routing_test.rb
-
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
@@ -22,10 +24,6 @@ class RoutingTest < Test::Unit::TestCase
private
- # yes, I know about assert_recognizes, but it has proven problematic to
- # use in these tests, since it uses RouteSet#recognize (which actually
- # tries to instantiate the controller) and because it uses an awkward
- # parameter order.
def assert_recognition(method, path, options)
result = ActionController::Routing::Routes.recognize_path(path, :method => method)
assert_equal options, result
@@ -33,18 +31,19 @@ class RoutingTest < Test::Unit::TestCase
end
--------------------------------------------------------
+Once you see the tests fail by running 'rake', you can make them pass with:
+
+*vendor/plugins/yaffle/lib/yaffle.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-require "routing"
-ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
+require "yaffle/routing"
--------------------------------------------------------
+*vendor/plugins/yaffle/lib/yaffle/routing.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: vendor/plugins/yaffle/lib/routing.rb
-
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
@@ -54,14 +53,15 @@ module Yaffle #:nodoc:
end
end
end
+
+ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
+*config/routes.rb*
+
[source, ruby]
--------------------------------------------------------
-# File: config/routes.rb
-
ActionController::Routing::Routes.draw do |map|
- ...
map.yaffles
end
--------------------------------------------------------
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..cd4b6ecb04
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/setup.txt
@@ -0,0 +1,84 @@
+== Setup ==
+
+=== Create the basic app ===
+
+The examples in this guide require that you have a working rails application. To create a simple rails app execute:
+
+------------------------------------------------
+gem install rails
+rails yaffle_guide
+cd yaffle_guide
+script/generate scaffold bird name:string
+rake db:migrate
+script/server
+------------------------------------------------
+
+Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
+
+.Editor's note:
+NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
+
+
+=== Generate the plugin skeleton ===
+
+Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
+
+This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
+
+Examples:
+----------------------------------------------
+./script/generate plugin yaffle
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+To get more detailed help on the plugin generator, type `./script/generate plugin`.
+
+Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now:
+
+----------------------------------------------
+./script/generate plugin yaffle --with-generator
+----------------------------------------------
+
+You should see the following output:
+
+----------------------------------------------
+create vendor/plugins/yaffle/lib
+create vendor/plugins/yaffle/tasks
+create vendor/plugins/yaffle/test
+create vendor/plugins/yaffle/README
+create vendor/plugins/yaffle/MIT-LICENSE
+create vendor/plugins/yaffle/Rakefile
+create vendor/plugins/yaffle/init.rb
+create vendor/plugins/yaffle/install.rb
+create vendor/plugins/yaffle/uninstall.rb
+create vendor/plugins/yaffle/lib/yaffle.rb
+create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
+create vendor/plugins/yaffle/test/core_ext_test.rb
+create vendor/plugins/yaffle/generators
+create vendor/plugins/yaffle/generators/yaffle
+create vendor/plugins/yaffle/generators/yaffle/templates
+create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
+create vendor/plugins/yaffle/generators/yaffle/USAGE
+----------------------------------------------
+
+=== Organize your files ===
+
+To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this:
+
+--------------------------------------------------------
+|-- lib
+| |-- yaffle
+| `-- yaffle.rb
+`-- rails
+ |
+ `-- init.rb
+--------------------------------------------------------
+
+*vendor/plugins/yaffle/rails/init.rb*
+
+[source, ruby]
+--------------------------------------------------------
+require 'yaffle'
+--------------------------------------------------------
+
+Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean. \ No newline at end of file
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 50516cef69..0000000000
--- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
+++ /dev/null
@@ -1,103 +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:
-
-[source, ruby]
---------------------------------------------------------
-# 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.
-
-[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
-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:
-
-[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)
- 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
---------------------------------------------------------
-
-[source, ruby]
---------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-require "core_ext"
---------------------------------------------------------
-
-[source, ruby]
---------------------------------------------------------
-# 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.
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..d848c2cfa1
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/tasks.txt
@@ -0,0 +1,27 @@
+== Rake tasks ==
+
+When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.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
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..47611542cb
--- /dev/null
+++ b/railties/doc/guides/source/creating_plugins/tests.txt
@@ -0,0 +1,165 @@
+== Tests ==
+
+In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files:
+
+ * A 'database.yml' file with all of your connection strings
+ * A 'schema.rb' file with your table definitions
+ * A test helper method that sets up the database
+
+=== Test Setup ===
+
+*vendor/plugins/yaffle/test/database.yml:*
+
+----------------------------------------------
+sqlite:
+ :adapter: sqlite
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
+
+sqlite3:
+ :adapter: sqlite3
+ :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
+
+postgresql:
+ :adapter: postgresql
+ :username: postgres
+ :password: postgres
+ :database: yaffle_plugin_test
+ :min_messages: ERROR
+
+mysql:
+ :adapter: mysql
+ :host: localhost
+ :username: root
+ :password: password
+ :database: yaffle_plugin_test
+----------------------------------------------
+
+For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following:
+
+*vendor/plugins/yaffle/test/schema.rb:*
+
+[source, ruby]
+----------------------------------------------
+ActiveRecord::Schema.define(:version => 0) do
+ create_table :hickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_squawk
+ t.datetime :last_squawked_at
+ end
+ create_table :wickwalls, :force => true do |t|
+ t.string :name
+ t.string :last_tweet
+ t.datetime :last_tweeted_at
+ end
+ create_table :woodpeckers, :force => true do |t|
+ t.string :name
+ end
+end
+----------------------------------------------
+
+*vendor/plugins/yaffle/test/test_helper.rb:*
+
+[source, ruby]
+----------------------------------------------
+ENV['RAILS_ENV'] = 'test'
+ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
+
+require 'test/unit'
+require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
+
+def load_schema
+ config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
+ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
+
+ db_adapter = ENV['DB']
+
+ # no db passed, try one of these fine config-free DBs before bombing.
+ db_adapter ||=
+ begin
+ require 'rubygems'
+ require 'sqlite'
+ 'sqlite'
+ rescue MissingSourceFile
+ begin
+ require 'sqlite3'
+ 'sqlite3'
+ rescue MissingSourceFile
+ end
+ end
+
+ if db_adapter.nil?
+ raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
+ end
+
+ ActiveRecord::Base.establish_connection(config[db_adapter])
+ load(File.dirname(__FILE__) + "/schema.rb")
+ require File.dirname(__FILE__) + '/../rails/init.rb'
+end
+----------------------------------------------
+
+Now whenever you write a test that requires the database, you can call 'load_schema'.
+
+=== Run the plugin tests ===
+
+Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with:
+
+*vendor/plugins/yaffle/test/yaffle_test.rb:*
+
+[source, ruby]
+----------------------------------------------
+require File.dirname(__FILE__) + '/test_helper.rb'
+
+class YaffleTest < Test::Unit::TestCase
+ load_schema
+
+ class Hickwall < ActiveRecord::Base
+ end
+
+ class Wickwall < ActiveRecord::Base
+ end
+
+ def test_schema_has_loaded_correctly
+ assert_equal [], Hickwall.all
+ assert_equal [], Wickwall.all
+ end
+
+end
+----------------------------------------------
+
+To run this, go to the plugin directory and run `rake`:
+
+----------------------------------------------
+cd vendor/plugins/yaffle
+rake
+----------------------------------------------
+
+You should see output like:
+
+----------------------------------------------
+/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
+-- create_table(:hickwalls, {:force=>true})
+ -> 0.0220s
+-- create_table(:wickwalls, {:force=>true})
+ -> 0.0077s
+-- initialize_schema_migrations_table()
+ -> 0.0007s
+-- assume_migrated_upto_version(0)
+ -> 0.0007s
+Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
+Started
+.
+Finished in 0.002236 seconds.
+
+1 test, 1 assertion, 0 failures, 0 errors
+----------------------------------------------
+
+By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake:
+
+----------------------------------------------
+rake DB=sqlite
+rake DB=sqlite3
+rake DB=mysql
+rake DB=postgresql
+----------------------------------------------
+
+Now you are ready to test-drive your plugin!
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 b03a190e1a..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:
-
-[source, ruby]
----------------------------------------------------------------
-# 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:
-
-[source, ruby]
----------------------------------------------------------------
-# File: vendor/plugins/yaffle/init.rb
-
-require "view_helpers"
-ActionView::Base.send :include, YaffleViewHelper
----------------------------------------------------------------
-
-Then add the view helpers file and
-
-[source, ruby]
----------------------------------------------------------------
-# 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)
----------------------------------------------------------------
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]
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
+<h1>Hello world!</h1>
+<p><%= flash[:notice] %></p>
+-------------------------------------------------------
+
+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
+<h1><%=t :hello_world %></h1>
+<p><%= flash[:notice] %></p>
+-------------------------------------------------------
+
+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]
diff --git a/railties/doc/guides/source/migrations/index.txt b/railties/doc/guides/source/migrations/index.txt
index be183e8597..1670b73178 100644
--- a/railties/doc/guides/source/migrations/index.txt
+++ b/railties/doc/guides/source/migrations/index.txt
@@ -1,7 +1,7 @@
Migrations
==========
-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.
diff --git a/railties/doc/guides/source/migrations/rakeing_around.txt b/railties/doc/guides/source/migrations/rakeing_around.txt
index 6d8c43d7a3..b01451d54d 100644
--- a/railties/doc/guides/source/migrations/rakeing_around.txt
+++ b/railties/doc/guides/source/migrations/rakeing_around.txt
@@ -2,6 +2,8 @@
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/routing_outside_in.txt b/railties/doc/guides/source/routing_outside_in.txt
index a9ebb7bc36..4086fd0cbd 100644
--- a/railties/doc/guides/source/routing_outside_in.txt
+++ b/railties/doc/guides/source/routing_outside_in.txt
@@ -229,6 +229,8 @@ Although the conventions of RESTful routing are likely to be sufficient for many
* +:path_names+
* +:path_prefix+
* +:name_prefix+
+* +:only+
+* +:except+
You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide.
@@ -400,6 +402,30 @@ This combination will give you route helpers such as +photographer_photos_path+
NOTE: You can also use +:name_prefix+ with non-RESTful routes.
+==== Using :only and :except
+
+By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :only => [:index, :show]
+-------------------------------------------------------
+
+With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail.
+
+The +:except+ option specifies a route or list of routes that should _not_ be generated:
+
+[source, ruby]
+-------------------------------------------------------
+map.resources :photos, :except => :destroy
+-------------------------------------------------------
+
+In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/_id_+) will be generated.
+
+In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options.
+
+TIP: 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.
+
=== Nested Resources
It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:
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
---------------------------------------------------------------------------- */
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']:
-<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:
[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.
-<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.
+
+[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.
-<nil> 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 #<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.
@@ -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)