From 3b2b77baaef3c8b9a8794f4c37916adf27a4d63e Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 31 Oct 2008 11:15:12 +1030 Subject: Removed extra space from the array conditions section. --- railties/doc/guides/source/finders.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 945b527e1d..2e6b368e3f 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -134,7 +134,7 @@ If you'd like to add conditions to your find, you could just specify them in the === Array Conditions === - Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field. +Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field. The reason for doing code like: -- cgit v1.2.3 From 396d599e24cbfa15c62b20fab8cc02cdba046ce3 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 6 Nov 2008 01:10:30 +0530 Subject: Update guides from docrails --- railties/Rakefile | 21 +- railties/doc/guides/html/2_2_release_notes.html | 2 +- .../doc/guides/html/actioncontroller_basics.html | 299 +++++++++++++++------ .../html/activerecord_validations_callbacks.html | 267 ++++++++++++++++++ railties/doc/guides/html/authors.html | 13 + .../guides/html/debugging_rails_applications.html | 192 ++++++++++--- railties/doc/guides/html/finders.html | 45 ++-- railties/doc/guides/html/form_helpers.html | 76 +++++- .../guides/html/getting_started_with_rails.html | 114 ++++---- railties/doc/guides/html/index.html | 20 +- railties/doc/guides/html/migrations.html | 2 +- .../guides/html/testing_rails_applications.html | 67 ++--- railties/doc/guides/source/2_2_release_notes.txt | 2 +- .../source/actioncontroller_basics/changelog.txt | 5 + .../source/actioncontroller_basics/cookies.txt | 2 +- .../guides/source/actioncontroller_basics/csrf.txt | 32 +++ .../source/actioncontroller_basics/filters.txt | 18 +- .../source/actioncontroller_basics/http_auth.txt | 2 +- .../source/actioncontroller_basics/index.txt | 14 +- .../actioncontroller_basics/introduction.txt | 6 +- .../source/actioncontroller_basics/methods.txt | 10 +- .../parameter_filtering.txt | 4 +- .../source/actioncontroller_basics/params.txt | 43 ++- .../request_response_objects.txt | 30 ++- .../source/actioncontroller_basics/rescue.txt | 8 +- .../source/actioncontroller_basics/session.txt | 22 +- .../source/actioncontroller_basics/streaming.txt | 14 +- .../actioncontroller_basics/verification.txt | 6 +- .../doc/guides/source/active_record_basics.txt | 2 +- .../source/activerecord_validations_callbacks.txt | 25 ++ railties/doc/guides/source/authors.txt | 14 + railties/doc/guides/source/configuring.txt | 225 ++++++++++++++++ .../guides/source/debugging_rails_applications.txt | 110 +++++++- railties/doc/guides/source/finders.txt | 5 - railties/doc/guides/source/form_helpers.txt | 85 +++++- .../guides/source/getting_started_with_rails.txt | 23 +- railties/doc/guides/source/index.txt | 8 +- .../guides/source/migrations/rakeing_around.txt | 2 +- .../guides/source/testing_rails_applications.txt | 9 +- 39 files changed, 1476 insertions(+), 368 deletions(-) create mode 100644 railties/doc/guides/html/activerecord_validations_callbacks.html create mode 100644 railties/doc/guides/source/actioncontroller_basics/changelog.txt create mode 100644 railties/doc/guides/source/actioncontroller_basics/csrf.txt create mode 100644 railties/doc/guides/source/activerecord_validations_callbacks.txt create mode 100644 railties/doc/guides/source/configuring.txt diff --git a/railties/Rakefile b/railties/Rakefile index 872ea83ec2..52357a09c5 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -283,26 +283,35 @@ task :guides do template = File.expand_path("doc/guides/source/templates/guides.html.erb") - ignore = ['icons', 'images', 'templates', 'stylesheets'] + ignore = ['..', 'icons', 'images', 'templates', 'stylesheets'] ignore << 'active_record_basics.txt' indexless = ['index.txt', 'authors.txt'] - Dir.entries(source)[2..-1].each do |entry| + # Traverse all entries in doc/guides/source/ + Dir.entries(source).each do |entry| next if ignore.include?(entry) if File.directory?(File.join(source, entry)) - input = File.join(source, entry, 'index.txt') - output = File.join(html, entry) + # If the current entry is a directory, then we will want to compile + # the 'index.txt' file inside this directory. + if entry == '.' + input = File.join(source, 'index.txt') + output = File.join(html, "index.html") + else + input = File.join(source, entry, 'index.txt') + output = File.join(html, "#{entry}.html") + end else + # If the current entry is a file, then we will want to compile this file. input = File.join(source, entry) - output = File.join(html, entry).sub(/\.txt$/, '') + output = File.join(html, entry).sub(/\.txt$/, '.html') end begin puts "GENERATING => #{output}" ENV['MANUALSONRAILS_TOC'] = 'no' if indexless.include?(entry) - Mizuho::Generator.new(input, output, template).start + Mizuho::Generator.new(input, :output => output, :template => template).start rescue Mizuho::GenerationError STDERR.puts "*** ERROR" exit 2 diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index c68f10ad5a..931786ef6c 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -407,7 +407,7 @@ More information :

All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers.

-

If you want to these generate guides locally, inside your application:

+

If you want to generate these guides locally, inside your application:

-
class ClientsController < ActionController::Base
+
class ClientsController < ApplicationController
 
   # Actions are public methods
   def new
@@ -321,7 +374,7 @@ private
 end
 

Private methods in a controller are also used as filters, which will be covered later in this guide.

-

As an example, if the user goes to /clients/new in your application to add a new client, a ClientsController instance will be created and the new method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the new.html.erb view unless the action says otherwise. The new method could make available to the view a @client instance variable by creating a new Client:

+

As an example, if the user goes to /clients/new in your application to add a new client, Rails will create a ClientsController instance will be created and run the new method. Note that the empty method from the example above could work just fine because Rails will by default render the new.html.erb view unless the action says otherwise. The new method could make available to the view a @client instance variable by creating a new Client:

end

The Layouts & rendering guide explains this in more detail.

+

ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.

3. Parameters

-

You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller:

+

You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the params hash in your controller:

class ClientsController < ActionController::Base
 
-  # This action uses query string parameters because it gets run by a HTTP GET request,
-  # but this does not make any difference to the way in which the parameters are accessed.
-  # The URL for this action would look like this in order to list activated clients: /clients?status=activated
+  # This action uses query string parameters because it gets run by a HTTP
+  # GET request, but this does not make any difference to the way in which
+  # the parameters are accessed. The URL for this action would look like this
+  # in order to list activated clients: /clients?status=activated
   def index
     if params[:status] = "activated"
       @clients = Client.activated
@@ -370,11 +425,11 @@ http://www.gnu.org/software/src-highlite -->
 
 end
 
-

3.1. Hash and array parameters

+

3.1. Hash and Array Parameters

The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:

-
GET /clients?ids[]=1&ids[2]&ids[]=3
+
GET /clients?ids[]=1&ids[]=2&ids[]=3

The value of params[:ids] will now be ["1", "2", "3"]. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.

To send a hash you include the key name inside the brackets:

@@ -388,8 +443,32 @@ http://www.gnu.org/software/src-highlite --> </form>

The value of params[:client] when this form is submitted will be {:name ⇒ "Acme", :phone ⇒ "12345", :address ⇒ {:postcode ⇒ "12345", :city ⇒ "Carrot City"}}. Note the nested hash in params[:client][:address].

-

3.2. Routing parameters

-

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available.

+

3.2. Routing Parameters

+

The params hash will always contain the :controller and :action keys, but you should use the methods controller_name and action_name instead to access these values. Any other parameters defined by the routing, such as :id will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the :status parameter in a "pretty" URL:

+
+
+
# ...
+map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar"
+# ...
+
+

In this case, when a user opens the URL /clients/active, params[:status] will be set to "active". When this route is used, params[:foo] will also be set to "bar" just like it was passed in the query string in the same way params[:action] will contain "index".

+

3.3. default_url_options

+

You can set global default parameters that will be used when generating URLs with default_url_options. To do this, define a method with that name in your controller:

+
+
+
class ApplicationController < ActionController::Base
+
+  #The options parameter is the hash passed in to url_for
+  def default_url_options(options)
+    {:locale => I18n.locale}
+  end
+
+end
+
+

These options will be used as a starting-point when generating, so it's possible they'll be overridden by url_for. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.

4. Session

@@ -416,8 +495,9 @@ ActiveRecordStore - Stores the data in a database using Active Record.

-

All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server.

-

The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.

+

All session stores store either the session ID or the entire session in a cookie - Rails does not allow the session ID to be passed in any other way. Most stores also use this key to locate the session data on the server.

+

The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.

+

Read more about session storage in the Security Guide.

If you need a different session storage mechanism, you can change it in the config/environment.rb file:

# Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]
 config.action_controller.session_store = :active_record_store
 
-

4.1. Disabling the session

-

Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the session class method in your controller:

+

4.1. Disabling the Session

+

Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the session class method in your controller:

session :on end
-

Or even a single action:

+

Or even for specified actions:

session :on, :only => [:create, :update] end
-

4.2. Accessing the session

+

4.2. Accessing the Session

In your controller you can access the session through the session instance method.

@@ -481,7 +561,7 @@ http://www.gnu.org/software/src-highlite --> private # Finds the User with the ID stored in the session with the key :current_user_id - # This is a common way to do user login in a Rails application; logging in sets the + # This is a common way to handle user login in a Rails application; logging in sets the# session value and logging out removes it.def current_user @_current_user||= session[:current_user_id]&& User.find(session[:current_user_id]) @@ -525,9 +605,9 @@ http://www.gnu.org/software/src-highlite --> end -

To reset the entire session, use reset_session.

+

To reset the entire session, use reset_session.

4.3. The flash

-

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request:

+

The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:

end
-

4.3.1. flash.now

+

4.3.1. flash.now

By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the create action fails to save a resource and you render the new template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use flash.now in the same way you use the normal flash:

end
-

Note that while for session values, you set the key to nil, to delete a cookie value, you use cookies.delete(:key).

+

Note that while for session values, you set the key to nil, to delete a cookie value, you should use cookies.delete(:key).

6. Filters

-

Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first:

+

Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:

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, so to prevent this filter from running you can use skip_before_filter :

+

In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter :

end
-

Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

-

6.1. After filters and around filters

+

Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

+

6.1. After Filters and Around Filters

In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.

end

Note that the filter in this case uses send because the logged_in? method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.

-

The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class:

+

The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:

end
-

Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method filter which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same filter method, which will get run in the same way. The method must yield to execute the action. Alternatively, it can have both a before and an after method that are run before and after the action.

+

Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method filter which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same filter method, which will get run in the same way. The method must yield to execute the action. Alternatively, it can have both a before and an after method that are run before and after the action.

The Rails API documentation has more information on using filters.

7. Verification

-

Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the params, session or flash hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the API codumentation as "essentially a special kind of before_filter".

-

Let's see how we can use verification to make sure the user supplies a username and a password in order to log in:

+

Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the params, session or flash hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the API documentation as "essentially a special kind of before_filter".

+

Here's an example of using verification to make sure the user supplies a username and a password in order to log in:

verify :params => [:username, :password], :render => {:action => "new"}, :add_flash => {:error => "Username and password required to log in"}, - :only => :create #Only run this verification for the "create" action + :only => :create # Only run this verification for the "create" action end
-

8. The request and response objects

+

8. Request Forgery Protection

-

In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request method contains an instance of AbstractRequest and the response method contains the response object representing what is going to be sent back to the client.

-

8.1. The request

-

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 API documentation.

+

Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.

+

If you generate a form like this:

+
+
+
<% form_for @user do |f| -%>
+  <%= f.text_field :username %>
+  <%= f.text_field :password -%>
+<% end -%>
+
+

You will see how the token gets added as a hidden field:

+
+
+
<form action="/users/1" method="post">
+<div><!-- ... --><input type="hidden" value="67250ab105eb5ad10851c00a5621854a23af5489" name="authenticity_token"/></div>
+<!-- Fields -->
+</form>
+
+

Rails adds this token to every form that's generated using the form helpers, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method form_authenticity_token:

+
+
Example: Add a JavaScript variable containing the token for use with Ajax
+
+
<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %>
+
+

The Security Guide has more about this and a lot of other security-related issues that you should be aware of when developing a web application.

+
+

9. The request and response Objects

+
+

In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The request method contains an instance of AbstractRequest and the response method returns a response object representing what is going to be sent back to the client.

+

9.1. The request Object

+

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 API documentation. Among the properties that you can access on this object:

  • @@ -812,7 +925,7 @@ host - The hostname used for this request.

  • -domain - The hostname without the first part (usually "www"). +domain - The hostname without the first segment (usually "www").

  • @@ -861,11 +974,10 @@ url - The entire URL used for the request.

-

8.1.1. path_parameters, query_parameters and request_parameters

-

TODO: Does this belong here?

-

Rails collects all of the parameters sent along with the request in the params hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters hash contains parameters that were sent as part of the query string while the request_parameters hash contains parameters sent as part of the post body. The path_parameters hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action.

-

8.2. The response

-

The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.

+

9.1.1. path_parameters, query_parameters and request_parameters

+

Rails collects all of the parameters sent along with the request in the params hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The query_parameters hash contains parameters that were sent as part of the query string while the request_parameters hash contains parameters sent as part of the post body. The path_parameters hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.

+

9.2. The response Object

+

The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.

  • @@ -892,11 +1004,25 @@ content_type - The content type of the response. charset - The character set being used for the response. Default is "utf8".

  • +
  • +

    +headers - Headers used for the response. +

    +
+

9.2.1. Setting Custom Headers

+

If you want to set custom headers for a response then response.headers is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to headers with the name and value:

+
+
+
response.headers["Content-Type"] = "application/pdf"
+
-

9. HTTP Basic Authentication

+

10. HTTP Basic Authentication

-

Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, authenticate_or_request_with_http_basic.

+

Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, authenticate_or_request_with_http_basic.

- +
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 as someone could gain access to files they are not meant to have access to.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.
@@ -986,8 +1112,8 @@ http://www.gnu.org/software/src-highlite --> 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.
-

10.2. RESTful downloads

-

While send_data works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the show action:

+

11.2. RESTful Downloads

+

While send_data works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the show action, without any streaming:

end
-

In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb:

+

In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file config/initializers/mime_types.rb:

GET /clients/1.pdf
-

11. Parameter filtering

+

12. 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 keys 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":

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.

-

12. Rescue

+

13. Rescue

Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application:

-

12.1. The default 500 and 404 templates

+

13.1. The Default 500 and 404 Templates

By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the public folder, in 404.html and 500.html respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML.

-

12.2. rescue_from

-

If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.

-

Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.

+

13.2. rescue_from

+

If you want to do something a bit more elaborate when catching errors, you can use rescue_from, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the :with option. You can also use a block directly instead of an explicit Proc object.

+

Here's how you can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them.

+ + + + + + + + +
+ + + +
+

Active Record Validations and Callbacks

+
+
+

This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles.

+

After reading this guide and trying out the presented concepts, we hope that you'll be able to:

+
    +
  • +

    +Correctly use all the built-in Active Record validation helpers +

    +
  • +
  • +

    +Create your own custom validation methods +

    +
  • +
  • +

    +Work with the error messages generated by the validation proccess +

    +
  • +
  • +

    +Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved. +

    +
  • +
  • +

    +Create special classes that encapsulate common behaviour for your callbacks +

    +
  • +
  • +

    +Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations. +

    +
  • +
+
+
+

1. Active Record Validations

+
+
+

2. Credits

+
+
+

3. Changelog

+ + +
+
+ + diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html index 973cf7cd2e..a54135b14d 100644 --- a/railties/doc/guides/html/authors.html +++ b/railties/doc/guides/html/authors.html @@ -218,6 +218,19 @@ work with Rails. His near-daily links and other blogging can be found at Eventioz. He has been using Rails since 2006 and contributing since early 2008. Can be found at gmail, twitter, freenode, everywhere as miloops.

+
+
+
+
diff --git a/railties/doc/guides/html/debugging_rails_applications.html b/railties/doc/guides/html/debugging_rails_applications.html index bf1e442d59..95f5b39e4c 100644 --- a/railties/doc/guides/html/debugging_rails_applications.html +++ b/railties/doc/guides/html/debugging_rails_applications.html @@ -208,6 +208,8 @@ ul#navMain {
  • inspect
  • +
  • Debugging Javascript
  • +
  • @@ -253,6 +255,19 @@ ul#navMain {
  • + Debugging Memory Leaks + +
  • +
  • + Plugins for Debugging +
  • +
  • References
  • @@ -325,10 +340,7 @@ http://www.gnu.org/software/src-highlite -->

    You'll see something like this:

    -
    +
    --- !ruby/object:Post
     attributes:
       updated_at: 2008-09-05 22:55:47
    @@ -340,8 +352,8 @@ attributes:
     attributes_cache: {}
     
     
    -Title: Rails debugging guide
    -
    +Title: Rails debugging guide +

    1.2. to_yaml

    Displaying an instance variable, or any other object or method, in yaml format can be achieved this way:

    @@ -358,10 +370,7 @@ http://www.gnu.org/software/src-highlite -->

    The to_yaml method converts the method to YAML format leaving it more readable, and then the simple_format helper is used to render each line as in the console. This is how debug method does its magic.

    As a result of this, you will have something like this in your view:

    -
    +
    --- !ruby/object:Post
     attributes:
     updated_at: 2008-09-05 22:55:47
    @@ -372,8 +381,8 @@ id: "1"
     created_at: 2008-09-05 22:55:47
     attributes_cache: {}
     
    -Title: Rails debugging guide
    -
    +Title: Rails debugging guide +

    1.3. inspect

    Another useful method for displaying object values is inspect, especially when working with arrays or hashes. This will print the object value as a string. For example:

    @@ -389,14 +398,37 @@ http://www.gnu.org/software/src-highlite -->

    Will be rendered as follows:

    +
    +
    [1, 2, 3, 4, 5]
    +
    +Title: Rails debugging guide
    +
    +

    1.4. Debugging Javascript

    +

    Rails has built-in support to debug RJS, to active it, set ActionView::Base.debug_rjs to true, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).

    +

    To enable it, add the following in the Rails::Initializer do |config| block inside environment.rb:

    +
    -
    [1, 2, 3, 4, 5]
    -
    -Title: Rails debugging guide
    +
    config.action_view[:debug_rjs] = true
    +
    +

    Or, at any time, setting ActionView::Base.debug_rjs to true:

    +
    +
    +
    ActionView::Base.debug_rjs = true
     
    +
    + + + +
    +Tip +For more information on debugging javascript refer to Firebug, the popular debugger for Firefox.
    +

    2. The Logger

    @@ -488,11 +520,8 @@ http://www.gnu.org/software/src-highlite -->

    Here's an example of the log generated by this method:

    -
    -
    Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
    +
    +
    Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
       Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
     vbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhhc2h7AAY6CkB1c2VkewA=--b18cd92fba90eacf8137e5f6b3b06c4d724596a4
       Parameters: {"commit"=>"Create", "post"=>{"title"=>"Debugging Rails",
    @@ -506,8 +535,8 @@ Post should be valid: true
      'I''m learning how to print in logs!!!', 'f', '2008-09-08 14:52:54')
     The post was saved and now is the user is going to be redirected...
     Redirected to #<Post:0x20af760>
    -Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts]
    -
    +Completed in 0.01224 (81 reqs/sec) | DB: 0.00044 (3%) | 302 Found [http://localhost/posts] +

    Adding extra logging like this makes it easy to search for unexpected or unusual behavior in your logs. If you add extra logging, be sure to make sensible use of log levels, to avoid filling your production logs with useless trivia.

    3. Debugging with ruby-debug

    @@ -540,12 +569,9 @@ http://www.gnu.org/software/src-highlite -->

    If you see the message in the console or logs:

    -
    -
    ***** Debugger requested, but was not available: Start server with --debugger to enable *****
    -
    +
    +
    ***** Debugger requested, but was not available: Start server with --debugger to enable *****
    +

    Make sure you have started your web server with the option —debugger:

    @posts = Post.find(:all)
     (rdb:7)
    -

    Now it's time to play and dig into your application. A good place to start is by asking the debugger for help… so type: help (You didn't see that coming, right?)

    +

    Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help… so type: help (You didn't see that coming, right?)

    (rdb:7) help
    @@ -969,16 +995,104 @@ No breakpoints.

    Here's a good start for an .rdebugrc:

    +
    +
    set autolist
    +set forcestep
    +set listsize 25
    +
    +
    +

    4. Debugging Memory Leaks

    +
    +

    A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.

    +

    In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.

    +

    4.1. BleakHouse

    +

    BleakHouse is a library for finding memory leaks.

    +

    If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.

    +

    To install it run:

    +
    +
    +
    sudo gem install bleak_house
    +
    +

    Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:

    +
    -
    set autolist
    -set forcestep
    -set listsize 25
    +
    require 'bleak_house' if ENV['BLEAK_HOUSE']
     
    +

    Start a server instance with BleakHouse integration:

    +
    +
    +
    RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server
    +
    +

    Make sure to run a couple hundred requests to get better data samples, then press CTRL-C. The server will stop and Bleak House will produce a dumpfile in /tmp:

    +
    +
    +
    ** BleakHouse: working...
    +** BleakHouse: complete
    +** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
    +
    +

    To analyze it, just run the listed command. The top 20 leakiest lines will be listed:

    +
    +
    +
      191691 total objects
    +  Final heap size 191691 filled, 220961 free
    +  Displaying top 20 most common line/class pairs
    +  89513 __null__:__null__:__node__
    +  41438 __null__:__null__:String
    +  2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
    +  1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
    +  1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
    +   951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
    +   935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
    +   834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
    +  ...
    +
    +

    This way you can find where your application is leaking memory and fix it.

    +

    If BleakHouse doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.

    +

    4.2. Valgrind

    +

    Valgrind is a Linux-only application for detecting C-based memory leaks and race conditions.

    +

    There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls malloc() but is doesn't properly call free(), this memory won't be available until the app terminates.

    +

    For further information on how to install Valgrind and use with Ruby, refer to Valgrind and Ruby by Evan Weaver.

    -

    4. References

    +

    5. Plugins for Debugging

    +
    +

    There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:

    +
      +
    • +

      +Footnotes: Every Rails page has footnotes that link give request information and link back to your source via TextMate. +

      +
    • +
    • +

      +Query Trace: Adds query origin tracing to your logs. +

      +
    • +
    • +

      +Query Stats: A Rails plugin to track database queries. +

      +
    • +
    • +

      +Query Reviewer: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed. +

      +
    • +
    • +

      +Exception Notifier: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application. +

      +
    • +
    • +

      +Exception Logger: Logs your Rails exceptions in the database and provides a funky web interface to manage them. +

      +
    • +
    +
    +

    6. References

    -

    5. Changelog

    +

    7. Changelog

    • +November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by Emilio Tagua +

      +
    • +
    • +

      October 19, 2008: Copy editing pass by Mike Gunderloy

    • diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index f8396bb517..18bc32306f 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -373,27 +373,21 @@ http://www.gnu.org/software/src-highlite -->
      SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2))
       
    -
    +
    >> Client.find(1,2)
     => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
       created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
       #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    -  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    -
    + created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    +

    Note that if you pass in a list of numbers that the result will be returned as an array, not as a single Client object.

    If you wanted to find the first client you would simply type Client.first and that would find the first client created in your clients table:

    -
    +
    >> Client.first
     => #<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
    -  created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">
    -
    + created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"> +

    If you were running script/server you might see the following output:

    Indicating the query that Rails has performed on your database.

    To find the last client you would simply type Client.find(:last) and that would find the last client created in your clients table:

    -
    +
    >> Client.find(:last)
     => #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    -  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">
    -
    + created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"> +

    To find all the clients you would simply type Client.all and that would find all the clients in your clients table:

    -
    +
    >> Client.all
     => [#<Client id: 1, name: => "Ryan", locked: false, orders_count: 2,
       created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">,
       #<Client id: 2, name: => "Michael", locked: false, orders_count: 3,
    -  created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    -
    + created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">] +

    As alternatives to calling Client.first, Client.last, and Client.all, you can use the class methods Client.first, Client.last, and Client.all instead. Client.first, Client.last and Client.all just call their longer counterparts: Client.find(:first), Client.find(:last) and Client.find(:all) respectively.

    Be aware that Client.first/Client.find(:first) and Client.last/Client.find(:last) will both return a single object, where as Client.all/Client.find(:all) will return an array of Client objects, just as passing in an array of ids to find will do also.

    @@ -510,12 +498,9 @@ http://www.gnu.org/software/src-highlite -->

    This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:

    -
    -
    Got a packet bigger than 'max_allowed_packet' bytes: _query_
    -
    +
    +
    Got a packet bigger than 'max_allowed_packet' bytes: _query_
    +

    Where query is the actual query used to get that error.

    In this example it would be better to use greater-than and less-than operators in SQL, like so:

    diff --git a/railties/doc/guides/html/form_helpers.html b/railties/doc/guides/html/form_helpers.html index 28c317411b..7ff4a13a6a 100644 --- a/railties/doc/guides/html/form_helpers.html +++ b/railties/doc/guides/html/form_helpers.html @@ -220,6 +220,16 @@ ul#navMain {
  • +
  • + Making select boxes with ease + +
  • @@ -227,7 +237,7 @@ ul#navMain {

    Rails form helpers

    -

    Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.

    +

    Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.

    In this guide we will:

    • @@ -392,7 +402,7 @@ a submit element. Warning -Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly expecting tASSOC syntax error. +Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an expecting tASSOC syntax error.

    1.3. Checkboxes, radio buttons and other controls

    @@ -431,7 +441,7 @@ output: Important -Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region. +Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.

    Other form controls we might mention are the text area, password input and hidden input:

    @@ -458,7 +468,7 @@ output:

    1.4. How do forms with PUT or DELETE methods work?

    Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers don't support methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?

    -

    Rails works around this issue by emulating other methods over POST with a hidden input named "method" that is set to reflect the _real method:

    +

    Rails works around this issue by emulating other methods over POST with a hidden input named "_method" that is set to reflect the wanted method:

    form_tag(search_path, :method => "put")
    @@ -562,6 +572,64 @@ form_for(@article)
    When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, :url and :method explicitly.
    +
    +

    3. Making select boxes with ease

    +
    +

    Select boxes in HTML require a significant amount of markup (one OPTION element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.

    +

    Here is what our wanted markup might look like:

    +
    +
    +
    <select name="city_id" id="city_id">
    +  <option value="1">Lisabon</option>
    +  <option value="2">Madrid</option>
    +  ...
    +  <option value="12">Berlin</option>
    +</select>
    +
    +

    Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.

    +

    3.1. The select tag and options

    +

    The most generic helper is select_tag, which — as the name implies — simply generates the SELECT tag that encapsulates the options:

    +
    +
    +
    <%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
    +
    +

    This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.

    +

    We can generate option tags with the options_for_select helper:

    +
    +
    +
    <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
    +
    +output:
    +
    +<option value="1">Lisabon</option>
    +<option value="2">Madrid</option>
    +...
    +
    +

    For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).

    +

    Now you can combine select_tag and options_for_select to achieve the desired, complete markup:

    +
    +
    +
    <%= select_tag(:city_id, options_for_select(...)) %>
    +
    +

    Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The options_for_select helper supports this with an optional second argument:

    +
    +
    +
    <%= options_for_select(cities_array, 2) %>
    +
    +output:
    +
    +<option value="1">Lisabon</option>
    +<option value="2" selected="selected">Madrid</option>
    +...
    +
    +

    So whenever Rails sees that the internal value of an option being generated matches this value, it will add the selected attribute to that option.

    +

    3.2. Select boxes for dealing with models

    +

    Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a city_id attribute.

    +
    +
    +
    ...
    +
    +

    diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 797ae2fb3a..1b2eac0ce5 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -1457,51 +1457,57 @@ http://www.gnu.org/software/src-highlite -->

    At this point, it’s worth looking at some of the tools that Rails provides to eliminate duplication in your code. In particular, you can use partials to clean up duplication in views and filters to help with duplication in controllers.

    7.1. Using Partials to Eliminate View Duplication

    As you saw earlier, the scaffold-generated views for the new and edit actions are largely identical. You can pull the shared code out into a partial template. This requires editing the new and edit views, and adding a new template:

    -

    new.html.erb: -[source, ruby]

    +

    new.html.erb:

    -
    -
    <h1>New post</h1>
    +
    +
    <h1>New post</h1>
     
    -<%= render :partial => "form" %>
    +<%= render :partial => "form" %>
     
    -<%= link_to 'Back', posts_path %>
    -
    -

    edit.html.erb: -[source, ruby]

    +<%= link_to 'Back', posts_path %> +
    +

    edit.html.erb:

    -
    -
    <h1>Editing post</h1>
    +
    +
    <h1>Editing post</h1>
     
    -<%= render :partial => "form" %>
    +<%= render :partial => "form" %>
     
    -<%= link_to 'Show', @post %> |
    -<%= link_to 'Back', posts_path %>
    -
    -

    _form.html.erb: -[source, ruby]

    +<%= link_to 'Show', @post %> | +<%= link_to 'Back', posts_path %> +
    +

    _form.html.erb:

    -
    -
    <% form_for(@post) do |f| %>
    -  <%= f.error_messages %>
    -
    -  <p>
    -    <%= f.label :name %><br />
    -    <%= f.text_field :name %>
    -  </p>
    -  <p>
    -    <%= f.label :title, "title" %><br />
    -    <%= f.text_field :title %>
    -  </p>
    -  <p>
    -    <%= f.label :content %><br />
    -    <%= f.text_area :content %>
    -  </p>
    -  <p>
    -    <%= f.submit "Save" %>
    -  </p>
    -<% end %>
    -
    +
    +
    <% form_for(@post) do |f| %>
    +  <%= f.error_messages %>
    +
    +  <p>
    +    <%= f.label :name %><br />
    +    <%= f.text_field :name %>
    +  </p>
    +  <p>
    +    <%= f.label :title, "title" %><br />
    +    <%= f.text_field :title %>
    +  </p>
    +  <p>
    +    <%= f.label :content %><br />
    +    <%= f.text_area :content %>
    +  </p>
    +  <p>
    +    <%= f.submit "Save" %>
    +  </p>
    +<% end %>
    +

    Now, when Rails renders the new or edit view, it will insert the _form partial at the indicated point. Note the naming convention for partials: if you refer to a partial named form inside of a view, the corresponding file is _form.html.erb, with a leading underscore.

    For more information on partials, refer to the Layouts and Rending in Rails guide.

    7.2. Using Filters to Eliminate Controller Duplication

    @@ -1721,32 +1727,32 @@ http://www.gnu.org/software/src-highlite -->
  • -+app/helpers/comments_helper.rb - A view helper file +app/helpers/comments_helper.rb - A view helper file

  • -+app/views/comments/index.html.erb - The view for the index action +app/views/comments/index.html.erb - The view for the index action

  • -+app/views/comments/show.html.erb - The view for the show action +app/views/comments/show.html.erb - The view for the show action

  • -+app/views/comments/new.html.erb - The view for the new action +app/views/comments/new.html.erb - The view for the new action

  • -+app/views/comments/edit.html.erb - The view for the edit action +app/views/comments/edit.html.erb - The view for the edit action

  • -+test/functional/comments_controller_test.rb - The functional tests for the controller +test/functional/comments_controller_test.rb - The functional tests for the controller

  • @@ -1984,7 +1990,7 @@ http://www.gnu.org/software/src-highlite -->
    +

    Rails also comes with built-in help that you can generate using the rake command-line utility:

    +
      +
    • +

      +Running rake doc:guides will put a full copy of the Rails Guides in the /doc/guides folder of your application. Open /doc/guides/index.html in your web browser to explore the Guides. +

      +
    • +
    • +

      +Running rake doc:rails will put a full copy of the API documentation for Rails in the /doc/api folder of your application. Open /doc/api/index.html in your web browser to explore the API documentation. +

      +
    • +

    10. Changelog

    @@ -2010,6 +2029,11 @@ The Rails wiki
    • +November 3, 2008: Formatting patch from Dave Rothlisberger +

      +
    • +
    • +

      November 1, 2008: First approved version by Mike Gunderloy

    • diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index 306257678b..991b10c7e8 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -250,7 +250,7 @@ ul#navMain {
    @@ -276,14 +276,6 @@ understand how to use routing in your own Rails applications, start here.

    @@ -318,20 +310,12 @@ Enjoy.

    -

    will run the down method fron the last 3 migrations.

    +

    will run the down method from the last 3 migrations.

    The db:migrate:redo task is a shortcut for doing a rollback and then migrating back up again. As with the db:rollback task you can use the STEP parameter if you need to go more than one version back, for example

    diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html index 73634ef328..666d1dff85 100644 --- a/railties/doc/guides/html/testing_rails_applications.html +++ b/railties/doc/guides/html/testing_rails_applications.html @@ -233,7 +233,7 @@ ul#navMain {
  • What to include in your Functional Tests
  • -
  • Available Request Types for Functional Tests===
  • +
  • Available Request Types for Functional Tests
  • The 4 Hashes of the Apocalypse
  • @@ -398,15 +398,12 @@ steve:

    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"
    -
    +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:

    • @@ -535,17 +532,14 @@ email(david.

      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:

    -
    +
    $ script/generate model Post
     ...
     create  app/models/post.rb
     create  test/unit/post_test.rb
     create  test/fixtures/posts.yml
    -...
    -
    +... +

    The default test stub in test/unit/post_test.rb looks like this:

    +
    $ ruby unit/post_test.rb -n test_truth
     
     Loaded suite unit/post_test
    @@ -648,8 +639,8 @@ Started
     .
     Finished in 0.023513 seconds.
     
    -1 tests, 1 assertions, 0 failures, 0 errors
    -
    +1 tests, 1 assertions, 0 failures, 0 errors +

    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:

    @@ -664,10 +655,7 @@ http://www.gnu.org/software/src-highlite -->

    If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:

    -
    +
    $ ruby unit/post_test.rb
     Loaded suite unit/post_test
     Started
    @@ -681,8 +669,8 @@ test_should_have_atleast_one_post(PostTest)
          /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.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    -
    +2 tests, 2 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:

    Running this test shows the friendlier assertion message:

    -
    +
    $ ruby unit/post_test.rb
     Loaded suite unit/post_test
     Started
    @@ -714,8 +699,8 @@ test_should_have_atleast_one_post(PostTest)
     Should not be nil as Posts table should have atleast one post.
     <nil> expected to not be nil.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    -
    +2 tests, 2 assertions, 1 failures, 0 errors +

    To see how an error gets reported, here's a test containing an error:

    Now you can see even more output in the console from running the tests:

    -
    +
    $ ruby unit/post_test.rb
     Loaded suite unit/post_test
     Started
    @@ -756,8 +738,8 @@ NameError: undefined local variable or method `some_undefined_variable' for #<
         /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
    -
    +3 tests, 2 assertions, 1 failures, 1 errors +

    Notice the E in the output. It denotes a test with error.

    @@ -1160,7 +1142,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
     
    -

    4.2. Available Request Types for Functional Tests===

    +

    4.2. Available Request Types for Functional Tests

    If you're familiar with the HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails functional tests:

    • @@ -1638,16 +1620,13 @@ http://www.gnu.org/software/src-highlite -->

      In this test, @expected is an instance of TMail::Mail that you can use in your tests. It is defined in ActionMailer::TestCase. The test above uses @expected to construct an email, which it then asserts with email created by the custom mailer. The invite fixture is the body of the email and is used as the sample content to assert against. The helper read_fixture is used to read in the content from this file.

      Here's the content of the invite fixture:

      -
      +
      Hi friend@example.com,
       
       You have been invited.
       
      -Cheers!
      -
      +Cheers! +

    This is the right time to understand a little more about writing tests for your mailers. The line ActionMailer::Base.delivery_method = :test in config/environments/test.rb sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (ActionMailer::Base.deliveries).

    However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be.

    6.3. Functional Testing

    diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt index 2e9e9b8aa1..715648b95e 100644 --- a/railties/doc/guides/source/2_2_release_notes.txt +++ b/railties/doc/guides/source/2_2_release_notes.txt @@ -44,7 +44,7 @@ The internal documentation of Rails, in the form of code comments, has been impr All told, the Guides provide tens of thousands of words of guidance for beginning and intermediate Rails developers. -If you want to these generate guides locally, inside your application: +If you want to generate these guides locally, inside your application: [source, ruby] ------------------------------------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/changelog.txt b/railties/doc/guides/source/actioncontroller_basics/changelog.txt new file mode 100644 index 0000000000..4ee16af19e --- /dev/null +++ b/railties/doc/guides/source/actioncontroller_basics/changelog.txt @@ -0,0 +1,5 @@ +== Changelog == + +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17[Lighthouse ticket] + +* November 4, 2008: First release version by Tore Darrell diff --git a/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/railties/doc/guides/source/actioncontroller_basics/cookies.txt index d451f3f7a6..88b99de3ee 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 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/csrf.txt b/railties/doc/guides/source/actioncontroller_basics/csrf.txt new file mode 100644 index 0000000000..87e3d39c88 --- /dev/null +++ b/railties/doc/guides/source/actioncontroller_basics/csrf.txt @@ -0,0 +1,32 @@ +== Request Forgery Protection == + +Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user's knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access. + +If you generate a form like this: + +[source, ruby] +----------------------------------------- +<% form_for @user do |f| -%> + <%= f.text_field :username %> + <%= f.text_field :password -%> +<% end -%> +----------------------------------------- + +You will see how the token gets added as a hidden field: + +[source, html] +----------------------------------------- + +
    + + +----------------------------------------- + +Rails adds this token to every form that's generated using the link:../form_helpers.html[form helpers], so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method `form_authenticity_token`: + +.Add a JavaScript variable containing the token for use with Ajax +----------------------------------------- +<%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %> +----------------------------------------- + +The link:../security.html[Security Guide] has more about this and a lot of other security-related issues that you should be aware of when developing a web application. diff --git a/railties/doc/guides/source/actioncontroller_basics/filters.txt b/railties/doc/guides/source/actioncontroller_basics/filters.txt index a6f688d144..df67977efd 100644 --- a/railties/doc/guides/source/actioncontroller_basics/filters.txt +++ b/railties/doc/guides/source/actioncontroller_basics/filters.txt @@ -1,6 +1,6 @@ == Filters == -Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. Let's define the filter method first: +Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way: [source, ruby] --------------------------------- @@ -27,7 +27,7 @@ private end --------------------------------- -The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering/redirecting filter, they are also cancelled. To use this filter in a controller, use the link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000704[before_filter] method: +The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the `before_filter` method: [source, ruby] --------------------------------- @@ -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, so to prevent this filter from running you can use link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html#M000711[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,9 +49,9 @@ 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 === +=== After Filters and Around Filters === In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it. @@ -75,11 +75,11 @@ private end --------------------------------- -=== Other ways to use filters === +=== Other Ways to Use Filters === While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing. -The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritte to use a block: +The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block: [source, ruby] --------------------------------- @@ -92,7 +92,7 @@ end Note that the filter in this case uses `send` because the `logged_in?` method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful. -The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, we will rewrite the login filter again to use a class: +The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class: [source, ruby] --------------------------------- @@ -114,6 +114,6 @@ class LoginFilter end --------------------------------- -Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets it passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action. +Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action. The Rails API documentation has link:http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html[more information on using filters]. diff --git a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt index 7df0e635bf..954b8a525e 100644 --- a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt +++ b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt @@ -1,6 +1,6 @@ == HTTP Basic Authentication == -Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, we will create an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, link:http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic/ControllerMethods.html#M000610[authenticate_or_request_with_http_basic]. +Rails comes with built-in HTTP Basic authentication. This is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `authenticate_or_request_with_http_basic`. [source, ruby] ------------------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/index.txt b/railties/doc/guides/source/actioncontroller_basics/index.txt index 0b884e590b..6865ace97b 100644 --- a/railties/doc/guides/source/actioncontroller_basics/index.txt +++ b/railties/doc/guides/source/actioncontroller_basics/index.txt @@ -1,7 +1,15 @@ Action Controller basics ======================= -In this guide you will learn how controllers work and how they fit into the request cycle in your application. You will learn how to make use of the many tools provided by Action Controller to work with the session, cookies and filters and how to use the built-in HTTP authentication and data streaming facilities. In the end, we will take a look at some tools that will be useful once your controllers are ready and working, like how to filter sensitive parameters from the log and how to rescue and deal with exceptions that may be raised during the request. +In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to: + +* Follow the flow of a request through a controller +* Understand why and how to store data in the session or cookies +* Work with filters to execute code during request processing +* Use Action Controller's built-in HTTP authentication +* Stream data directly to the user's browser +* Filter sensitive parameters so they do not appear in the application's log +* Deal with exceptions that may be raised during request processing include::introduction.txt[] @@ -17,6 +25,8 @@ include::filters.txt[] include::verification.txt[] +include::csrf.txt[] + include::request_response_objects.txt[] include::http_auth.txt[] @@ -26,3 +36,5 @@ include::streaming.txt[] include::parameter_filtering.txt[] include::rescue.txt[] + +include::changelog.txt[] diff --git a/railties/doc/guides/source/actioncontroller_basics/introduction.txt b/railties/doc/guides/source/actioncontroller_basics/introduction.txt index e4b0953b95..6ea217dbb9 100644 --- a/railties/doc/guides/source/actioncontroller_basics/introduction.txt +++ b/railties/doc/guides/source/actioncontroller_basics/introduction.txt @@ -1,7 +1,9 @@ -== What does a controller do? == +== What Does a Controller do? == Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible. For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work. -A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display it to the user, and it saves or updates data from the user to the model. +A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model. + +NOTE: For more details on the routing process, see link:../routing_outside_in.html[Rails Routing from the Outside In]. diff --git a/railties/doc/guides/source/actioncontroller_basics/methods.txt b/railties/doc/guides/source/actioncontroller_basics/methods.txt index 370b492e41..c6ae54a540 100644 --- a/railties/doc/guides/source/actioncontroller_basics/methods.txt +++ b/railties/doc/guides/source/actioncontroller_basics/methods.txt @@ -1,10 +1,10 @@ -== Methods and actions == +== Methods and Actions == -A controller is a Ruby class which inherits from ActionController::Base and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then an instance of that controller will be created and the method corresponding to the action (the method with the same name as the action) gets run. +A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. Usually these methods correspond to actions in MVC, but they can just as well be helpful methods which can be called by actions. When your application receives a request, the routing will determine which controller and action to run. Then Rails creates an instance of that controller and runs the method corresponding to the action (the method with the same name as the action). [source, ruby] ---------------------------------------------- -class ClientsController < ActionController::Base +class ClientsController < ApplicationController # Actions are public methods def new @@ -25,7 +25,7 @@ end Private methods in a controller are also used as filters, which will be covered later in this guide. -As an example, if the user goes to `/clients/new` in your application to add a new client, a ClientsController instance will be created and the `new` method will be run. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client: +As an example, if the user goes to `/clients/new` in your application to add a new client, Rails will create a ClientsController instance will be created and run the `new` method. Note that the empty method from the example above could work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new Client: [source, ruby] ---------------------------------------------- @@ -35,3 +35,5 @@ end ---------------------------------------------- The link:../layouts_and_rendering.html[Layouts & rendering guide] explains this in more detail. + +ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself. diff --git a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt index c4577d4f6d..e29f631038 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 == +== 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 link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000837[filter_parameter_logging] method can be used to filter out sensitive information from the log. It works by replacing certain keys 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] ------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/params.txt b/railties/doc/guides/source/actioncontroller_basics/params.txt index 7f494d7c9b..fb380519fd 100644 --- a/railties/doc/guides/source/actioncontroller_basics/params.txt +++ b/railties/doc/guides/source/actioncontroller_basics/params.txt @@ -1,14 +1,15 @@ == Parameters == -You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller: +You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller: [source, ruby] ------------------------------------- class ClientsController < ActionController::Base - # This action uses query string parameters because it gets run by a HTTP GET request, - # but this does not make any difference to the way in which the parameters are accessed. - # The URL for this action would look like this in order to list activated clients: /clients?status=activated + # This action uses query string parameters because it gets run by a HTTP + # GET request, but this does not make any difference to the way in which + # the parameters are accessed. The URL for this action would look like this + # in order to list activated clients: /clients?status=activated def index if params[:status] = "activated" @clients = Client.activated @@ -34,12 +35,12 @@ class ClientsController < ActionController::Base end ------------------------------------- -=== Hash and array parameters === +=== Hash and Array Parameters === The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name: ------------------------------------- -GET /clients?ids[]=1&ids[2]&ids[]=3 +GET /clients?ids[]=1&ids[]=2&ids[]=3 ------------------------------------- The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type. @@ -57,6 +58,32 @@ To send a hash you include the key name inside the brackets: The value of `params[:client]` when this form is submitted will be `{:name => "Acme", :phone => "12345", :address => {:postcode => "12345", :city => "Carrot City"}}`. Note the nested hash in `params[:client][:address]`. -=== Routing parameters === +=== Routing Parameters === -The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. +The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the `:status` parameter in a "pretty" URL: + +[source, ruby] +------------------------------------ +# ... +map.connect "/clients/:status", :controller => "clients", :action => "index", :foo => "bar" +# ... +------------------------------------ + +In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string in the same way `params[:action]` will contain "index". + +=== `default_url_options` === + +You can set global default parameters that will be used when generating URLs with `default_url_options`. To do this, define a method with that name in your controller: + +------------------------------------ +class ApplicationController < ActionController::Base + + #The options parameter is the hash passed in to url_for + def default_url_options(options) + {:locale => I18n.locale} + end + +end +------------------------------------ + +These options will be used as a starting-point when generating, so it's possible they'll be overridden by url_for. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there. 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 493bd4cb43..250f84bd72 100644 --- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt +++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt @@ -1,13 +1,13 @@ -== The request and response objects == +== The +request+ and +response+ Objects == -In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[AbstractRequest] and the `response` method contains the link:http://github.com/rails/rails/tree/master/actionpack/lib/action_controller/response.rb[response object] representing what is going to be sent back to the client. +In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The `request` method contains an instance of AbstractRequest and the `response` method returns a +response+ object representing what is going to be sent back to the client. -=== The request === +=== The +request+ Object === -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]. +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: * host - The hostname used for this request. - * domain - The hostname without the first part (usually "www"). + * domain - The hostname without the first segment (usually "www"). * 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. @@ -18,18 +18,26 @@ The request object contains a lot of useful information about the request coming * remote_ip - The IP address of the client. * url - The entire URL used for the request. -==== path_parameters, query_parameters and request_parameters ==== +==== +path_parameters+, +query_parameters+ and +request_parameters+ ==== -TODO: Does this belong here? +Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action. -Rails collects all of the parameters sent along with the request in the `params` hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognised by the routing as being part of the path leading to this particular controller and action. +=== The +response+ Object === -=== The response === - -The response objects is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. +The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. * body - This is the string of data being sent back to the client. This is most often HTML. * status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found. * location - The URL the client is being redirected to, if any. * content_type - The content type of the response. * charset - The character set being used for the response. Default is "utf8". + * headers - Headers used for the response. + +==== Setting Custom Headers ==== + +If you want to set custom headers for a response then `response.headers` is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to `headers` with the name and value: + +[source, ruby] +------------------------------------- +response.headers["Content-Type"] = "application/pdf" +------------------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/rescue.txt b/railties/doc/guides/source/actioncontroller_basics/rescue.txt index ec03006764..3353df617c 100644 --- a/railties/doc/guides/source/actioncontroller_basics/rescue.txt +++ b/railties/doc/guides/source/actioncontroller_basics/rescue.txt @@ -2,15 +2,15 @@ Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they're displayed to the user. There are several levels of exception handling available in a Rails application: -=== The default 500 and 404 templates === +=== The Default 500 and 404 Templates === By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the `public` folder, in `404.html` and `500.html` respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can't use RHTML or layouts in them, just plain HTML. === `rescue_from` === -If you want to do something a bit more elaborate when catching errors, you can use link::http://api.rubyonrails.org/classes/ActionController/Rescue/ClassMethods.html#M000620[rescue_from], which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a rescue_from directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object. +If you want to do something a bit more elaborate when catching errors, you can use `rescue_from`, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a +rescue_from+ directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the `:with` option. You can also use a block directly instead of an explicit Proc object. -Let's see how we can use rescue_from to intercept all ActiveRecord::RecordNotFound errors and do something with them. +Here's how you can use +rescue_from+ to intercept all ActiveRecord::RecordNotFound errors and do something with them. [source, ruby] ----------------------------------- @@ -27,7 +27,7 @@ private end ----------------------------------- -Of course, this example is anything but elaborate and doesn't improve the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application: +Of course, this example is anything but elaborate and doesn't improve on the default exception handling at all, but once you can catch all those exceptions you're free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn't have access to a certain section of your application: [source, ruby] ----------------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/session.txt b/railties/doc/guides/source/actioncontroller_basics/session.txt index 467cffbf85..3b69ec82ef 100644 --- a/railties/doc/guides/source/actioncontroller_basics/session.txt +++ b/railties/doc/guides/source/actioncontroller_basics/session.txt @@ -7,9 +7,11 @@ Your application has a session for each user in which you can store small amount * MemCacheStore - Stores the data in MemCache. * ActiveRecordStore - Stores the data in a database using Active Record. -All session stores store the session id in a cookie - there is no other way of passing it to the server. Most stores also use this key to locate the session data on the server. +All session stores store either the session ID or the entire session in a cookie - Rails does not allow the session ID to be passed in any other way. Most stores also use this key to locate the session data on the server. -The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. Expecially discouraged is storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application. +The default and recommended store, the Cookie Store, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it. It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the primary example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The Cookie Store has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application. + +Read more about session storage in the link:../security.html[Security Guide]. If you need a different session storage mechanism, you can change it in the `config/environment.rb` file: @@ -19,9 +21,9 @@ If you need a different session storage mechanism, you can change it in the `con config.action_controller.session_store = :active_record_store ------------------------------------------ -=== Disabling the session === +=== Disabling the Session === -Sometimes you don't need a session, and you can turn it off to avoid the unnecessary overhead. To do this, use the link:http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html#M000649[session] class method in your controller: +Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the `session` class method in your controller: [source, ruby] ------------------------------------------ @@ -41,7 +43,7 @@ class LoginsController < ActionController::Base end ------------------------------------------ -Or even a single action: +Or even for specified actions: [source, ruby] ------------------------------------------ @@ -50,7 +52,7 @@ class ProductsController < ActionController::Base end ------------------------------------------ -=== Accessing the session === +=== Accessing the Session === In your controller you can access the session through the `session` instance method. @@ -65,7 +67,7 @@ class ApplicationController < ActionController::Base private # Finds the User with the ID stored in the session with the key :current_user_id - # This is a common way to do user login in a Rails application; logging in sets the + # This is a common way to handle user login in a Rails application; logging in sets the # session value and logging out removes it. def current_user @_current_user ||= session[:current_user_id] && User.find(session[:current_user_id]) @@ -108,11 +110,11 @@ class LoginsController < ApplicationController end ------------------------------------------ -To reset the entire session, use link:http://api.rubyonrails.org/classes/ActionController/Base.html#M000855[reset_session]. +To reset the entire session, use `reset_session`. === The flash === -The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can set a message which will be displayed to the user on the next request: +The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request: [source, ruby] ------------------------------------------ @@ -163,7 +165,7 @@ class MainController < ApplicationController end ------------------------------------------ -==== flash.now ==== +==== +flash.now+ ==== By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the `create` action fails to save a resource and you render the `new` template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use `flash.now` in the same way you use the normal `flash`: diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt index 41d56935b9..f42480ba25 100644 --- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt +++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt @@ -1,6 +1,6 @@ -== Streaming and file downloads == +== Streaming and File Downloads == -Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000624[send_data] and the link:http://api.rubyonrails.org/classes/ActionController/Streaming.html#M000623[send_file] methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you. +Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the `send_data` and the `send_file` methods, that will both stream data to the client. `send_file` is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you. To stream data to the client, use `send_data`: @@ -31,7 +31,7 @@ end The `download_pdf` action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the `:disposition` option to "inline". The opposite and default value for this option is "attachment". -=== Sending files === +=== Sending Files === If you want to send a file that already exists on disk, use the `send_file` method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file. @@ -50,13 +50,13 @@ end This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the `stream` option or adjust the block size with the `buffer_size` option. -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 as someone could gain access to files they are not meant to have access to. +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. -=== RESTful downloads === +=== RESTful Downloads === -While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Let's try to rewrite the example so that the PDF download is a part of the `show` action: +While `send_data` works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here's how you can rewrite the example so that the PDF download is a part of the `show` action, without any streaming: [source, ruby] ---------------------------- @@ -75,7 +75,7 @@ class ClientsController < ApplicationController end ---------------------------- -In order for this example to work, we have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`: +In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file `config/initializers/mime_types.rb`: [source, ruby] ---------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/verification.txt b/railties/doc/guides/source/actioncontroller_basics/verification.txt index 39046eee85..5d8ee6117e 100644 --- a/railties/doc/guides/source/actioncontroller_basics/verification.txt +++ b/railties/doc/guides/source/actioncontroller_basics/verification.txt @@ -1,8 +1,8 @@ == Verification == -Verifications make sure certain criterias are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criterias are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API codumentation] as "essentially a special kind of before_filter". +Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the `params`, `session` or `flash` hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the link:http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html[API documentation] as "essentially a special kind of before_filter". -Let's see how we can use verification to make sure the user supplies a username and a password in order to log in: +Here's an example of using verification to make sure the user supplies a username and a password in order to log in: [source, ruby] --------------------------------------- @@ -34,7 +34,7 @@ class LoginsController < ApplicationController verify :params => [:username, :password], :render => {:action => "new"}, :add_flash => {:error => "Username and password required to log in"}, - :only => :create #Only run this verification for the "create" action + :only => :create # Only run this verification for the "create" action end --------------------------------------- diff --git a/railties/doc/guides/source/active_record_basics.txt b/railties/doc/guides/source/active_record_basics.txt index 15fc544f25..892adb2d43 100644 --- a/railties/doc/guides/source/active_record_basics.txt +++ b/railties/doc/guides/source/active_record_basics.txt @@ -1,7 +1,7 @@ Active Record Basics ==================== -Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of AcitveRecord. +Active Record is a design pattern that mitigates the mind-numbing mental gymnastics often needed to get your application to communicate with a database. This guide uses a mix of real-world examples, metaphors and detailed explanations of the actual Rails source code to help you make the most of ActiveRecord. After reading this guide readers should have a strong grasp of the Active Record pattern and how it can be used with or without Rails. Hopefully, some of the philosophical and theoretical intentions discussed here will also make them a stronger and better developer. diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt new file mode 100644 index 0000000000..cd698d0c1e --- /dev/null +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -0,0 +1,25 @@ +Active Record Validations and Callbacks +======================================= + +This guide teaches you how to work with the lifecycle of your Active Record objects. More precisely, you will learn how to validate the state of your objects before they go into the database and also how to teach them to perform custom operations at certain points of their lifecycles. + +After reading this guide and trying out the presented concepts, we hope that you'll be able to: + +* Correctly use all the built-in Active Record validation helpers +* Create your own custom validation methods +* Work with the error messages generated by the validation proccess +* Register callback methods that will execute custom operations during your objects lifecycle, for example before/after they are saved. +* Create special classes that encapsulate common behaviour for your callbacks +* Create Observers - classes with callback methods specific for each of your models, keeping the callback code outside your models' declarations. + +== Active Record Validations + + + +== Credits + + + +== Changelog + +http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks diff --git a/railties/doc/guides/source/authors.txt b/railties/doc/guides/source/authors.txt index 8d0970e4f6..94dfc4db08 100644 --- a/railties/doc/guides/source/authors.txt +++ b/railties/doc/guides/source/authors.txt @@ -23,3 +23,17 @@ Cofounder of http://www.eventioz.com[Eventioz]. He has been using Rails since 20 Can be found at gmail, twitter, freenode, everywhere as miloops. *********************************************************** +.Heiko Webers +[[hawe]] +*********************************************************** +Heiko Webers is the founder of http://www.bauland42.de[bauland42], a German web application security consulting and development +company focused on Ruby on Rails. He blogs at http://www.rorsecurity.info. After 10 years of desktop application development, +Heiko has rarely looked back. +*********************************************************** + +.Tore Darell +[[toretore]] +*********************************************************** +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]. +*********************************************************** diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt new file mode 100644 index 0000000000..07b630c59d --- /dev/null +++ b/railties/doc/guides/source/configuring.txt @@ -0,0 +1,225 @@ +Configuring Rails Applications +============================== + +This guide covers the configuration and initialization features available to Rails applications. By referring to this guide, you will be able to: + +* Adjust the behavior of your Rails applications +* Add additional code to be run at application start time + +== Locations for Initialization Code + +preinitializers +environment.rb first +env-specific files +initializers (load_application_initializers) +after-initializer + +== Using a Preinitializer + +== Configuring Rails Components + +=== Configuring Active Record + +=== Configuring Action Controller + +=== Configuring Action View + +=== Configuring Action Mailer + +=== Configuring Active Resource + +=== Configuring Active Support + +== Using Initializers + organization, controlling load order + +== Using an After-Initializer + +== Changelog == + +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] + +* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] + + +actionmailer/lib/action_mailer/base.rb +257: cattr_accessor :logger +267: cattr_accessor :smtp_settings +273: cattr_accessor :sendmail_settings +276: cattr_accessor :raise_delivery_errors +282: cattr_accessor :perform_deliveries +285: cattr_accessor :deliveries +288: cattr_accessor :default_charset +291: cattr_accessor :default_content_type +294: cattr_accessor :default_mime_version +297: cattr_accessor :default_implicit_parts_order +299: cattr_reader :protected_instance_variables + +actionmailer/Rakefile +36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' + +actionpack/lib/action_controller/base.rb +263: cattr_reader :protected_instance_variables +273: cattr_accessor :asset_host +279: cattr_accessor :consider_all_requests_local +285: cattr_accessor :allow_concurrency +317: cattr_accessor :param_parsers +321: cattr_accessor :default_charset +325: cattr_accessor :logger +329: cattr_accessor :resource_action_separator +333: cattr_accessor :resources_path_names +337: cattr_accessor :request_forgery_protection_token +341: cattr_accessor :optimise_named_routes +351: cattr_accessor :use_accept_header +361: cattr_accessor :relative_url_root + +actionpack/lib/action_controller/caching/pages.rb +55: cattr_accessor :page_cache_directory +58: cattr_accessor :page_cache_extension + +actionpack/lib/action_controller/caching.rb +37: cattr_reader :cache_store +48: cattr_accessor :perform_caching + +actionpack/lib/action_controller/dispatcher.rb +98: cattr_accessor :error_file_path + +actionpack/lib/action_controller/mime_type.rb +24: cattr_reader :html_types, :unverifiable_types + +actionpack/lib/action_controller/rescue.rb +36: base.cattr_accessor :rescue_responses +40: base.cattr_accessor :rescue_templates + +actionpack/lib/action_controller/session/active_record_store.rb +60: cattr_accessor :data_column_name +170: cattr_accessor :connection +173: cattr_accessor :table_name +177: cattr_accessor :session_id_column +181: cattr_accessor :data_column +282: cattr_accessor :session_class + +actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +44: cattr_accessor :included_tags, :instance_writer => false + +actionpack/lib/action_view/base.rb +189: cattr_accessor :debug_rjs +193: cattr_accessor :warn_cache_misses + +actionpack/lib/action_view/helpers/active_record_helper.rb +7: cattr_accessor :field_error_proc + +actionpack/lib/action_view/helpers/form_helper.rb +805: cattr_accessor :default_form_builder + +actionpack/lib/action_view/template_handlers/erb.rb +47: cattr_accessor :erb_trim_mode + +actionpack/test/active_record_unit.rb +5: cattr_accessor :able_to_connect +6: cattr_accessor :connected + +actionpack/test/controller/filters_test.rb +286: cattr_accessor :execution_log + +actionpack/test/template/form_options_helper_test.rb +3:TZInfo::Timezone.cattr_reader :loaded_zones + +activemodel/lib/active_model/errors.rb +28: cattr_accessor :default_error_messages + +activemodel/Rakefile +19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' + +activerecord/lib/active_record/attribute_methods.rb +9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false +11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false + +activerecord/lib/active_record/base.rb +394: cattr_accessor :logger, :instance_writer => false +443: cattr_accessor :configurations, :instance_writer => false +450: cattr_accessor :primary_key_prefix_type, :instance_writer => false +456: cattr_accessor :table_name_prefix, :instance_writer => false +461: cattr_accessor :table_name_suffix, :instance_writer => false +467: cattr_accessor :pluralize_table_names, :instance_writer => false +473: cattr_accessor :colorize_logging, :instance_writer => false +478: cattr_accessor :default_timezone, :instance_writer => false +487: cattr_accessor :schema_format , :instance_writer => false +491: cattr_accessor :timestamped_migrations , :instance_writer => false + +activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb +11: cattr_accessor :connection_handler, :instance_writer => false + +activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +166: cattr_accessor :emulate_booleans + +activerecord/lib/active_record/fixtures.rb +498: cattr_accessor :all_loaded_fixtures + +activerecord/lib/active_record/locking/optimistic.rb +38: base.cattr_accessor :lock_optimistically, :instance_writer => false + +activerecord/lib/active_record/migration.rb +259: cattr_accessor :verbose + +activerecord/lib/active_record/schema_dumper.rb +13: cattr_accessor :ignore_tables + +activerecord/lib/active_record/serializers/json_serializer.rb +4: base.cattr_accessor :include_root_in_json, :instance_writer => false + +activerecord/Rakefile +142: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' + +activerecord/test/cases/lifecycle_test.rb +61: cattr_reader :last_inherited + +activerecord/test/cases/mixin_test.rb +9: cattr_accessor :forced_now_time + +activeresource/lib/active_resource/base.rb +206: cattr_accessor :logger + +activeresource/Rakefile +43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' + +activesupport/lib/active_support/buffered_logger.rb +17: cattr_accessor :silencer + +activesupport/lib/active_support/cache.rb +81: cattr_accessor :logger + +activesupport/lib/active_support/core_ext/class/attribute_accessors.rb +5:# cattr_accessor :hair_colors +10: def cattr_reader(*syms) +29: def cattr_writer(*syms) +50: def cattr_accessor(*syms) +51: cattr_reader(*syms) +52: cattr_writer(*syms) + +activesupport/lib/active_support/core_ext/logger.rb +34: cattr_accessor :silencer + +activesupport/test/core_ext/class/attribute_accessor_test.rb +6: cattr_accessor :foo +7: cattr_accessor :bar, :instance_writer => false + +activesupport/test/core_ext/module/synchronization_test.rb +6: @target.cattr_accessor :mutex, :instance_writer => false + +railties/doc/guides/html/creating_plugins.html +786: cattr_accessor :yaffle_text_field,:yaffle_date_field +860: cattr_accessor :yaffle_text_field,:yaffle_date_field + +railties/lib/rails_generator/base.rb +93: cattr_accessor :logger + +railties/Rakefile +265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object' + +railties/test/rails_info_controller_test.rb +12: cattr_accessor :local_request + +Rakefile +32: rdoc.options << '-A cattr_accessor=object' + diff --git a/railties/doc/guides/source/debugging_rails_applications.txt b/railties/doc/guides/source/debugging_rails_applications.txt index 24eb0c0431..b45473fc14 100644 --- a/railties/doc/guides/source/debugging_rails_applications.txt +++ b/railties/doc/guides/source/debugging_rails_applications.txt @@ -31,7 +31,6 @@ The `debug` helper will return a
    -tag that renders the object using the YAM
     
     You'll see something like this:
     
    -[source, log]
     ----------------------------------------------------------------------------
     --- !ruby/object:Post
     attributes:
    @@ -64,7 +63,6 @@ The `to_yaml` method converts the method to YAML format leaving it more readable
     
     As a result of this, you will have something like this in your view:
     
    -[source, log]
     ----------------------------------------------------------------------------
     --- !ruby/object:Post
     attributes:
    @@ -94,13 +92,33 @@ Another useful method for displaying object values is `inspect`, especially when
     
     Will be rendered as follows:
     
    -[source, log]
     ----------------------------------------------------------------------------
     [1, 2, 3, 4, 5]
     
     Title: Rails debugging guide
     ----------------------------------------------------------------------------
     
    +=== Debugging Javascript
    +
    +Rails has built-in support to debug RJS, to active it, set `ActionView::Base.debug_rjs` to _true_, this will specify whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it).
    +
    +To enable it, add the following in the `Rails::Initializer do |config|` block inside +environment.rb+:
    +
    +[source, ruby]
    +----------------------------------------------------------------------------
    +config.action_view[:debug_rjs] = true
    +----------------------------------------------------------------------------
    +
    +Or, at any time, setting `ActionView::Base.debug_rjs` to _true_:
    +
    +[source, ruby]
    +----------------------------------------------------------------------------
    +ActionView::Base.debug_rjs = true
    +----------------------------------------------------------------------------
    +
    +[TIP]
    +For more information on debugging javascript refer to link:http://getfirebug.com/[Firebug], the popular debugger for Firefox.
    +
     == The Logger
     
     It can also be useful to save information to log files at runtime. Rails maintains a separate log file for each runtime environment.
    @@ -183,7 +201,6 @@ end
     
     Here's an example of the log generated by this method:
     
    -[source, log]
     ----------------------------------------------------------------------------
     Processing PostsController#create (for 127.0.0.1 at 2008-09-08 11:52:54) [POST]
       Session ID: BAh7BzoMY3NyZl9pZCIlMDY5MWU1M2I1ZDRjODBlMzkyMWI1OTg2NWQyNzViZjYiCmZsYXNoSUM6J0FjdGl
    @@ -237,7 +254,6 @@ end
     
     If you see the message in the console or logs:
     
    -[source, log]
     ----------------------------------------------------------------------------
     ***** Debugger requested, but was not available: Start server with --debugger to enable *****
     ----------------------------------------------------------------------------
    @@ -271,7 +287,7 @@ For example:
     (rdb:7)
     ----------------------------------------------------------------------------
     
    -Now it's time to play and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
    +Now it's time to explore and dig into your application. A good place to start is by asking the debugger for help... so type: `help` (You didn't see that coming, right?)
     
     ----------------------------------------------------------------------------
     (rdb:7) help
    @@ -610,13 +626,91 @@ You can include any number of these configuration lines inside a `.rdebugrc` fil
     
     Here's a good start for an `.rdebugrc`:
     
    -[source, log]
     ----------------------------------------------------------------------------
     set autolist
     set forcestep
     set listsize 25
     ----------------------------------------------------------------------------
     
    +== Debugging Memory Leaks
    +
    +A Ruby application (on Rails or not), can leak memory - either in the Ruby code or at the C code level.
    +
    +In this section, you will learn how to find and fix such leaks by using Bleak House and Valgrind debugging tools.
    +
    +=== BleakHouse
    +
    +link:http://github.com/fauna/bleak_house/tree/master[BleakHouse] is a library for finding memory leaks.
    +
    +If a Ruby object does not go out of scope, the Ruby Garbage Collector won't sweep it since it is referenced somewhere. Leaks like this can grow slowly and your application will consume more and more memory, gradually affecting the overall system performance. This tool will help you find leaks on the Ruby heap.
    +
    +To install it run:
    +
    +----------------------------------------------------------------------------
    +sudo gem install bleak_house
    +----------------------------------------------------------------------------
    +
    +Then setup you application for profiling. Then add the following at the bottom of config/environment.rb:
    +
    +[source, ruby]
    +----------------------------------------------------------------------------
    +require 'bleak_house' if ENV['BLEAK_HOUSE']
    +----------------------------------------------------------------------------
    +
    +Start a server instance with BleakHouse integration:
    +
    +----------------------------------------------------------------------------
    +RAILS_ENV=production BLEAK_HOUSE=1 ruby-bleak-house ./script/server
    +----------------------------------------------------------------------------
    +
    +Make sure to run a couple hundred requests to get better data samples, then press `CTRL-C`. The server will stop and Bleak House will produce a dumpfile in `/tmp`:
    +
    +----------------------------------------------------------------------------
    +** BleakHouse: working...
    +** BleakHouse: complete
    +** Bleakhouse: run 'bleak /tmp/bleak.5979.0.dump' to analyze.
    +----------------------------------------------------------------------------
    + 
    +To analyze it, just run the listed command. The top 20 leakiest lines will be listed: 
    +
    +----------------------------------------------------------------------------
    +  191691 total objects
    +  Final heap size 191691 filled, 220961 free
    +  Displaying top 20 most common line/class pairs
    +  89513 __null__:__null__:__node__
    +  41438 __null__:__null__:String
    +  2348 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:Array
    +  1508 /opt/local//lib/ruby/gems/1.8/specifications/gettext-1.90.0.gemspec:14:String
    +  1021 /opt/local//lib/ruby/gems/1.8/specifications/heel-0.2.0.gemspec:14:String
    +   951 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:111:String
    +   935 /opt/local//lib/ruby/site_ruby/1.8/rubygems/specification.rb:557:String
    +   834 /opt/local//lib/ruby/site_ruby/1.8/rubygems/version.rb:146:Array
    +  ...
    +----------------------------------------------------------------------------
    +
    +This way you can find where your application is leaking memory and fix it.
    +
    +If link:http://github.com/fauna/bleak_house/tree/master[BleakHouse] doesn't report any heap growth but you still have memory growth, you might have a broken C extension, or real leak in the interpreter. In that case, try using Valgrind to investigate further.
    +
    +=== Valgrind
    +
    +link:http://valgrind.org/[Valgrind] is a Linux-only application for detecting C-based memory leaks and race conditions.
    +
    +There are Valgrind tools that can automatically detect many memory management and threading bugs, and profile your programs in detail. For example, a C extension in the interpreter calls `malloc()` but is doesn't properly call `free()`, this memory won't be available until the app terminates.
    +
    +For further information on how to install Valgrind and use with Ruby, refer to link:http://blog.evanweaver.com/articles/2008/02/05/valgrind-and-ruby/[Valgrind and Ruby] by Evan Weaver.
    +
    +== Plugins for Debugging
    +
    +There are some Rails plugins to help you to find errors and debug your application. Here is a list of useful plugins for debugging:
    +
    +* link:http://github.com/drnic/rails-footnotes/tree/master[Footnotes]: Every Rails page has footnotes that link give request information and link back to your source via TextMate.
    +* link:http://github.com/ntalbott/query_trace/tree/master[Query Trace]: Adds query origin tracing to your logs.
    +* link:http://github.com/dan-manges/query_stats/tree/master[Query Stats]: A Rails plugin to track database queries. 
    +* link:http://code.google.com/p/query-reviewer/[Query Reviewer]: This rails plugin not only runs "EXPLAIN" before each of your select queries in development, but provides a small DIV in the rendered output of each page with the summary of warnings for each query that it analyzed.
    +* link:http://github.com/rails/exception_notification/tree/master[Exception Notifier]: Provides a mailer object and a default set of templates for sending email notifications when errors occur in a Rails application.
    +* link:http://github.com/defunkt/exception_logger/tree/master[Exception Logger]: Logs your Rails exceptions in the database and provides a funky web interface to manage them.
    +
     == References
     
     * link:http://www.datanoise.com/ruby-debug[ruby-debug Homepage]
    @@ -628,10 +722,12 @@ set listsize 25
     * link:http://bashdb.sourceforge.net/ruby-debug.html[Debugging with ruby-debug]
     * link:http://cheat.errtheblog.com/s/rdebug/[ruby-debug cheat sheet]
     * link:http://wiki.rubyonrails.org/rails/pages/HowtoConfigureLogging[Ruby on Rails Wiki: How to Configure Logging]
    +* link:http://blog.evanweaver.com/files/doc/fauna/bleak_house/files/README.html[Bleak House Documentation]
     
     == Changelog ==
     
     http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/5[Lighthouse ticket]
     
    +* November 3, 2008: Accepted for publication. Added RJS, memory leaks and plugins chapters by link:../authors.html#miloops[Emilio Tagua]
     * October 19, 2008: Copy editing pass by link:../authors.html#mgunderloy[Mike Gunderloy]
     * September 16, 2008: initial version by link:../authors.html#miloops[Emilio Tagua]
    diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
    index 945b527e1d..24d078f9e4 100644
    --- a/railties/doc/guides/source/finders.txt
    +++ b/railties/doc/guides/source/finders.txt
    @@ -68,7 +68,6 @@ If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +
     SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2)) 
     -------------------------------------------------------
     
    -[source,txt]
     -------------------------------------------------------
     >> Client.find(1,2)
     => [# "Ryan", locked: false, orders_count: 2, 
    @@ -81,7 +80,6 @@ Note that if you pass in a list of numbers that the result will be returned as a
     
     If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table:
     
    -[source,txt]
     -------------------------------------------------------
     >> Client.first
     => # "Ryan", locked: false, orders_count: 2, 
    @@ -99,7 +97,6 @@ Indicating the query that Rails has performed on your database.
     
     To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table:
     
    -[source,txt]
     -------------------------------------------------------
     >> Client.find(:last)
     => # "Michael", locked: false, orders_count: 3, 
    @@ -113,7 +110,6 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
     
     To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table:
     
    -[source,txt]
     -------------------------------------------------------
     >> Client.all
     => [# "Ryan", locked: false, orders_count: 2, 
    @@ -192,7 +188,6 @@ SELECT * FROM +users+ WHERE (created_at IN
     
     This could possibly cause your database server to raise an unexpected error, for example MySQL will throw back this error:
     
    -[source, txt]
     -------------------------------------------------------
     Got a packet bigger than 'max_allowed_packet' bytes: _query_
     -------------------------------------------------------
    diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt
    index 7b0aeb0ed9..88ca74a557 100644
    --- a/railties/doc/guides/source/form_helpers.txt
    +++ b/railties/doc/guides/source/form_helpers.txt
    @@ -2,7 +2,7 @@ Rails form helpers
     ==================
     Mislav Marohnić 
     
    -Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
    +Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
     
     In this guide we will:
     
    @@ -112,7 +112,7 @@ form_tag({:controller => "people", :action => "search"}, :method => "get")
     
     This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
     
    -WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly `expecting tASSOC` syntax error.
    +WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an `expecting tASSOC` syntax error.
     
     Checkboxes, radio buttons and other controls
     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    @@ -149,7 +149,7 @@ output:
       
     ----------------------------------------------------------------------------
     
    -IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.
    +IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.
     
     Other form controls we might mention are the text area, password input and hidden input:
     
    @@ -174,7 +174,7 @@ How do forms with PUT or DELETE methods work?
     
     Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" and "DELETE" requests (besides "GET" and "POST"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?
     
    -Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the _real_ method:
    +Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the wanted method:
     
     ----------------------------------------------------------------------------
     form_tag(search_path, :method => "put")
    @@ -267,4 +267,79 @@ form_for(@article)
     
     Notice how the short-style `form_for` invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking `record.new_record?`.
     
    -WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.
    \ No newline at end of file
    +WARNING: When you're using STI (single-table inheritance) with your models, you can't rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, `:url` and `:method` explicitly.
    +
    +
    +Making select boxes with ease
    +-----------------------------
    +
    +Select boxes in HTML require a significant amount of markup (one `OPTION` element for each option to choose from), therefore it makes the most sense for them to be dynamically generated from data stored in arrays or hashes.
    +
    +Here is what our wanted markup might look like:
    +
    +----------------------------------------------------------------------------
    +
    +----------------------------------------------------------------------------
    +
    +Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.
    +
    +The select tag and options
    +~~~~~~~~~~~~~~~~~~~~~~~~~~
    +
    +The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options:
    +
    +----------------------------------------------------------------------------
    +<%= select_tag(:city_id, '...') %>
    +----------------------------------------------------------------------------
    +
    +This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.
    +
    +We can generate option tags with the `options_for_select` helper:
    +
    +----------------------------------------------------------------------------
    +<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
    +
    +output:
    +
    +
    +
    +...
    +----------------------------------------------------------------------------
    +
    +For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).
    +
    +Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
    +
    +----------------------------------------------------------------------------
    +<%= select_tag(:city_id, options_for_select(...)) %>
    +----------------------------------------------------------------------------
    +
    +Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The `options_for_select` helper supports this with an optional second argument:
    +
    +----------------------------------------------------------------------------
    +<%= options_for_select(cities_array, 2) %>
    +
    +output:
    +
    +
    +
    +...
    +----------------------------------------------------------------------------
    +
    +So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
    +
    +Select boxes for dealing with models
    +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    +
    +Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute.
    +
    +----------------------------------------------------------------------------
    +...
    +----------------------------------------------------------------------------
    +
    +...
    \ No newline at end of file
    diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt
    index c5bbc9e814..f924d0793a 100644
    --- a/railties/doc/guides/source/getting_started_with_rails.txt
    +++ b/railties/doc/guides/source/getting_started_with_rails.txt
    @@ -751,6 +751,7 @@ At this point, it’s worth looking at some of the tools that Rails provides to
     As you saw earlier, the scaffold-generated views for the +new+ and +edit+ actions are largely identical. You can pull the shared code out into a +partial+ template. This requires editing the new and edit views, and adding a new template:
     
     +new.html.erb+:
    +
     [source, ruby]
     -------------------------------------------------------
     

    New post

    @@ -761,6 +762,7 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action ------------------------------------------------------- +edit.html.erb+: + [source, ruby] -------------------------------------------------------

    Editing post

    @@ -772,6 +774,7 @@ As you saw earlier, the scaffold-generated views for the +new+ and +edit+ action ------------------------------------------------------- +_form.html.erb+: + [source, ruby] ------------------------------------------------------- <% form_for(@post) do |f| %> @@ -979,12 +982,12 @@ $ script/generate controller Comments index show new edit This creates seven files: * +app/controllers/comments_controller.rb+ - The controller -* +app/helpers/comments_helper.rb - A view helper file -* +app/views/comments/index.html.erb - The view for the index action -* +app/views/comments/show.html.erb - The view for the show action -* +app/views/comments/new.html.erb - The view for the new action -* +app/views/comments/edit.html.erb - The view for the edit action -* +test/functional/comments_controller_test.rb - The functional tests for the controller +* +app/helpers/comments_helper.rb+ - A view helper file +* +app/views/comments/index.html.erb+ - The view for the index action +* +app/views/comments/show.html.erb+ - The view for the show action +* +app/views/comments/new.html.erb+ - The view for the new action +* +app/views/comments/edit.html.erb+ - The view for the edit action +* +test/functional/comments_controller_test.rb+ - The functional tests for the controller The controller will be generated with empty methods for each action that you specified in the call to +script/generate controller+: @@ -1216,15 +1219,21 @@ 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 [http://manuals.rubyonrails.org/]Ruby On Rails guides +* The link:http://manuals.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] +Rails also comes with built-in help that you can generate using the rake command-line utility: + +* Running +rake doc:guides+ will put a full copy of the Rails Guides in the +/doc/guides+ folder of your application. Open +/doc/guides/index.html+ in your web browser to explore the Guides. +* Running +rake doc:rails+ will put a full copy of the API documentation for Rails in the +/doc/api+ folder of your application. Open +/doc/api/index.html+ in your web browser to explore the API documentation. + == Changelog == http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/2[Lighthouse ticket] +* November 3, 2008: Formatting patch from Dave Rothlisberger * November 1, 2008: First approved version by link:../authors.html#mgunderloy[Mike Gunderloy] * October 16, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) * October 13, 2008: First complete draft by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) diff --git a/railties/doc/guides/source/index.txt b/railties/doc/guides/source/index.txt index 05d7deee6a..8828e1d313 100644 --- a/railties/doc/guides/source/index.txt +++ b/railties/doc/guides/source/index.txt @@ -42,7 +42,7 @@ This guide covers the find method defined in ActiveRecord::Base, as well as name .link:layouts_and_rendering.html[Layouts and Rendering in Rails] *********************************************************** This guide covers the basic layout features of Action Controller and Action View, -including rendering and redirecting, using +content_for_ blocks, and working +including rendering and redirecting, using +content_for+ blocks, and working with partials. *********************************************************** @@ -65,8 +65,6 @@ understand how to use routing in your own Rails applications, start here. .link:actioncontroller_basics.html[Basics of Action Controller] *********************************************************** -CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/17[Lighthouse Ticket] - This guide covers how controllers work and how they fit into the request cycle in your application. It includes sessions, filters, and cookies, data streaming, and dealing with exceptions raised by a request, among other topics. *********************************************************** @@ -92,14 +90,12 @@ Enjoy. .link:security.html[Securing Rails Applications] *********************************************************** -This manual describes common security problems in web applications and how to +This guide describes common security problems in web applications and how to avoid them with Rails. *********************************************************** .link:debugging_rails_applications.html[Debugging Rails Applications] *********************************************************** -CAUTION: link:http://rails.lighthouseapp.com/projects/16213/tickets/5[Lighthouse Ticket] - This guide describes how to debug Rails applications. It covers the different ways of achieving this and how to understand what is happening "behind the scenes" of your code. diff --git a/railties/doc/guides/source/migrations/rakeing_around.txt b/railties/doc/guides/source/migrations/rakeing_around.txt index 1fcca0cf24..6d8c43d7a3 100644 --- a/railties/doc/guides/source/migrations/rakeing_around.txt +++ b/railties/doc/guides/source/migrations/rakeing_around.txt @@ -25,7 +25,7 @@ This will run the `down` method from the latest migration. If you need to undo s rake db:rollback STEP=3 ------------------ -will run the `down` method fron the last 3 migrations. +will run the `down` method from the last 3 migrations. The `db:migrate:redo` task is a shortcut for doing a rollback and then migrating back up again. As with the `db:rollback` task you can use the `STEP` parameter if you need to go more than one version back, for example diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt index dc7635eff9..31b6fc2cfa 100644 --- a/railties/doc/guides/source/testing_rails_applications.txt +++ b/railties/doc/guides/source/testing_rails_applications.txt @@ -89,7 +89,6 @@ Fixtures can also be described using the all-too-familiar comma-separated value A CSV fixture looks like this: -[source, log] -------------------------------------------------------------- id, username, password, stretchable, comments 1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!"" @@ -184,7 +183,6 @@ 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: -[source, log] ------------------------------------------------------- $ script/generate model Post ... @@ -266,7 +264,6 @@ This will run all the test methods from the test case. You can also run a particular test method from the test case by using the +-n+ switch with the +test method name+. -[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb -n test_truth @@ -292,7 +289,6 @@ 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: -[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -322,7 +318,6 @@ end Running this test shows the friendlier assertion message: -[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -354,7 +349,6 @@ end Now you can see even more output in the console from running the tests: -[source, log] ------------------------------------------------------- $ ruby unit/post_test.rb Loaded suite unit/post_test @@ -519,7 +513,7 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param get(:view, {'id' => '12'}, nil, {'message' => 'booya!'}) -------------------------------------------------- -=== Available Request Types for Functional Tests=== +=== 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: @@ -817,7 +811,6 @@ In this test, +@expected+ is an instance of +TMail::Mail+ that you can use in yo Here's the content of the +invite+ fixture: -[source, log] ------------------------------------------------- Hi friend@example.com, -- cgit v1.2.3 From 0832bc63f4047d0ad0171c411460db23450213aa Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Thu, 6 Nov 2008 01:29:09 +0530 Subject: Make sure ActiveRecord::Base.connected? doesn't raise an exception for defined connections --- .../active_record/connection_adapters/abstract/connection_pool.rb | 3 ++- activerecord/test/cases/pooled_connections_test.rb | 5 +++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 3016c329bd..54a17e20a9 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -324,7 +324,8 @@ module ActiveRecord # Returns true if a connection that's accessible to this class has # already been opened. def connected?(klass) - conn = retrieve_connection_pool(klass) ? conn.connected? : false + conn = retrieve_connection_pool(klass) + conn ? conn.connected? : false end # Remove the connection for this class. This will close the active diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 3e8c617a89..36b45868b9 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -74,6 +74,11 @@ class PooledConnectionsTest < ActiveRecord::TestCase conn_pool.checkin(conn) end + def test_not_connected_defined_connection_reutnrs_false + ActiveRecord::Base.establish_connection(@connection) + assert ! ActiveRecord::Base.connected? + end + def test_undefined_connection_returns_false old_handler = ActiveRecord::Base.connection_handler ActiveRecord::Base.connection_handler = ActiveRecord::ConnectionAdapters::ConnectionHandler.new -- cgit v1.2.3 From 55707da1a14814ad84f138ee98e5b5fb1a745afc Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 6 Nov 2008 09:59:11 +0100 Subject: Dont bother logging the parameters hash if there are no parameters --- actionpack/lib/action_controller/base.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 3a7f6c0f3c..43f6c1be44 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -1241,7 +1241,7 @@ module ActionController #:nodoc: parameters = respond_to?(:filter_parameters) ? filter_parameters(params) : params.dup parameters = parameters.except!(:controller, :action, :format, :_method) - logger.info " Parameters: #{parameters.inspect}" + logger.info " Parameters: #{parameters.inspect}" unless parameters.empty? end def default_render #:nodoc: -- cgit v1.2.3 From 8adb79b9b5983cda8dbdd4ef401661fbd51d8844 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 6 Nov 2008 10:00:15 +0100 Subject: Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 for the MysqlAdapter as they only clutter up the log and offer no value [DHH] --- activerecord/CHANGELOG | 2 ++ .../lib/active_record/connection_adapters/mysql_adapter.rb | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 4ca062b535..154d9f71c4 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *2.2.1 [RC2 or 2.2 final]* +* Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 as they only clutter up the log and offer no value [DHH] + * Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] * Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth] diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 1e452ae88a..edf54026ff 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -305,8 +305,12 @@ module ActiveRecord rows end - def execute(sql, name = nil) #:nodoc: - log(sql, name) { @connection.query(sql) } + def execute(sql, name = nil, skip_logging = false) #:nodoc: + if skip_logging + @connection.query(sql) + else + log(sql, name) { @connection.query(sql) } + end rescue ActiveRecord::StatementInvalid => exception if exception.message.split(":").first =~ /Packets out of order/ raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings." @@ -437,7 +441,7 @@ module ActiveRecord def columns(table_name, name = nil)#:nodoc: sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}" columns = [] - execute(sql, name).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } + execute(sql, name, true).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } columns end @@ -555,7 +559,7 @@ module ActiveRecord # By default, MySQL 'where id is null' selects the last inserted id. # Turn this off. http://dev.rubyonrails.org/ticket/6778 - execute("SET SQL_AUTO_IS_NULL=0") + execute("SET SQL_AUTO_IS_NULL=0", "ID NULL OFF", true) end def select(sql, name = nil) -- cgit v1.2.3 From 077773257b682b7929e77ced3bbf46acf56a10c9 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 6 Nov 2008 10:00:15 +0100 Subject: Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 for the MysqlAdapter as they only clutter up the log and offer no value [DHH] --- activerecord/CHANGELOG | 2 ++ .../lib/active_record/connection_adapters/mysql_adapter.rb | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 4ca062b535..154d9f71c4 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,5 +1,7 @@ *2.2.1 [RC2 or 2.2 final]* +* Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 as they only clutter up the log and offer no value [DHH] + * Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] * Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth] diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 1e452ae88a..edf54026ff 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -305,8 +305,12 @@ module ActiveRecord rows end - def execute(sql, name = nil) #:nodoc: - log(sql, name) { @connection.query(sql) } + def execute(sql, name = nil, skip_logging = false) #:nodoc: + if skip_logging + @connection.query(sql) + else + log(sql, name) { @connection.query(sql) } + end rescue ActiveRecord::StatementInvalid => exception if exception.message.split(":").first =~ /Packets out of order/ raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings." @@ -437,7 +441,7 @@ module ActiveRecord def columns(table_name, name = nil)#:nodoc: sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}" columns = [] - execute(sql, name).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } + execute(sql, name, true).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } columns end @@ -555,7 +559,7 @@ module ActiveRecord # By default, MySQL 'where id is null' selects the last inserted id. # Turn this off. http://dev.rubyonrails.org/ticket/6778 - execute("SET SQL_AUTO_IS_NULL=0") + execute("SET SQL_AUTO_IS_NULL=0", "ID NULL OFF", true) end def select(sql, name = nil) -- cgit v1.2.3 From a358d87e16fa876de29286b69474ab6aaee4a80b Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 6 Nov 2008 13:02:32 +0100 Subject: Fixed the sanitize helper to avoid double escaping already properly escaped entities [#683 state:committed] --- actionpack/CHANGELOG | 2 ++ .../lib/action_controller/vendor/html-scanner/html/sanitizer.rb | 2 +- actionpack/test/controller/html-scanner/sanitizer_test.rb | 4 ++++ activerecord/CHANGELOG | 2 +- 4 files changed, 8 insertions(+), 2 deletions(-) diff --git a/actionpack/CHANGELOG b/actionpack/CHANGELOG index 3ce6522535..e7d5031f1a 100644 --- a/actionpack/CHANGELOG +++ b/actionpack/CHANGELOG @@ -1,5 +1,7 @@ *2.2.1 [RC2 or 2.2 final]* +* Fixed the sanitize helper to avoid double escaping already properly escaped entities #683 [antonmos/Ryan McGeary] + * Fixed that FormTagHelper generated illegal html if name contained square brackets #1238 [Vladimir Dobriakov] * Fix regression bug that made date_select and datetime_select raise a Null Pointer Exception when a nil date/datetime was passed and only month and year were displayed #1289 [Bernardo Padua/Tor Erik] diff --git a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb index 12c8405101..ae20f9947c 100644 --- a/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb +++ b/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb @@ -160,7 +160,7 @@ module HTML if !options[:attributes].include?(attr_name) || contains_bad_protocols?(attr_name, value) node.attributes.delete(attr_name) else - node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(value) + node.attributes[attr_name] = attr_name == 'style' ? sanitize_css(value) : CGI::escapeHTML(CGI::unescapeHTML(value)) end end end diff --git a/actionpack/test/controller/html-scanner/sanitizer_test.rb b/actionpack/test/controller/html-scanner/sanitizer_test.rb index a9e8447e32..bae0f5c9fd 100644 --- a/actionpack/test/controller/html-scanner/sanitizer_test.rb +++ b/actionpack/test/controller/html-scanner/sanitizer_test.rb @@ -253,6 +253,10 @@ class SanitizerTest < Test::Unit::TestCase assert_sanitized "neverending...", "<![CDATA[<span>neverending...]]>" end + def test_should_not_mangle_urls_with_ampersand + assert_sanitized %{my link} + end + protected def assert_sanitized(input, expected = nil) @sanitizer ||= HTML::WhiteListSanitizer.new diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 154d9f71c4..290c0d785c 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,6 +1,6 @@ *2.2.1 [RC2 or 2.2 final]* -* Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 as they only clutter up the log and offer no value [DHH] +* Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 for the MysqlAdapter as they only clutter up the log and offer no value [DHH] * Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] -- cgit v1.2.3 From 732c724df61bc8b780dc42817625b25a321908e4 Mon Sep 17 00:00:00 2001 From: Grant Hollingworth Date: Wed, 5 Nov 2008 22:54:37 -0500 Subject: Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it [#1336 state:committed] Signed-off-by: David Heinemeier Hansson --- actionmailer/CHANGELOG | 5 +++++ actionmailer/lib/action_mailer/base.rb | 6 ++++-- actionmailer/test/abstract_unit.rb | 8 ++++++-- actionmailer/test/mail_service_test.rb | 14 ++++++++++++++ 4 files changed, 29 insertions(+), 4 deletions(-) diff --git a/actionmailer/CHANGELOG b/actionmailer/CHANGELOG index d8636fd83d..4ae7b91327 100644 --- a/actionmailer/CHANGELOG +++ b/actionmailer/CHANGELOG @@ -1,3 +1,8 @@ +*2.2.1 [RC2 or 2.2 final]* + +* Turn on STARTTLS if it is available in Net::SMTP (added in Ruby 1.8.7) and the SMTP server supports it (This is required for Gmail's SMTP server) #1336 [Grant Hollingworth] + + *2.2.0 [RC1] (October 24th, 2008)* * Add layout functionality to mailers [Pratik] diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 043f56ba17..d63a608109 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -663,8 +663,10 @@ module ActionMailer #:nodoc: mail.ready_to_send sender = mail['return-path'] || mail.from - Net::SMTP.start(smtp_settings[:address], smtp_settings[:port], smtp_settings[:domain], - smtp_settings[:user_name], smtp_settings[:password], smtp_settings[:authentication]) do |smtp| + smtp = Net::SMTP.new(smtp_settings[:address], smtp_settings[:port]) + smtp.enable_starttls_auto if smtp.respond_to?(:enable_starttls_auto) + smtp.start(smtp_settings[:domain], smtp_settings[:user_name], smtp_settings[:password], + smtp_settings[:authentication]) do |smtp| smtp.sendmail(mail.encoded, sender, destinations) end end diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index 905f25c9f7..1617b88c8e 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -24,11 +24,15 @@ class MockSMTP def sendmail(mail, from, to) @@deliveries << [mail, from, to] end + + def start(*args) + yield self + end end class Net::SMTP - def self.start(*args) - yield MockSMTP.new + def self.new(*args) + MockSMTP.new end end diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index 7f9540c44b..f5cb372b2a 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -938,6 +938,20 @@ EOF mail = TestMailer.create_body_ivar(@recipient) assert_equal "body: foo\nbar: baz", mail.body end + + def test_starttls_is_enabled_if_supported + MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(true) + MockSMTP.any_instance.expects(:enable_starttls_auto) + ActionMailer::Base.delivery_method = :smtp + TestMailer.deliver_signed_up(@recipient) + end + + def test_starttls_is_disabled_if_not_supported + MockSMTP.any_instance.expects(:respond_to?).with(:enable_starttls_auto).returns(false) + MockSMTP.any_instance.expects(:enable_starttls_auto).never + ActionMailer::Base.delivery_method = :smtp + TestMailer.deliver_signed_up(@recipient) + end end end # uses_mocha -- cgit v1.2.3 From af5b304a4002fe8ebeb8f31cd0a481dfa4a944db Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Thu, 6 Nov 2008 18:52:02 +0000 Subject: Fix stupid typo --- actionpack/lib/action_controller/request.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/request.rb b/actionpack/lib/action_controller/request.rb index a6d4abf029..c079895683 100755 --- a/actionpack/lib/action_controller/request.rb +++ b/actionpack/lib/action_controller/request.rb @@ -13,7 +13,7 @@ module ActionController ActiveSupport::Deprecation.warn( "ActionController::AbstractRequest.relative_url_root= has been renamed." + "You can now set it with config.action_controller.relative_url_root=", caller) - ActionController::base.relative_url_root=relative_url_root + ActionController::Base.relative_url_root=relative_url_root end HTTP_METHODS = %w(get head put post delete options) -- cgit v1.2.3 From 099f10679ec6d9ead9606cac2f843e854787db0c Mon Sep 17 00:00:00 2001 From: Aliaksey Kandratsenka Date: Sat, 1 Nov 2008 13:55:45 +0200 Subject: Don't eval recognize_optimized use __FILE__ and __LINE__ in the optimised recognition code. It produces meaningless line numbers. This also easily produces line numbers greater than recognition_optimization.rb have, which causes rcov to trash memory outside of it's coverage counting arrays. [#1319 state:committed] Signed-off-by: Michael Koziarski --- actionpack/lib/action_controller/routing/recognition_optimisation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/routing/recognition_optimisation.rb b/actionpack/lib/action_controller/routing/recognition_optimisation.rb index 6c47ced6d1..3b98b16683 100644 --- a/actionpack/lib/action_controller/routing/recognition_optimisation.rb +++ b/actionpack/lib/action_controller/routing/recognition_optimisation.rb @@ -148,7 +148,7 @@ module ActionController end nil end - }, __FILE__, __LINE__ + }, '(recognize_optimized)', 1 end def clear_recognize_optimized! -- cgit v1.2.3 From 4ccbc5dffb980edf35be899889f9e227dbd426c7 Mon Sep 17 00:00:00 2001 From: Luca Guidi Date: Mon, 3 Nov 2008 10:07:05 +0100 Subject: Increment the version of our modified memcache_client code to prevent users with the gem installed not seeing our changes. The changes will be submitted upstream. Signed-off-by: Michael Koziarski [#1239 state:committed] --- activesupport/lib/active_support/vendor.rb | 4 +- .../vendor/memcache-client-1.5.0/memcache.rb | 849 --------------------- .../vendor/memcache-client-1.5.1/memcache.rb | 849 +++++++++++++++++++++ activesupport/test/caching_test.rb | 6 + 4 files changed, 857 insertions(+), 851 deletions(-) delete mode 100644 activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb create mode 100644 activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb diff --git a/activesupport/lib/active_support/vendor.rb b/activesupport/lib/active_support/vendor.rb index 633eb2ef08..dc98936525 100644 --- a/activesupport/lib/active_support/vendor.rb +++ b/activesupport/lib/active_support/vendor.rb @@ -14,9 +14,9 @@ rescue Gem::LoadError end begin - gem 'memcache-client', '~> 1.5.0' + gem 'memcache-client', '~> 1.5.1' rescue Gem::LoadError - $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.0" + $:.unshift "#{File.dirname(__FILE__)}/vendor/memcache-client-1.5.1" end begin diff --git a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb b/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb deleted file mode 100644 index 30113201a6..0000000000 --- a/activesupport/lib/active_support/vendor/memcache-client-1.5.0/memcache.rb +++ /dev/null @@ -1,849 +0,0 @@ -# All original code copyright 2005, 2006, 2007 Bob Cottrell, Eric Hodel, -# The Robot Co-op. All rights reserved. -# -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions -# are met: -# -# 1. Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in the -# documentation and/or other materials provided with the distribution. -# 3. Neither the names of the authors nor the names of their contributors -# may be used to endorse or promote products derived from this software -# without specific prior written permission. -# -# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS -# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, -# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT -# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - -require 'socket' -require 'thread' -require 'timeout' -require 'rubygems' - -class String - - ## - # Uses the ITU-T polynomial in the CRC32 algorithm. - - def crc32_ITU_T - n = length - r = 0xFFFFFFFF - - n.times do |i| - r ^= self[i] - 8.times do - if (r & 1) != 0 then - r = (r>>1) ^ 0xEDB88320 - else - r >>= 1 - end - end - end - - r ^ 0xFFFFFFFF - end - -end - -## -# A Ruby client library for memcached. -# -# This is intended to provide access to basic memcached functionality. It -# does not attempt to be complete implementation of the entire API, but it is -# approaching a complete implementation. - -class MemCache - - ## - # The version of MemCache you are using. - - VERSION = '1.5.0' - - ## - # Default options for the cache object. - - DEFAULT_OPTIONS = { - :namespace => nil, - :readonly => false, - :multithread => false, - } - - ## - # Default memcached port. - - DEFAULT_PORT = 11211 - - ## - # Default memcached server weight. - - DEFAULT_WEIGHT = 1 - - ## - # The amount of time to wait for a response from a memcached server. If a - # response is not completed within this time, the connection to the server - # will be closed and an error will be raised. - - attr_accessor :request_timeout - - ## - # The namespace for this instance - - attr_reader :namespace - - ## - # The multithread setting for this instance - - attr_reader :multithread - - ## - # The servers this client talks to. Play at your own peril. - - attr_reader :servers - - ## - # Accepts a list of +servers+ and a list of +opts+. +servers+ may be - # omitted. See +servers=+ for acceptable server list arguments. - # - # Valid options for +opts+ are: - # - # [:namespace] Prepends this value to all keys added or retrieved. - # [:readonly] Raises an exception on cache writes when true. - # [:multithread] Wraps cache access in a Mutex for thread safety. - # - # Other options are ignored. - - def initialize(*args) - servers = [] - opts = {} - - case args.length - when 0 then # NOP - when 1 then - arg = args.shift - case arg - when Hash then opts = arg - when Array then servers = arg - when String then servers = [arg] - else raise ArgumentError, 'first argument must be Array, Hash or String' - end - when 2 then - servers, opts = args - else - raise ArgumentError, "wrong number of arguments (#{args.length} for 2)" - end - - opts = DEFAULT_OPTIONS.merge opts - @namespace = opts[:namespace] - @readonly = opts[:readonly] - @multithread = opts[:multithread] - @mutex = Mutex.new if @multithread - @buckets = [] - self.servers = servers - end - - ## - # Returns a string representation of the cache object. - - def inspect - "" % - [@servers.length, @buckets.length, @namespace, @readonly] - end - - ## - # Returns whether there is at least one active server for the object. - - def active? - not @servers.empty? - end - - ## - # Returns whether or not the cache object was created read only. - - def readonly? - @readonly - end - - ## - # Set the servers that the requests will be distributed between. Entries - # can be either strings of the form "hostname:port" or - # "hostname:port:weight" or MemCache::Server objects. - - def servers=(servers) - # Create the server objects. - @servers = servers.collect do |server| - case server - when String - host, port, weight = server.split ':', 3 - port ||= DEFAULT_PORT - weight ||= DEFAULT_WEIGHT - Server.new self, host, port, weight - when Server - if server.memcache.multithread != @multithread then - raise ArgumentError, "can't mix threaded and non-threaded servers" - end - server - else - raise TypeError, "cannot convert #{server.class} into MemCache::Server" - end - end - - # Create an array of server buckets for weight selection of servers. - @buckets = [] - @servers.each do |server| - server.weight.times { @buckets.push(server) } - end - end - - ## - # Decrements the value for +key+ by +amount+ and returns the new value. - # +key+ must already exist. If +key+ is not an integer, it is assumed to be - # 0. +key+ can not be decremented below 0. - - def decr(key, amount = 1) - server, cache_key = request_setup key - - if @multithread then - threadsafe_cache_decr server, cache_key, amount - else - cache_decr server, cache_key, amount - end - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err - end - - ## - # Retrieves +key+ from memcache. If +raw+ is false, the value will be - # unmarshalled. - - def get(key, raw = false) - server, cache_key = request_setup key - - value = if @multithread then - threadsafe_cache_get server, cache_key - else - cache_get server, cache_key - end - - return nil if value.nil? - - value = Marshal.load value unless raw - - return value - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err - end - - ## - # Retrieves multiple values from memcached in parallel, if possible. - # - # The memcached protocol supports the ability to retrieve multiple - # keys in a single request. Pass in an array of keys to this method - # and it will: - # - # 1. map the key to the appropriate memcached server - # 2. send a single request to each server that has one or more key values - # - # Returns a hash of values. - # - # cache["a"] = 1 - # cache["b"] = 2 - # cache.get_multi "a", "b" # => { "a" => 1, "b" => 2 } - - def get_multi(*keys) - raise MemCacheError, 'No active servers' unless active? - - keys.flatten! - key_count = keys.length - cache_keys = {} - server_keys = Hash.new { |h,k| h[k] = [] } - - # map keys to servers - keys.each do |key| - server, cache_key = request_setup key - cache_keys[cache_key] = key - server_keys[server] << cache_key - end - - results = {} - - server_keys.each do |server, keys_for_server| - keys_for_server = keys_for_server.join ' ' - values = if @multithread then - threadsafe_cache_get_multi server, keys_for_server - else - cache_get_multi server, keys_for_server - end - values.each do |key, value| - results[cache_keys[key]] = Marshal.load value - end - end - - return results - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err - end - - ## - # Increments the value for +key+ by +amount+ and retruns the new value. - # +key+ must already exist. If +key+ is not an integer, it is assumed to be - # 0. - - def incr(key, amount = 1) - server, cache_key = request_setup key - - if @multithread then - threadsafe_cache_incr server, cache_key, amount - else - cache_incr server, cache_key, amount - end - rescue TypeError, SocketError, SystemCallError, IOError => err - handle_error server, err - end - - ## - # Add +key+ to the cache with value +value+ that expires in +expiry+ - # seconds. If +raw+ is true, +value+ will not be Marshalled. - # - # Warning: Readers should not call this method in the event of a cache miss; - # see MemCache#add. - - def set(key, value, expiry = 0, raw = false) - raise MemCacheError, "Update of readonly cache" if @readonly - server, cache_key = request_setup key - socket = server.socket - - value = Marshal.dump value unless raw - command = "set #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" - - begin - @mutex.lock if @multithread - socket.write command - result = socket.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - ensure - @mutex.unlock if @multithread - end - end - - ## - # Add +key+ to the cache with value +value+ that expires in +expiry+ - # seconds, but only if +key+ does not already exist in the cache. - # If +raw+ is true, +value+ will not be Marshalled. - # - # Readers should call this method in the event of a cache miss, not - # MemCache#set or MemCache#[]=. - - def add(key, value, expiry = 0, raw = false) - raise MemCacheError, "Update of readonly cache" if @readonly - server, cache_key = request_setup key - socket = server.socket - - value = Marshal.dump value unless raw - command = "add #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" - - begin - @mutex.lock if @multithread - socket.write command - result = socket.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - ensure - @mutex.unlock if @multithread - end - end - - ## - # Removes +key+ from the cache in +expiry+ seconds. - - def delete(key, expiry = 0) - @mutex.lock if @multithread - - raise MemCacheError, "No active servers" unless active? - cache_key = make_cache_key key - server = get_server_for_key cache_key - - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? - - begin - sock.write "delete #{cache_key} #{expiry}\r\n" - result = sock.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - end - ensure - @mutex.unlock if @multithread - end - - ## - # Flush the cache from all memcache servers. - - def flush_all - raise MemCacheError, 'No active servers' unless active? - raise MemCacheError, "Update of readonly cache" if @readonly - begin - @mutex.lock if @multithread - @servers.each do |server| - begin - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? - sock.write "flush_all\r\n" - result = sock.gets - raise_on_error_response! result - result - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - end - end - ensure - @mutex.unlock if @multithread - end - end - - ## - # Reset the connection to all memcache servers. This should be called if - # there is a problem with a cache lookup that might have left the connection - # in a corrupted state. - - def reset - @servers.each { |server| server.close } - end - - ## - # Returns statistics for each memcached server. An explanation of the - # statistics can be found in the memcached docs: - # - # http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt - # - # Example: - # - # >> pp CACHE.stats - # {"localhost:11211"=> - # {"bytes"=>4718, - # "pid"=>20188, - # "connection_structures"=>4, - # "time"=>1162278121, - # "pointer_size"=>32, - # "limit_maxbytes"=>67108864, - # "cmd_get"=>14532, - # "version"=>"1.2.0", - # "bytes_written"=>432583, - # "cmd_set"=>32, - # "get_misses"=>0, - # "total_connections"=>19, - # "curr_connections"=>3, - # "curr_items"=>4, - # "uptime"=>1557, - # "get_hits"=>14532, - # "total_items"=>32, - # "rusage_system"=>0.313952, - # "rusage_user"=>0.119981, - # "bytes_read"=>190619}} - # => nil - - def stats - raise MemCacheError, "No active servers" unless active? - server_stats = {} - - @servers.each do |server| - sock = server.socket - raise MemCacheError, "No connection to server" if sock.nil? - - value = nil - begin - sock.write "stats\r\n" - stats = {} - while line = sock.gets do - raise_on_error_response! line - break if line == "END\r\n" - if line =~ /\ASTAT ([\w]+) ([\w\.\:]+)/ then - name, value = $1, $2 - stats[name] = case name - when 'version' - value - when 'rusage_user', 'rusage_system' then - seconds, microseconds = value.split(/:/, 2) - microseconds ||= 0 - Float(seconds) + (Float(microseconds) / 1_000_000) - else - if value =~ /\A\d+\Z/ then - value.to_i - else - value - end - end - end - end - server_stats["#{server.host}:#{server.port}"] = stats - rescue SocketError, SystemCallError, IOError => err - server.close - raise MemCacheError, err.message - end - end - - server_stats - end - - ## - # Shortcut to get a value from the cache. - - alias [] get - - ## - # Shortcut to save a value in the cache. This method does not set an - # expiration on the entry. Use set to specify an explicit expiry. - - def []=(key, value) - set key, value - end - - protected - - ## - # Create a key for the cache, incorporating the namespace qualifier if - # requested. - - def make_cache_key(key) - if namespace.nil? then - key - else - "#{@namespace}:#{key}" - end - end - - ## - # Pick a server to handle the request based on a hash of the key. - - def get_server_for_key(key) - raise ArgumentError, "illegal character in key #{key.inspect}" if - key =~ /\s/ - raise ArgumentError, "key too long #{key.inspect}" if key.length > 250 - raise MemCacheError, "No servers available" if @servers.empty? - return @servers.first if @servers.length == 1 - - hkey = hash_for key - - 20.times do |try| - server = @buckets[hkey % @buckets.nitems] - return server if server.alive? - hkey += hash_for "#{try}#{key}" - end - - raise MemCacheError, "No servers available" - end - - ## - # Returns an interoperable hash value for +key+. (I think, docs are - # sketchy for down servers). - - def hash_for(key) - (key.crc32_ITU_T >> 16) & 0x7fff - end - - ## - # Performs a raw decr for +cache_key+ from +server+. Returns nil if not - # found. - - def cache_decr(server, cache_key, amount) - socket = server.socket - socket.write "decr #{cache_key} #{amount}\r\n" - text = socket.gets - raise_on_error_response! text - return nil if text == "NOT_FOUND\r\n" - return text.to_i - end - - ## - # Fetches the raw data for +cache_key+ from +server+. Returns nil on cache - # miss. - - def cache_get(server, cache_key) - socket = server.socket - socket.write "get #{cache_key}\r\n" - keyline = socket.gets # "VALUE \r\n" - - if keyline.nil? then - server.close - raise MemCacheError, "lost connection to #{server.host}:#{server.port}" - end - - raise_on_error_response! keyline - return nil if keyline == "END\r\n" - - unless keyline =~ /(\d+)\r/ then - server.close - raise MemCacheError, "unexpected response #{keyline.inspect}" - end - value = socket.read $1.to_i - socket.read 2 # "\r\n" - socket.gets # "END\r\n" - return value - end - - ## - # Fetches +cache_keys+ from +server+ using a multi-get. - - def cache_get_multi(server, cache_keys) - values = {} - socket = server.socket - socket.write "get #{cache_keys}\r\n" - - while keyline = socket.gets do - return values if keyline == "END\r\n" - raise_on_error_response! keyline - - unless keyline =~ /\AVALUE (.+) (.+) (.+)/ then - server.close - raise MemCacheError, "unexpected response #{keyline.inspect}" - end - - key, data_length = $1, $3 - values[$1] = socket.read data_length.to_i - socket.read(2) # "\r\n" - end - - server.close - raise MemCacheError, "lost connection to #{server.host}:#{server.port}" - end - - ## - # Performs a raw incr for +cache_key+ from +server+. Returns nil if not - # found. - - def cache_incr(server, cache_key, amount) - socket = server.socket - socket.write "incr #{cache_key} #{amount}\r\n" - text = socket.gets - raise_on_error_response! text - return nil if text == "NOT_FOUND\r\n" - return text.to_i - end - - ## - # Handles +error+ from +server+. - - def handle_error(server, error) - server.close if server - new_error = MemCacheError.new error.message - new_error.set_backtrace error.backtrace - raise new_error - end - - ## - # Performs setup for making a request with +key+ from memcached. Returns - # the server to fetch the key from and the complete key to use. - - def request_setup(key) - raise MemCacheError, 'No active servers' unless active? - cache_key = make_cache_key key - server = get_server_for_key cache_key - raise MemCacheError, 'No connection to server' if server.socket.nil? - return server, cache_key - end - - def threadsafe_cache_decr(server, cache_key, amount) # :nodoc: - @mutex.lock - cache_decr server, cache_key, amount - ensure - @mutex.unlock - end - - def threadsafe_cache_get(server, cache_key) # :nodoc: - @mutex.lock - cache_get server, cache_key - ensure - @mutex.unlock - end - - def threadsafe_cache_get_multi(socket, cache_keys) # :nodoc: - @mutex.lock - cache_get_multi socket, cache_keys - ensure - @mutex.unlock - end - - def threadsafe_cache_incr(server, cache_key, amount) # :nodoc: - @mutex.lock - cache_incr server, cache_key, amount - ensure - @mutex.unlock - end - - def raise_on_error_response!(response) - if response =~ /\A(?:CLIENT_|SERVER_)?ERROR (.*)/ - raise MemCacheError, $1.strip - end - end - - - ## - # This class represents a memcached server instance. - - class Server - - ## - # The amount of time to wait to establish a connection with a memcached - # server. If a connection cannot be established within this time limit, - # the server will be marked as down. - - CONNECT_TIMEOUT = 0.25 - - ## - # The amount of time to wait before attempting to re-establish a - # connection with a server that is marked dead. - - RETRY_DELAY = 30.0 - - ## - # The host the memcached server is running on. - - attr_reader :host - - ## - # The port the memcached server is listening on. - - attr_reader :port - - ## - # The weight given to the server. - - attr_reader :weight - - ## - # The time of next retry if the connection is dead. - - attr_reader :retry - - ## - # A text status string describing the state of the server. - - attr_reader :status - - ## - # Create a new MemCache::Server object for the memcached instance - # listening on the given host and port, weighted by the given weight. - - def initialize(memcache, host, port = DEFAULT_PORT, weight = DEFAULT_WEIGHT) - raise ArgumentError, "No host specified" if host.nil? or host.empty? - raise ArgumentError, "No port specified" if port.nil? or port.to_i.zero? - - @memcache = memcache - @host = host - @port = port.to_i - @weight = weight.to_i - - @multithread = @memcache.multithread - @mutex = Mutex.new - - @sock = nil - @retry = nil - @status = 'NOT CONNECTED' - end - - ## - # Return a string representation of the server object. - - def inspect - "" % [@host, @port, @weight, @status] - end - - ## - # Check whether the server connection is alive. This will cause the - # socket to attempt to connect if it isn't already connected and or if - # the server was previously marked as down and the retry time has - # been exceeded. - - def alive? - !!socket - end - - ## - # Try to connect to the memcached server targeted by this object. - # Returns the connected socket object on success or nil on failure. - - def socket - @mutex.lock if @multithread - return @sock if @sock and not @sock.closed? - - @sock = nil - - # If the host was dead, don't retry for a while. - return if @retry and @retry > Time.now - - # Attempt to connect if not already connected. - begin - @sock = timeout CONNECT_TIMEOUT do - TCPSocket.new @host, @port - end - if Socket.constants.include? 'TCP_NODELAY' then - @sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1 - end - @retry = nil - @status = 'CONNECTED' - rescue SocketError, SystemCallError, IOError, Timeout::Error => err - mark_dead err.message - end - - return @sock - ensure - @mutex.unlock if @multithread - end - - ## - # Close the connection to the memcached server targeted by this - # object. The server is not considered dead. - - def close - @mutex.lock if @multithread - @sock.close if @sock && !@sock.closed? - @sock = nil - @retry = nil - @status = "NOT CONNECTED" - ensure - @mutex.unlock if @multithread - end - - private - - ## - # Mark the server as dead and close its socket. - - def mark_dead(reason = "Unknown error") - @sock.close if @sock && !@sock.closed? - @sock = nil - @retry = Time.now + RETRY_DELAY - - @status = sprintf "DEAD: %s, will retry at %s", reason, @retry - end - end - - ## - # Base MemCache exception class. - - class MemCacheError < RuntimeError; end - -end - diff --git a/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb b/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb new file mode 100644 index 0000000000..99c9af0398 --- /dev/null +++ b/activesupport/lib/active_support/vendor/memcache-client-1.5.1/memcache.rb @@ -0,0 +1,849 @@ +# All original code copyright 2005, 2006, 2007 Bob Cottrell, Eric Hodel, +# The Robot Co-op. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# 3. Neither the names of the authors nor the names of their contributors +# may be used to endorse or promote products derived from this software +# without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT +# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR +# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +require 'socket' +require 'thread' +require 'timeout' +require 'rubygems' + +class String + + ## + # Uses the ITU-T polynomial in the CRC32 algorithm. + + def crc32_ITU_T + n = length + r = 0xFFFFFFFF + + n.times do |i| + r ^= self[i] + 8.times do + if (r & 1) != 0 then + r = (r>>1) ^ 0xEDB88320 + else + r >>= 1 + end + end + end + + r ^ 0xFFFFFFFF + end + +end + +## +# A Ruby client library for memcached. +# +# This is intended to provide access to basic memcached functionality. It +# does not attempt to be complete implementation of the entire API, but it is +# approaching a complete implementation. + +class MemCache + + ## + # The version of MemCache you are using. + + VERSION = '1.5.0' + + ## + # Default options for the cache object. + + DEFAULT_OPTIONS = { + :namespace => nil, + :readonly => false, + :multithread => false, + } + + ## + # Default memcached port. + + DEFAULT_PORT = 11211 + + ## + # Default memcached server weight. + + DEFAULT_WEIGHT = 1 + + ## + # The amount of time to wait for a response from a memcached server. If a + # response is not completed within this time, the connection to the server + # will be closed and an error will be raised. + + attr_accessor :request_timeout + + ## + # The namespace for this instance + + attr_reader :namespace + + ## + # The multithread setting for this instance + + attr_reader :multithread + + ## + # The servers this client talks to. Play at your own peril. + + attr_reader :servers + + ## + # Accepts a list of +servers+ and a list of +opts+. +servers+ may be + # omitted. See +servers=+ for acceptable server list arguments. + # + # Valid options for +opts+ are: + # + # [:namespace] Prepends this value to all keys added or retrieved. + # [:readonly] Raises an exception on cache writes when true. + # [:multithread] Wraps cache access in a Mutex for thread safety. + # + # Other options are ignored. + + def initialize(*args) + servers = [] + opts = {} + + case args.length + when 0 then # NOP + when 1 then + arg = args.shift + case arg + when Hash then opts = arg + when Array then servers = arg + when String then servers = [arg] + else raise ArgumentError, 'first argument must be Array, Hash or String' + end + when 2 then + servers, opts = args + else + raise ArgumentError, "wrong number of arguments (#{args.length} for 2)" + end + + opts = DEFAULT_OPTIONS.merge opts + @namespace = opts[:namespace] + @readonly = opts[:readonly] + @multithread = opts[:multithread] + @mutex = Mutex.new if @multithread + @buckets = [] + self.servers = servers + end + + ## + # Returns a string representation of the cache object. + + def inspect + "" % + [@servers.length, @buckets.length, @namespace, @readonly] + end + + ## + # Returns whether there is at least one active server for the object. + + def active? + not @servers.empty? + end + + ## + # Returns whether or not the cache object was created read only. + + def readonly? + @readonly + end + + ## + # Set the servers that the requests will be distributed between. Entries + # can be either strings of the form "hostname:port" or + # "hostname:port:weight" or MemCache::Server objects. + + def servers=(servers) + # Create the server objects. + @servers = servers.collect do |server| + case server + when String + host, port, weight = server.split ':', 3 + port ||= DEFAULT_PORT + weight ||= DEFAULT_WEIGHT + Server.new self, host, port, weight + when Server + if server.memcache.multithread != @multithread then + raise ArgumentError, "can't mix threaded and non-threaded servers" + end + server + else + raise TypeError, "cannot convert #{server.class} into MemCache::Server" + end + end + + # Create an array of server buckets for weight selection of servers. + @buckets = [] + @servers.each do |server| + server.weight.times { @buckets.push(server) } + end + end + + ## + # Decrements the value for +key+ by +amount+ and returns the new value. + # +key+ must already exist. If +key+ is not an integer, it is assumed to be + # 0. +key+ can not be decremented below 0. + + def decr(key, amount = 1) + server, cache_key = request_setup key + + if @multithread then + threadsafe_cache_decr server, cache_key, amount + else + cache_decr server, cache_key, amount + end + rescue TypeError, SocketError, SystemCallError, IOError => err + handle_error server, err + end + + ## + # Retrieves +key+ from memcache. If +raw+ is false, the value will be + # unmarshalled. + + def get(key, raw = false) + server, cache_key = request_setup key + + value = if @multithread then + threadsafe_cache_get server, cache_key + else + cache_get server, cache_key + end + + return nil if value.nil? + + value = Marshal.load value unless raw + + return value + rescue TypeError, SocketError, SystemCallError, IOError => err + handle_error server, err + end + + ## + # Retrieves multiple values from memcached in parallel, if possible. + # + # The memcached protocol supports the ability to retrieve multiple + # keys in a single request. Pass in an array of keys to this method + # and it will: + # + # 1. map the key to the appropriate memcached server + # 2. send a single request to each server that has one or more key values + # + # Returns a hash of values. + # + # cache["a"] = 1 + # cache["b"] = 2 + # cache.get_multi "a", "b" # => { "a" => 1, "b" => 2 } + + def get_multi(*keys) + raise MemCacheError, 'No active servers' unless active? + + keys.flatten! + key_count = keys.length + cache_keys = {} + server_keys = Hash.new { |h,k| h[k] = [] } + + # map keys to servers + keys.each do |key| + server, cache_key = request_setup key + cache_keys[cache_key] = key + server_keys[server] << cache_key + end + + results = {} + + server_keys.each do |server, keys_for_server| + keys_for_server = keys_for_server.join ' ' + values = if @multithread then + threadsafe_cache_get_multi server, keys_for_server + else + cache_get_multi server, keys_for_server + end + values.each do |key, value| + results[cache_keys[key]] = Marshal.load value + end + end + + return results + rescue TypeError, SocketError, SystemCallError, IOError => err + handle_error server, err + end + + ## + # Increments the value for +key+ by +amount+ and retruns the new value. + # +key+ must already exist. If +key+ is not an integer, it is assumed to be + # 0. + + def incr(key, amount = 1) + server, cache_key = request_setup key + + if @multithread then + threadsafe_cache_incr server, cache_key, amount + else + cache_incr server, cache_key, amount + end + rescue TypeError, SocketError, SystemCallError, IOError => err + handle_error server, err + end + + ## + # Add +key+ to the cache with value +value+ that expires in +expiry+ + # seconds. If +raw+ is true, +value+ will not be Marshalled. + # + # Warning: Readers should not call this method in the event of a cache miss; + # see MemCache#add. + + def set(key, value, expiry = 0, raw = false) + raise MemCacheError, "Update of readonly cache" if @readonly + server, cache_key = request_setup key + socket = server.socket + + value = Marshal.dump value unless raw + command = "set #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" + + begin + @mutex.lock if @multithread + socket.write command + result = socket.gets + raise_on_error_response! result + result + rescue SocketError, SystemCallError, IOError => err + server.close + raise MemCacheError, err.message + ensure + @mutex.unlock if @multithread + end + end + + ## + # Add +key+ to the cache with value +value+ that expires in +expiry+ + # seconds, but only if +key+ does not already exist in the cache. + # If +raw+ is true, +value+ will not be Marshalled. + # + # Readers should call this method in the event of a cache miss, not + # MemCache#set or MemCache#[]=. + + def add(key, value, expiry = 0, raw = false) + raise MemCacheError, "Update of readonly cache" if @readonly + server, cache_key = request_setup key + socket = server.socket + + value = Marshal.dump value unless raw + command = "add #{cache_key} 0 #{expiry} #{value.size}\r\n#{value}\r\n" + + begin + @mutex.lock if @multithread + socket.write command + result = socket.gets + raise_on_error_response! result + result + rescue SocketError, SystemCallError, IOError => err + server.close + raise MemCacheError, err.message + ensure + @mutex.unlock if @multithread + end + end + + ## + # Removes +key+ from the cache in +expiry+ seconds. + + def delete(key, expiry = 0) + @mutex.lock if @multithread + + raise MemCacheError, "No active servers" unless active? + cache_key = make_cache_key key + server = get_server_for_key cache_key + + sock = server.socket + raise MemCacheError, "No connection to server" if sock.nil? + + begin + sock.write "delete #{cache_key} #{expiry}\r\n" + result = sock.gets + raise_on_error_response! result + result + rescue SocketError, SystemCallError, IOError => err + server.close + raise MemCacheError, err.message + end + ensure + @mutex.unlock if @multithread + end + + ## + # Flush the cache from all memcache servers. + + def flush_all + raise MemCacheError, 'No active servers' unless active? + raise MemCacheError, "Update of readonly cache" if @readonly + begin + @mutex.lock if @multithread + @servers.each do |server| + begin + sock = server.socket + raise MemCacheError, "No connection to server" if sock.nil? + sock.write "flush_all\r\n" + result = sock.gets + raise_on_error_response! result + result + rescue SocketError, SystemCallError, IOError => err + server.close + raise MemCacheError, err.message + end + end + ensure + @mutex.unlock if @multithread + end + end + + ## + # Reset the connection to all memcache servers. This should be called if + # there is a problem with a cache lookup that might have left the connection + # in a corrupted state. + + def reset + @servers.each { |server| server.close } + end + + ## + # Returns statistics for each memcached server. An explanation of the + # statistics can be found in the memcached docs: + # + # http://code.sixapart.com/svn/memcached/trunk/server/doc/protocol.txt + # + # Example: + # + # >> pp CACHE.stats + # {"localhost:11211"=> + # {"bytes"=>4718, + # "pid"=>20188, + # "connection_structures"=>4, + # "time"=>1162278121, + # "pointer_size"=>32, + # "limit_maxbytes"=>67108864, + # "cmd_get"=>14532, + # "version"=>"1.2.0", + # "bytes_written"=>432583, + # "cmd_set"=>32, + # "get_misses"=>0, + # "total_connections"=>19, + # "curr_connections"=>3, + # "curr_items"=>4, + # "uptime"=>1557, + # "get_hits"=>14532, + # "total_items"=>32, + # "rusage_system"=>0.313952, + # "rusage_user"=>0.119981, + # "bytes_read"=>190619}} + # => nil + + def stats + raise MemCacheError, "No active servers" unless active? + server_stats = {} + + @servers.each do |server| + sock = server.socket + raise MemCacheError, "No connection to server" if sock.nil? + + value = nil + begin + sock.write "stats\r\n" + stats = {} + while line = sock.gets do + raise_on_error_response! line + break if line == "END\r\n" + if line =~ /\ASTAT ([\w]+) ([\w\.\:]+)/ then + name, value = $1, $2 + stats[name] = case name + when 'version' + value + when 'rusage_user', 'rusage_system' then + seconds, microseconds = value.split(/:/, 2) + microseconds ||= 0 + Float(seconds) + (Float(microseconds) / 1_000_000) + else + if value =~ /\A\d+\Z/ then + value.to_i + else + value + end + end + end + end + server_stats["#{server.host}:#{server.port}"] = stats + rescue SocketError, SystemCallError, IOError => err + server.close + raise MemCacheError, err.message + end + end + + server_stats + end + + ## + # Shortcut to get a value from the cache. + + alias [] get + + ## + # Shortcut to save a value in the cache. This method does not set an + # expiration on the entry. Use set to specify an explicit expiry. + + def []=(key, value) + set key, value + end + + protected + + ## + # Create a key for the cache, incorporating the namespace qualifier if + # requested. + + def make_cache_key(key) + if namespace.nil? then + key + else + "#{@namespace}:#{key}" + end + end + + ## + # Pick a server to handle the request based on a hash of the key. + + def get_server_for_key(key) + raise ArgumentError, "illegal character in key #{key.inspect}" if + key =~ /\s/ + raise ArgumentError, "key too long #{key.inspect}" if key.length > 250 + raise MemCacheError, "No servers available" if @servers.empty? + return @servers.first if @servers.length == 1 + + hkey = hash_for key + + 20.times do |try| + server = @buckets[hkey % @buckets.nitems] + return server if server.alive? + hkey += hash_for "#{try}#{key}" + end + + raise MemCacheError, "No servers available" + end + + ## + # Returns an interoperable hash value for +key+. (I think, docs are + # sketchy for down servers). + + def hash_for(key) + (key.crc32_ITU_T >> 16) & 0x7fff + end + + ## + # Performs a raw decr for +cache_key+ from +server+. Returns nil if not + # found. + + def cache_decr(server, cache_key, amount) + socket = server.socket + socket.write "decr #{cache_key} #{amount}\r\n" + text = socket.gets + raise_on_error_response! text + return nil if text == "NOT_FOUND\r\n" + return text.to_i + end + + ## + # Fetches the raw data for +cache_key+ from +server+. Returns nil on cache + # miss. + + def cache_get(server, cache_key) + socket = server.socket + socket.write "get #{cache_key}\r\n" + keyline = socket.gets # "VALUE \r\n" + + if keyline.nil? then + server.close + raise MemCacheError, "lost connection to #{server.host}:#{server.port}" + end + + raise_on_error_response! keyline + return nil if keyline == "END\r\n" + + unless keyline =~ /(\d+)\r/ then + server.close + raise MemCacheError, "unexpected response #{keyline.inspect}" + end + value = socket.read $1.to_i + socket.read 2 # "\r\n" + socket.gets # "END\r\n" + return value + end + + ## + # Fetches +cache_keys+ from +server+ using a multi-get. + + def cache_get_multi(server, cache_keys) + values = {} + socket = server.socket + socket.write "get #{cache_keys}\r\n" + + while keyline = socket.gets do + return values if keyline == "END\r\n" + raise_on_error_response! keyline + + unless keyline =~ /\AVALUE (.+) (.+) (.+)/ then + server.close + raise MemCacheError, "unexpected response #{keyline.inspect}" + end + + key, data_length = $1, $3 + values[$1] = socket.read data_length.to_i + socket.read(2) # "\r\n" + end + + server.close + raise MemCacheError, "lost connection to #{server.host}:#{server.port}" + end + + ## + # Performs a raw incr for +cache_key+ from +server+. Returns nil if not + # found. + + def cache_incr(server, cache_key, amount) + socket = server.socket + socket.write "incr #{cache_key} #{amount}\r\n" + text = socket.gets + raise_on_error_response! text + return nil if text == "NOT_FOUND\r\n" + return text.to_i + end + + ## + # Handles +error+ from +server+. + + def handle_error(server, error) + server.close if server + new_error = MemCacheError.new error.message + new_error.set_backtrace error.backtrace + raise new_error + end + + ## + # Performs setup for making a request with +key+ from memcached. Returns + # the server to fetch the key from and the complete key to use. + + def request_setup(key) + raise MemCacheError, 'No active servers' unless active? + cache_key = make_cache_key key + server = get_server_for_key cache_key + raise MemCacheError, 'No connection to server' if server.socket.nil? + return server, cache_key + end + + def threadsafe_cache_decr(server, cache_key, amount) # :nodoc: + @mutex.lock + cache_decr server, cache_key, amount + ensure + @mutex.unlock + end + + def threadsafe_cache_get(server, cache_key) # :nodoc: + @mutex.lock + cache_get server, cache_key + ensure + @mutex.unlock + end + + def threadsafe_cache_get_multi(socket, cache_keys) # :nodoc: + @mutex.lock + cache_get_multi socket, cache_keys + ensure + @mutex.unlock + end + + def threadsafe_cache_incr(server, cache_key, amount) # :nodoc: + @mutex.lock + cache_incr server, cache_key, amount + ensure + @mutex.unlock + end + + def raise_on_error_response!(response) + if response =~ /\A(?:CLIENT_|SERVER_)?ERROR (.*)/ + raise MemCacheError, $1.strip + end + end + + + ## + # This class represents a memcached server instance. + + class Server + + ## + # The amount of time to wait to establish a connection with a memcached + # server. If a connection cannot be established within this time limit, + # the server will be marked as down. + + CONNECT_TIMEOUT = 0.25 + + ## + # The amount of time to wait before attempting to re-establish a + # connection with a server that is marked dead. + + RETRY_DELAY = 30.0 + + ## + # The host the memcached server is running on. + + attr_reader :host + + ## + # The port the memcached server is listening on. + + attr_reader :port + + ## + # The weight given to the server. + + attr_reader :weight + + ## + # The time of next retry if the connection is dead. + + attr_reader :retry + + ## + # A text status string describing the state of the server. + + attr_reader :status + + ## + # Create a new MemCache::Server object for the memcached instance + # listening on the given host and port, weighted by the given weight. + + def initialize(memcache, host, port = DEFAULT_PORT, weight = DEFAULT_WEIGHT) + raise ArgumentError, "No host specified" if host.nil? or host.empty? + raise ArgumentError, "No port specified" if port.nil? or port.to_i.zero? + + @memcache = memcache + @host = host + @port = port.to_i + @weight = weight.to_i + + @multithread = @memcache.multithread + @mutex = Mutex.new + + @sock = nil + @retry = nil + @status = 'NOT CONNECTED' + end + + ## + # Return a string representation of the server object. + + def inspect + "" % [@host, @port, @weight, @status] + end + + ## + # Check whether the server connection is alive. This will cause the + # socket to attempt to connect if it isn't already connected and or if + # the server was previously marked as down and the retry time has + # been exceeded. + + def alive? + !!socket + end + + ## + # Try to connect to the memcached server targeted by this object. + # Returns the connected socket object on success or nil on failure. + + def socket + @mutex.lock if @multithread + return @sock if @sock and not @sock.closed? + + @sock = nil + + # If the host was dead, don't retry for a while. + return if @retry and @retry > Time.now + + # Attempt to connect if not already connected. + begin + @sock = timeout CONNECT_TIMEOUT do + TCPSocket.new @host, @port + end + if Socket.constants.include? 'TCP_NODELAY' then + @sock.setsockopt Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1 + end + @retry = nil + @status = 'CONNECTED' + rescue SocketError, SystemCallError, IOError, Timeout::Error => err + mark_dead err.message + end + + return @sock + ensure + @mutex.unlock if @multithread + end + + ## + # Close the connection to the memcached server targeted by this + # object. The server is not considered dead. + + def close + @mutex.lock if @multithread + @sock.close if @sock && !@sock.closed? + @sock = nil + @retry = nil + @status = "NOT CONNECTED" + ensure + @mutex.unlock if @multithread + end + + private + + ## + # Mark the server as dead and close its socket. + + def mark_dead(reason = "Unknown error") + @sock.close if @sock && !@sock.closed? + @sock = nil + @retry = Time.now + RETRY_DELAY + + @status = sprintf "DEAD: %s, will retry at %s", reason, @retry + end + end + + ## + # Base MemCache exception class. + + class MemCacheError < RuntimeError; end + +end + diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb index cc371b3a7b..e7dac4cc6b 100644 --- a/activesupport/test/caching_test.rb +++ b/activesupport/test/caching_test.rb @@ -160,6 +160,12 @@ uses_memcached 'memcached backed store' do @cache.read('foo').gsub!(/.*/, 'baz') assert_equal 'bar', @cache.read('foo') end + + def test_write_should_return_true_on_success + result = @cache.write('foo', 'bar') + assert_equal 'bar', @cache.read('foo') # make sure 'foo' was written + assert result + end end class CompressedMemCacheStore < Test::Unit::TestCase -- cgit v1.2.3 From 77697e03353ec06a4b12f42a32d7569797d1eb8f Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Thu, 6 Nov 2008 17:10:16 -0600 Subject: Fix memory leak issue in ActiveRecord scoped_methods --- activerecord/lib/active_record/base.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index a36a137f0d..757102eb6b 100755 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -2023,8 +2023,7 @@ module ActiveRecord #:nodoc: end def scoped_methods #:nodoc: - scoped_methods = (Thread.current[:scoped_methods] ||= {}) - scoped_methods[self] ||= [] + Thread.current[:"#{self}_scoped_methods"] ||= [] end def current_scoped_methods #:nodoc: -- cgit v1.2.3 From b5291ed0f1e956cc98e1bfc8e50ee9fb4f6a661b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 01:01:04 -0500 Subject: Mark utf-8 encoding --- activesupport/lib/active_support/inflector.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index 1ccfec4000..ba52e41c08 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -1,3 +1,4 @@ +# encoding: utf-8 require 'singleton' require 'iconv' -- cgit v1.2.3 From 66d4b558993ab9a92303d905fea6a01800dd0474 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 01:08:21 -0500 Subject: Fix indentation mismatch --- activesupport/test/core_ext/time_ext_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 11ec1c6cd6..fd17f7a812 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -123,7 +123,7 @@ class TimeExtCalculationsTest < Test::Unit::TestCase def test_end_of_year assert_equal Time.local(2007,12,31,23,59,59), Time.local(2007,2,22,10,10,10).end_of_year assert_equal Time.local(2007,12,31,23,59,59), Time.local(2007,12,31,10,10,10).end_of_year - end + end def test_beginning_of_year assert_equal Time.local(2005,1,1,0,0,0), Time.local(2005,2,22,10,10,10).beginning_of_year -- cgit v1.2.3 From 983dc8078708fff5d99fc31eb5eac8b532e950b3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 01:08:59 -0500 Subject: Don't shadow local with black arg --- activesupport/lib/active_support/rescuable.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb index f2bc12e832..c27c4ddb1a 100644 --- a/activesupport/lib/active_support/rescuable.rb +++ b/activesupport/lib/active_support/rescuable.rb @@ -78,7 +78,7 @@ module ActiveSupport def handler_for_rescue(exception) # We go from right to left because pairs are pushed onto rescue_handlers # as rescue_from declarations are found. - _, handler = Array(rescue_handlers).reverse.detect do |klass_name, handler| + _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler| # The purpose of allowing strings in rescue_from is to support the # declaration of handler associations for exception classes whose # definition is yet unknown. @@ -97,11 +97,11 @@ module ActiveSupport exception.is_a?(klass) if klass end - case handler + case rescuer when Symbol - method(handler) + method(rescuer) when Proc - handler.bind(self) + rescuer.bind(self) end end end -- cgit v1.2.3 From 9d4337ea13be371fd3fbf3ca8ba467e810888c37 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Fri, 7 Nov 2008 07:31:01 +0000 Subject: Revert commit which breaks all the tests. This reverts commit 8adb79b9b5983cda8dbdd4ef401661fbd51d8844. Conflicts: activerecord/CHANGELOG --- activerecord/CHANGELOG | 2 -- .../lib/active_record/connection_adapters/mysql_adapter.rb | 12 ++++-------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/activerecord/CHANGELOG b/activerecord/CHANGELOG index 290c0d785c..4ca062b535 100644 --- a/activerecord/CHANGELOG +++ b/activerecord/CHANGELOG @@ -1,7 +1,5 @@ *2.2.1 [RC2 or 2.2 final]* -* Stop logging SHOW FIELDS and SET SQL_AUTO_IS_NULL=0 for the MysqlAdapter as they only clutter up the log and offer no value [DHH] - * Ensure indices don't flip order in schema.rb #1266 [Jordi Bunster] * Fixed that serialized strings should never be type-casted (i.e. turning "Yes" to a boolean) #857 [Andreas Korth] diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index edf54026ff..1e452ae88a 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -305,12 +305,8 @@ module ActiveRecord rows end - def execute(sql, name = nil, skip_logging = false) #:nodoc: - if skip_logging - @connection.query(sql) - else - log(sql, name) { @connection.query(sql) } - end + def execute(sql, name = nil) #:nodoc: + log(sql, name) { @connection.query(sql) } rescue ActiveRecord::StatementInvalid => exception if exception.message.split(":").first =~ /Packets out of order/ raise ActiveRecord::StatementInvalid, "'Packets out of order' error was received from the database. Please update your mysql bindings (gem install mysql) and read http://dev.mysql.com/doc/mysql/en/password-hashing.html for more information. If you're on Windows, use the Instant Rails installer to get the updated mysql bindings." @@ -441,7 +437,7 @@ module ActiveRecord def columns(table_name, name = nil)#:nodoc: sql = "SHOW FIELDS FROM #{quote_table_name(table_name)}" columns = [] - execute(sql, name, true).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } + execute(sql, name).each { |field| columns << MysqlColumn.new(field[0], field[4], field[1], field[2] == "YES") } columns end @@ -559,7 +555,7 @@ module ActiveRecord # By default, MySQL 'where id is null' selects the last inserted id. # Turn this off. http://dev.rubyonrails.org/ticket/6778 - execute("SET SQL_AUTO_IS_NULL=0", "ID NULL OFF", true) + execute("SET SQL_AUTO_IS_NULL=0") end def select(sql, name = nil) -- cgit v1.2.3 From 26978e3ce84eda4e659fe9724e89c51efdd01781 Mon Sep 17 00:00:00 2001 From: Tekin Suleyman Date: Thu, 6 Nov 2008 20:00:54 +0000 Subject: Added :counter_sql as a valid key for habtm associations Signed-off-by: Michael Koziarski --- activerecord/lib/active_record/associations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index c7cb6eb966..7f7819115c 100755 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1609,7 +1609,7 @@ module ActiveRecord :class_name, :table_name, :join_table, :foreign_key, :association_foreign_key, :select, :conditions, :include, :order, :group, :limit, :offset, :uniq, - :finder_sql, :delete_sql, :insert_sql, + :finder_sql, :counter_sql, :delete_sql, :insert_sql, :before_add, :after_add, :before_remove, :after_remove, :extend, :readonly, :validate -- cgit v1.2.3 From 32a5cfcd7f8d14407f0c00ce2cdc82b1b568438e Mon Sep 17 00:00:00 2001 From: Tekin Suleyman Date: Thu, 6 Nov 2008 21:06:40 +0000 Subject: Added tests for HABTM associations with counter_sql Signed-off-by: Michael Koziarski [#1102 state:committed] --- .../has_and_belongs_to_many_associations_test.rb | 23 ++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 2949f1d304..b5bedf3704 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -68,6 +68,16 @@ class DeveloperWithSymbolsForKeys < ActiveRecord::Base :foreign_key => "developer_id" end +class DeveloperWithCounterSQL < ActiveRecord::Base + set_table_name 'developers' + has_and_belongs_to_many :projects, + :class_name => "DeveloperWithCounterSQL", + :join_table => "developers_projects", + :association_foreign_key => "project_id", + :foreign_key => "developer_id", + :counter_sql => 'SELECT COUNT(*) AS count_all FROM projects INNER JOIN developers_projects ON projects.id = developers_projects.project_id WHERE developers_projects.developer_id =#{id}' +end + class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects, :parrots, :pirates, :treasures, :price_estimates, :tags, :taggings @@ -739,6 +749,19 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase assert_nothing_raised { david.projects.count(:all, :conditions => '1=1') } end + def test_count + david = Developer.find(1) + assert_equal 2, david.projects.count + end + + def test_count_with_counter_sql + developer = DeveloperWithCounterSQL.create(:name => 'tekin') + developer.project_ids = [projects(:active_record).id] + developer.save + developer.reload + assert_equal 1, developer.projects.count + end + uses_mocha 'mocking Post.transaction' do def test_association_proxy_transaction_method_starts_transaction_in_association_class Post.expects(:transaction) -- cgit v1.2.3 From d3ec1d3c22904c8801945b56956466f8ead9f3c1 Mon Sep 17 00:00:00 2001 From: Rich Manalang Date: Thu, 6 Nov 2008 20:02:32 -0800 Subject: auto_link view helper was failing on URLs with colons after a query param Signed-off-by: Michael Koziarski [#1341 state:committed] --- actionpack/lib/action_view/helpers/text_helper.rb | 4 ++-- actionpack/test/template/text_helper_test.rb | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb index d80e7c6e57..36f7575652 100644 --- a/actionpack/lib/action_view/helpers/text_helper.rb +++ b/actionpack/lib/action_view/helpers/text_helper.rb @@ -559,7 +559,7 @@ module ActionView (?:\.[-\w]+)* # remaining subdomains or domain (?::\d+)? # port (?:/(?:[~\w\+@%=\(\)-]|(?:[,.;:'][^\s$]))*)* # path - (?:\?[\w\+@%&=.;-]+)? # query string + (?:\?[\w\+@%&=.;:-]+)? # query string (?:\#[\w\-]*)? # trailing anchor ) ([[:punct:]]|<|$|) # trailing text @@ -598,4 +598,4 @@ module ActionView end end end -end \ No newline at end of file +end diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb index 5f9f715819..095c952d67 100644 --- a/actionpack/test/template/text_helper_test.rb +++ b/actionpack/test/template/text_helper_test.rb @@ -221,6 +221,7 @@ class TextHelperTest < ActionView::TestCase http://www.amazon.com/Testing-Equal-Sign-In-Path/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1198861734&sr=8-1 http://en.wikipedia.org/wiki/Sprite_(computer_graphics) http://en.wikipedia.org/wiki/Texas_hold'em + https://www.google.com/doku.php?id=gps:resource:scs:start ) urls.each do |url| -- cgit v1.2.3 From 529c2716992490a6eab55486788ca0d35c17e60b Mon Sep 17 00:00:00 2001 From: Nick Sieger Date: Sat, 8 Nov 2008 03:49:25 +0530 Subject: Simplify dispatcher callbacks to eliminate unnecessary stale thread purging. [Nick Sieger, Pratik Naik] Signed-off-by: Pratik Naik --- actionpack/lib/action_controller/dispatcher.rb | 1 - .../active_record/connection_adapters/abstract/connection_pool.rb | 5 +---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/actionpack/lib/action_controller/dispatcher.rb b/actionpack/lib/action_controller/dispatcher.rb index f3e173004a..2d5e80f0bb 100644 --- a/actionpack/lib/action_controller/dispatcher.rb +++ b/actionpack/lib/action_controller/dispatcher.rb @@ -23,7 +23,6 @@ module ActionController if defined?(ActiveRecord) after_dispatch :checkin_connections - before_dispatch { ActiveRecord::Base.verify_active_connections! } to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers } end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 54a17e20a9..cf760e334e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -292,10 +292,7 @@ module ActiveRecord # and also returns connections to the pool cached by threads that are no # longer alive. def clear_active_connections! - @connection_pools.each_value do |pool| - pool.release_connection - pool.clear_stale_cached_connections! - end + @connection_pools.each_value {|pool| pool.release_connection } end # Clears the cache which maps classes -- cgit v1.2.3 From d20955f889223b6035dbc7d61acba9091bf7b7ed Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 8 Nov 2008 03:56:52 +0530 Subject: Don't leave open dangling connections in development mode. [#1335 state:resolved] --- activerecord/lib/active_record/connection_adapters/abstract_adapter.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index c5183357a1..f8fa969dc3 100755 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -125,9 +125,8 @@ module ActiveRecord end # Returns true if its safe to reload the connection between requests for development mode. - # This is not the case for Ruby/MySQL and it's not necessary for any adapters except SQLite. def requires_reloading? - false + true end # Checks whether the connection to the database is still active (i.e. not stale). -- cgit v1.2.3 From aaa2abf73fa39e0d455b4b781fb4d00e51d0bdc7 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 17:44:31 -0500 Subject: Use delete if the rhs is nil --- actionpack/test/template/asset_tag_helper_test.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/actionpack/test/template/asset_tag_helper_test.rb b/actionpack/test/template/asset_tag_helper_test.rb index bade96fe17..1a3a6e86fa 100644 --- a/actionpack/test/template/asset_tag_helper_test.rb +++ b/actionpack/test/template/asset_tag_helper_test.rb @@ -239,7 +239,11 @@ class AssetTagHelperTest < ActionView::TestCase File.stubs(:exist?).with('template/../fixtures/public/images/rails.png.').returns(true) assert_equal 'Rails', image_tag('rails.png') ensure - ENV["RAILS_ASSET_ID"] = old_asset_id + if old_asset_id + ENV["RAILS_ASSET_ID"] = old_asset_id + else + ENV.delete("RAILS_ASSET_ID") + end end end -- cgit v1.2.3 From 07fe3370f8abe49b4c055d4eb8c39f1e73847eea Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 17:46:03 -0500 Subject: Check whether last arg is a Hash instead of duck-typing against [] --- actionpack/lib/action_view/helpers/atom_feed_helper.rb | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_view/helpers/atom_feed_helper.rb b/actionpack/lib/action_view/helpers/atom_feed_helper.rb index ccb7df212a..cd25684940 100644 --- a/actionpack/lib/action_view/helpers/atom_feed_helper.rb +++ b/actionpack/lib/action_view/helpers/atom_feed_helper.rb @@ -1,3 +1,5 @@ +require 'set' + # Adds easy defaults to writing Atom feeds with the Builder template engine (this does not work on ERb or any other # template languages). module ActionView @@ -121,6 +123,8 @@ module ActionView end class AtomBuilder + XHTML_TAG_NAMES = %w(content rights title subtitle summary).to_set + def initialize(xml) @xml = xml end @@ -140,14 +144,15 @@ module ActionView @xml.__send__(method, *arguments, &block) end end - + # True if the method name matches one of the five elements defined # in the Atom spec as potentially containing XHTML content and # if :type => 'xhtml' is, in fact, specified. def xhtml_block?(method, arguments) - %w( content rights title subtitle summary ).include?(method.to_s) && - arguments.last.respond_to?(:[]) && - arguments.last[:type].to_s == 'xhtml' + if XHTML_TAG_NAMES.include?(method.to_s) + last = arguments.last + last.is_a?(Hash) && last[:type].to_s == 'xhtml' + end end end -- cgit v1.2.3 From 425382d95fbc93efde52c7a1c369f3fbcba70b2e Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 17:45:10 -0500 Subject: Don't worry about attribute ordering --- actionpack/test/template/atom_feed_helper_test.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/actionpack/test/template/atom_feed_helper_test.rb b/actionpack/test/template/atom_feed_helper_test.rb index 9247a42d33..06af8d1d6a 100644 --- a/actionpack/test/template/atom_feed_helper_test.rb +++ b/actionpack/test/template/atom_feed_helper_test.rb @@ -255,7 +255,8 @@ class AtomFeedTest < Test::Unit::TestCase def test_feed_xml_processing_instructions with_restful_routing(:scrolls) do get :index, :id => 'feed_with_xml_processing_instructions' - assert_match %r{<\?xml-stylesheet type="text/css" href="t.css"\?>}, @response.body + assert_match %r{<\?xml-stylesheet [^\?]*type="text/css"}, @response.body + assert_match %r{<\?xml-stylesheet [^\?]*href="t.css"}, @response.body end end -- cgit v1.2.3 From a7f920f674d234f281d2491ebe6d74710a79e663 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Fri, 7 Nov 2008 20:39:06 -0600 Subject: If average value from DB is 0, make sure to convert it to a 0.0 float before calling #to_d on it [#1346 state:resolved] Signed-off-by: Joshua Peek --- activerecord/lib/active_record/calculations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 5e33cf1bd4..dd90580b3d 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -286,7 +286,7 @@ module ActiveRecord case operation when 'count' then value.to_i when 'sum' then type_cast_using_column(value || '0', column) - when 'avg' then value && value.to_d + when 'avg' then value && value.to_f.to_d else type_cast_using_column(value, column) end end -- cgit v1.2.3 From 0be5bc3f5981f11d81c24ccfb97863a69406cf9d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 21:50:39 -0500 Subject: Work around ruby 1.9 segfault --- actionpack/test/controller/session/cookie_store_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/actionpack/test/controller/session/cookie_store_test.rb b/actionpack/test/controller/session/cookie_store_test.rb index 010c00fa14..30422314a1 100644 --- a/actionpack/test/controller/session/cookie_store_test.rb +++ b/actionpack/test/controller/session/cookie_store_test.rb @@ -266,6 +266,7 @@ class CookieStoreTest < Test::Unit::TestCase @options = self.class.default_session_options.merge(options) session = CGI::Session.new(cgi, @options) + ObjectSpace.undefine_finalizer(session) assert_nil cgi.output_hidden, "Output hidden params should be empty: #{cgi.output_hidden.inspect}" assert_nil cgi.output_cookies, "Output cookies should be empty: #{cgi.output_cookies.inspect}" -- cgit v1.2.3 From dd77733f2fdb6dde2be7115fc31ad1dcbfccb5a1 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 8 Nov 2008 00:24:36 -0500 Subject: Timeout the connection pool monitor on ruby 1.8 only --- .../connection_adapters/abstract/connection_pool.rb | 14 +++++++++++--- activerecord/test/cases/pooled_connections_test.rb | 11 +++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index cf760e334e..901b17124c 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -65,15 +65,23 @@ module ActiveRecord # The default ConnectionPool maximum size is 5. def initialize(spec) @spec = spec + # The cache of reserved connections mapped to threads @reserved_connections = {} + # The mutex used to synchronize pool access @connection_mutex = Monitor.new @queue = @connection_mutex.new_cond - # default 5 second timeout - @timeout = spec.config[:wait_timeout] || 5 + + # default 5 second timeout unless on ruby 1.9 + @timeout = + if RUBY_VERSION < '1.9' + spec.config[:wait_timeout] || 5 + end + # default max pool size to 5 @size = (spec.config[:pool] && spec.config[:pool].to_i) || 5 + @connections = [] @checked_out = [] end @@ -187,7 +195,7 @@ module ActiveRecord # try looting dead threads clear_stale_cached_connections! if @size == @checked_out.size - raise ConnectionTimeoutError, "could not obtain a database connection within #{@timeout} seconds. The pool size is currently #{@size}, perhaps you need to increase it?" + raise ConnectionTimeoutError, "could not obtain a database connection#{" within #{@timeout} seconds" if @timeout}. The max pool size is currently #{@size}; consider increasing it." end end end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 36b45868b9..2a5e9509b3 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -28,10 +28,13 @@ class PooledConnectionsTest < ActiveRecord::TestCase end end - def test_pooled_connection_checkout - checkout_connections - assert_equal @connections.length, 2 - assert_equal @timed_out, 2 + # Will deadlock due to lack of Monitor timeouts in 1.9 + if RUBY_VERSION < '1.9' + def test_pooled_connection_checkout + checkout_connections + assert_equal @connections.length, 2 + assert_equal @timed_out, 2 + end end def checkout_checkin_connections(pool_size, threads) -- cgit v1.2.3 From 5cc27f2b0302698ef517755df41f3212587bceb9 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 8 Nov 2008 18:45:19 +0530 Subject: Add some basic controller logging tests --- actionpack/test/controller/logging_test.rb | 46 ++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 actionpack/test/controller/logging_test.rb diff --git a/actionpack/test/controller/logging_test.rb b/actionpack/test/controller/logging_test.rb new file mode 100644 index 0000000000..3c936854dd --- /dev/null +++ b/actionpack/test/controller/logging_test.rb @@ -0,0 +1,46 @@ +require 'abstract_unit' + +class LoggingController < ActionController::Base + def show + render :nothing => true + end +end + +class LoggingTest < ActionController::TestCase + tests LoggingController + + class MockLogger + attr_reader :logged + + def method_missing(method, *args) + @logged ||= [] + @logged << args.first + end + end + + setup :set_logger + + def test_logging_without_parameters + get :show + assert_equal 2, logs.size + assert_nil logs.detect {|l| l =~ /Parameters/ } + end + + def test_logging_with_parameters + get :show, :id => 10 + assert_equal 3, logs.size + + params = logs.detect {|l| l =~ /Parameters/ } + assert_equal 'Parameters: {"id"=>"10"}', params + end + + private + + def set_logger + @controller.logger = MockLogger.new + end + + def logs + @logs ||= @controller.logger.logged.compact.map {|l| l.strip} + end +end -- cgit v1.2.3 From a6d6a1c9aca612232228c1111be810736a26ab63 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 8 Nov 2008 18:58:08 -0500 Subject: Move sshpublisher require into the rake tasks that use it so ruby 1.9 and macruby don't need the rake gem installed --- activesupport/Rakefile | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/activesupport/Rakefile b/activesupport/Rakefile index 1961fb43cf..ccbab525ba 100644 --- a/activesupport/Rakefile +++ b/activesupport/Rakefile @@ -1,7 +1,6 @@ require 'rake/testtask' require 'rake/rdoctask' require 'rake/gempackagetask' -require 'rake/contrib/sshpublisher' require File.join(File.dirname(__FILE__), 'lib', 'active_support', 'version') @@ -65,12 +64,14 @@ end desc "Publish the beta gem" task :pgem => [:package] do + require 'rake/contrib/sshpublisher' Rake::SshFilePublisher.new("gems.rubyonrails.org", "/u/sites/gems/gems", "pkg", "#{PKG_FILE_NAME}.gem").upload `ssh gems.rubyonrails.org '/u/sites/gems/gemupdate.sh'` end desc "Publish the API documentation" task :pdoc => [:rdoc] do + require 'rake/contrib/sshpublisher' Rake::SshDirPublisher.new("wrath.rubyonrails.org", "public_html/as", "doc").upload end -- cgit v1.2.3 From 335a31524055c7dd79618ea79b3c18d827e25d3d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 10 Nov 2008 14:16:43 -0600 Subject: Add simple case when DB calculations returns 0 instead of 0.0 [#1346 state:resolved] --- activerecord/lib/active_record/calculations.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index dd90580b3d..6f4e02b430 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -286,7 +286,7 @@ module ActiveRecord case operation when 'count' then value.to_i when 'sum' then type_cast_using_column(value || '0', column) - when 'avg' then value && value.to_f.to_d + when 'avg' then value && (value == 0 ? 0.0.to_d : value.to_d) else type_cast_using_column(value, column) end end -- cgit v1.2.3 From 5db9f9b3ad47fadf0b3f12ada1c2ea7b9c15ded5 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 10 Nov 2008 17:41:07 -0800 Subject: Pare down object creation during route building --- .../lib/action_controller/routing/builder.rb | 53 ++++++++++------------ .../lib/action_controller/routing/routing_ext.rb | 4 ++ 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/actionpack/lib/action_controller/routing/builder.rb b/actionpack/lib/action_controller/routing/builder.rb index 7b888fa8d2..d4e501e780 100644 --- a/actionpack/lib/action_controller/routing/builder.rb +++ b/actionpack/lib/action_controller/routing/builder.rb @@ -1,23 +1,16 @@ module ActionController module Routing class RouteBuilder #:nodoc: - attr_accessor :separators, :optional_separators + attr_reader :separators, :optional_separators + attr_reader :separator_regexp, :nonseparator_regexp, :interval_regexp def initialize - self.separators = Routing::SEPARATORS - self.optional_separators = %w( / ) - end - - def separator_pattern(inverted = false) - "[#{'^' if inverted}#{Regexp.escape(separators.join)}]" - end - - def interval_regexp - Regexp.new "(.*?)(#{separators.source}|$)" - end + @separators = Routing::SEPARATORS + @optional_separators = %w( / ) - def multiline_regexp?(expression) - expression.options & Regexp::MULTILINE == Regexp::MULTILINE + @separator_regexp = /[#{Regexp.escape(separators.join)}]/ + @nonseparator_regexp = /\A([^#{Regexp.escape(separators.join)}]+)/ + @interval_regexp = /(.*?)(#{separator_regexp}|$)/ end # Accepts a "route path" (a string defining a route), and returns the array @@ -30,7 +23,7 @@ module ActionController rest, segments = path, [] until rest.empty? - segment, rest = segment_for rest + segment, rest = segment_for(rest) segments << segment end segments @@ -39,20 +32,20 @@ module ActionController # A factory method that returns a new segment instance appropriate for the # format of the given string. def segment_for(string) - segment = case string - when /\A:(\w+)/ - key = $1.to_sym - case key - when :controller then ControllerSegment.new(key) - else DynamicSegment.new key - end - when /\A\*(\w+)/ then PathSegment.new($1.to_sym, :optional => true) - when /\A\?(.*?)\?/ - StaticSegment.new($1, :optional => true) - when /\A(#{separator_pattern(:inverted)}+)/ then StaticSegment.new($1) - when Regexp.new(separator_pattern) then - DividerSegment.new($&, :optional => (optional_separators.include? $&)) - end + segment = + case string + when /\A:(\w+)/ + key = $1.to_sym + key == :controller ? ControllerSegment.new(key) : DynamicSegment.new(key) + when /\A\*(\w+)/ + PathSegment.new($1.to_sym, :optional => true) + when /\A\?(.*?)\?/ + StaticSegment.new($1, :optional => true) + when nonseparator_regexp + StaticSegment.new($1) + when separator_regexp + DividerSegment.new($&, :optional => optional_separators.include?($&)) + end [segment, $~.post_match] end @@ -98,7 +91,7 @@ module ActionController if requirement.source =~ %r{\A(\\A|\^)|(\\Z|\\z|\$)\Z} raise ArgumentError, "Regexp anchor characters are not allowed in routing requirements: #{requirement.inspect}" end - if multiline_regexp?(requirement) + if requirement.multiline? raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" end segment.regexp = requirement diff --git a/actionpack/lib/action_controller/routing/routing_ext.rb b/actionpack/lib/action_controller/routing/routing_ext.rb index 5f4ba90d0c..4a82b2af5f 100644 --- a/actionpack/lib/action_controller/routing/routing_ext.rb +++ b/actionpack/lib/action_controller/routing/routing_ext.rb @@ -27,6 +27,10 @@ class Regexp #:nodoc: Regexp.new("|#{source}").match('').captures.length end + def multiline? + options & MULTILINE == MULTILINE + end + class << self def optionalize(pattern) case unoptionalize(pattern) -- cgit v1.2.3 From 278b6cd9529f33286449a9be18f1903687814d3f Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 10 Nov 2008 19:53:53 -0800 Subject: Eliminate excess Regexp creation due to capture counting --- actionpack/lib/action_controller/routing/route.rb | 2 +- .../lib/action_controller/routing/segments.rb | 28 +++++++++++++++++++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_controller/routing/route.rb b/actionpack/lib/action_controller/routing/route.rb index 3b2cb28545..a610ec7e84 100644 --- a/actionpack/lib/action_controller/routing/route.rb +++ b/actionpack/lib/action_controller/routing/route.rb @@ -219,7 +219,7 @@ module ActionController next_capture = 1 extraction = segments.collect do |segment| x = segment.match_extraction(next_capture) - next_capture += Regexp.new(segment.regexp_chunk).number_of_captures + next_capture += segment.number_of_captures x end extraction.compact diff --git a/actionpack/lib/action_controller/routing/segments.rb b/actionpack/lib/action_controller/routing/segments.rb index e5f174ae2c..f6b03edcca 100644 --- a/actionpack/lib/action_controller/routing/segments.rb +++ b/actionpack/lib/action_controller/routing/segments.rb @@ -13,6 +13,10 @@ module ActionController @is_optional = false end + def number_of_captures + Regexp.new(regexp_chunk).number_of_captures + end + def extraction_code nil end @@ -84,6 +88,10 @@ module ActionController optional? ? Regexp.optionalize(chunk) : chunk end + def number_of_captures + 0 + end + def build_pattern(pattern) escaped = Regexp.escape(value) if optional? && ! pattern.empty? @@ -194,10 +202,16 @@ module ActionController end end + def number_of_captures + if regexp + regexp.number_of_captures + 1 + else + 1 + end + end + def build_pattern(pattern) - chunk = regexp_chunk - chunk = "(#{chunk})" if Regexp.new(chunk).number_of_captures == 0 - pattern = "#{chunk}#{pattern}" + pattern = "#{regexp_chunk}#{pattern}" optional? ? Regexp.optionalize(pattern) : pattern end @@ -230,6 +244,10 @@ module ActionController "(?i-:(#{(regexp || Regexp.union(*possible_names)).source}))" end + def number_of_captures + 1 + end + # Don't URI.escape the controller name since it may contain slashes. def interpolation_chunk(value_code = local_name) "\#{#{value_code}.to_s}" @@ -275,6 +293,10 @@ module ActionController regexp || "(.*)" end + def number_of_captures + regexp ? regexp.number_of_captures : 1 + end + def optionality_implied? true end -- cgit v1.2.3 From cbb38bbdba0f7cfb628a0f8716e79d0d079fd7bf Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 10 Nov 2008 21:39:05 -0800 Subject: Only track new constant definitions when we're reloading dependencies --- activesupport/lib/active_support/dependencies.rb | 12 ++++++++++-- activesupport/test/dependencies_test.rb | 10 +++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 3d871eec11..fe568d6127 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -138,14 +138,22 @@ module ActiveSupport #:nodoc: end def load_with_new_constant_marking(file, *extras) #:nodoc: - Dependencies.new_constants_in(Object) { load_without_new_constant_marking(file, *extras) } + if Dependencies.load? + Dependencies.new_constants_in(Object) { load_without_new_constant_marking(file, *extras) } + else + load_without_new_constant_marking(file, *extras) + end rescue Exception => exception # errors from loading file exception.blame_file! file raise end def require(file, *extras) #:nodoc: - Dependencies.new_constants_in(Object) { super } + if Dependencies.load? + Dependencies.new_constants_in(Object) { super } + else + super + end rescue Exception => exception # errors from required file exception.blame_file! file raise diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 6c3bd1a4fd..fe04b91f2b 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -694,17 +694,17 @@ class DependenciesTest < Test::Unit::TestCase with_loading 'autoloading_fixtures' do ActiveSupport::Dependencies.mechanism = :require 2.times do - assert_raise(NameError) {"RaisesNameError".constantize} + assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz } end end end def test_autoload_doesnt_shadow_name_error with_loading 'autoloading_fixtures' do - assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it hasn't been referenced yet!" + Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError) 2.times do begin - ::RaisesNameError.object_id + ::RaisesNameError::FooBarBaz.object_id flunk 'should have raised NameError when autoloaded file referenced FooBarBaz' rescue NameError => e assert_equal 'uninitialized constant RaisesNameError::FooBarBaz', e.message @@ -712,9 +712,9 @@ class DependenciesTest < Test::Unit::TestCase assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!" end - assert !defined?(RaisesNameError) + assert !defined?(::RaisesNameError) 2.times do - assert_raise(NameError) { RaisesNameError } + assert_raise(NameError) { ::RaisesNameError } assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!" end end -- cgit v1.2.3 From 78a18392e15c3de1c70b44e285d1742687624dd1 Mon Sep 17 00:00:00 2001 From: Frederick Cheung Date: Tue, 11 Nov 2008 11:22:13 +0100 Subject: Remove redundant uniq --- activerecord/lib/active_record/association_preload.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/association_preload.rb b/activerecord/lib/active_record/association_preload.rb index 6e194ab9b4..69300e5ce5 100644 --- a/activerecord/lib/active_record/association_preload.rb +++ b/activerecord/lib/active_record/association_preload.rb @@ -312,7 +312,7 @@ module ActiveRecord table_name = klass.quoted_table_name primary_key = klass.primary_key column_type = klass.columns.detect{|c| c.name == primary_key}.type - ids = id_map.keys.uniq.map do |id| + ids = id_map.keys.map do |id| if column_type == :integer id.to_i elsif column_type == :float -- cgit v1.2.3 From a62e9e90d8f47a643c9355f782ab4891fa8fefaa Mon Sep 17 00:00:00 2001 From: Joel Chippindale Date: Tue, 11 Nov 2008 09:39:50 -0600 Subject: Fix for ActionMailer::Base.method_missing so that it raises NoMethodError when no method is found [#1330 state:resolved] Signed-off-by: Joshua Peek --- actionmailer/lib/action_mailer/base.rb | 14 ++++++++------ actionmailer/test/mail_service_test.rb | 8 ++++++++ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index d63a608109..17b5eaa8d1 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -386,12 +386,14 @@ module ActionMailer #:nodoc: end def method_missing(method_symbol, *parameters) #:nodoc: - match = matches_dynamic_method?(method_symbol) - case match[1] - when 'create' then new(match[2], *parameters).mail - when 'deliver' then new(match[2], *parameters).deliver! - when 'new' then nil - else super + if match = matches_dynamic_method?(method_symbol) + case match[1] + when 'create' then new(match[2], *parameters).mail + when 'deliver' then new(match[2], *parameters).deliver! + when 'new' then nil + end + else + super end end diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index f5cb372b2a..8b1c9a8dca 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -1045,4 +1045,12 @@ class RespondToTest < Test::Unit::TestCase def test_should_not_respond_to_deliver_with_template_suffix_if_it_begins_with_a_digit assert !RespondToMailer.respond_to?(:deliver_1_template) end + + def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method + error = assert_raises NoMethodError do + RespondToMailer.not_a_method + end + + assert_match /undefined method.*not_a_method/, error.message + end end -- cgit v1.2.3 From c65075feb6c4ce15582bc08411e6698d782249a7 Mon Sep 17 00:00:00 2001 From: Joel Chippindale Date: Tue, 11 Nov 2008 09:45:53 -0600 Subject: Fixed method_missing for ActionMailer so it no longer matches methods where deliver or create are not a suffix [#1318 state:resolved] Signed-off-by: Joshua Peek --- actionmailer/lib/action_mailer/base.rb | 3 ++- actionmailer/test/mail_service_test.rb | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 17b5eaa8d1..19ce77ea5a 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -391,6 +391,7 @@ module ActionMailer #:nodoc: when 'create' then new(match[2], *parameters).mail when 'deliver' then new(match[2], *parameters).deliver! when 'new' then nil + else super end else super @@ -442,7 +443,7 @@ module ActionMailer #:nodoc: private def matches_dynamic_method?(method_name) #:nodoc: method_name = method_name.to_s - /(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name) + /^(create|deliver)_([_a-z]\w*)/.match(method_name) || /^(new)$/.match(method_name) end end diff --git a/actionmailer/test/mail_service_test.rb b/actionmailer/test/mail_service_test.rb index 8b1c9a8dca..b88beb3314 100644 --- a/actionmailer/test/mail_service_test.rb +++ b/actionmailer/test/mail_service_test.rb @@ -1046,6 +1046,10 @@ class RespondToTest < Test::Unit::TestCase assert !RespondToMailer.respond_to?(:deliver_1_template) end + def test_should_not_respond_to_method_where_deliver_is_not_a_suffix + assert !RespondToMailer.respond_to?(:foo_deliver_template) + end + def test_should_still_raise_exception_with_expected_message_when_calling_an_undefined_method error = assert_raises NoMethodError do RespondToMailer.not_a_method -- cgit v1.2.3 From ccd9ef158953e30e66a4da143314955cd64e71c8 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:21:09 -0500 Subject: Updated preparation section of plugins guide --- railties/doc/guides/html/creating_plugins.html | 92 ++++++++++------------ .../source/creating_plugins/odds_and_ends.txt | 21 ++--- .../guides/source/creating_plugins/preparation.txt | 47 +++++------ 3 files changed, 75 insertions(+), 85 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 48d5f03687..349986c0d3 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -204,7 +204,7 @@ ul#navMain {
  • Create the basic app
  • -
  • Create the plugin
  • +
  • Generate the plugin skeleton
  • Setup the plugin for testing
  • @@ -377,11 +377,12 @@ write custom Rake tasks in your plugin.

    1. Preparation

    1.1. Create the basic app

    -

    In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:

    +

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

    -
    rails plugin_demo
    -cd plugin_demo
    +
    gem install rails
    +rails yaffle_guide
    +cd yaffle_guide
     script/generate scaffold bird name:string
     rake db:migrate
     script/server
    @@ -392,22 +393,24 @@ script/server
    - +
    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. +
    Editor's note:
    The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
    -

    1.2. Create the plugin

    -

    The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also.

    +

    1.2. Generate the plugin skeleton

    +

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

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

    Examples:

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

    Later in the plugin we will create a generator, so go ahead and add the --with-generator option now:

    +

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

    +

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

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

    You should see the following output:

    @@ -430,22 +433,8 @@ 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
    -
    -
    - - - -
    -Note - -
    Editor's note:
    Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be require "yaffle". If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
    -

    1.3. Setup the plugin for testing

    -

    Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.

    +

    In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

    To setup your plugin to allow for easy testing you'll need to add 3 files:

    • @@ -464,7 +453,6 @@ A test helper that sets up the database before your tests.

    -

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

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

    @@ -490,7 +478,8 @@ mysql: :password: :database: yaffle_plugin_test
    -

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

    +

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

    +

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

    t.datetime :last_tweeted_at end end - -# File: vendor/plugins/yaffle/test/test_helper.rb - -ENV['RAILS_ENV'] = 'test' +
    +

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

    +
    +
    +
    ENV['RAILS_ENV'] = 'test'
     ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
     
     require 'test/unit'
    @@ -522,7 +515,6 @@ ActiveRecord::Base= ENV['DB']
     
    -# no db passed, try one of these fine config-free DBs before bombing.
     db_adapter ||=
       begin
         require 'rubygems'
    @@ -547,11 +539,9 @@ ActiveRecord::Baserequire 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
     
    @@ -1219,32 +1209,34 @@ ActionController::Routing

    8.1. Work with init.rb

    The plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    -

    If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:

    -

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

    +

    If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in init.rb, and it makes the plugin more difficult to turn into a gem.

    +

    A better alternative is to reopen the class in a different file, and require that file from init.rb.

    +

    If you must reopen a class in init.rb, there are various techniques. One way is to use module_eval or class_eval:

    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -class ::Hash
    +
    Hash.class_eval do
       def is_a_special_hash?
         true
       end
     end
     
    -

    OR you can use module_eval or class_eval:

    +

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

    +

    vendor/plugins/yaffle/init.rb

    -
    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -Hash.class_eval do
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    +
    +
    class ::Hash
    +  def is_a_special_hash?
    +    true
    +  end
    +end
    +

    8.2. Generate RDoc Documentation

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

    diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index eb127f73ca..32da7ed7f3 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -4,27 +4,30 @@ The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: +If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem. -The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: +A better alternative is to reopen the class in a different file, and require that file from `init.rb`. + +If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`: + +*vendor/plugins/yaffle/init.rb* [source, ruby] --------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -class ::Hash +Hash.class_eval do def is_a_special_hash? true end end --------------------------------------------------- -OR you can use `module_eval` or `class_eval`: +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: ---------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb +*vendor/plugins/yaffle/init.rb* -Hash.class_eval do +[source, ruby] +--------------------------------------------------- +class ::Hash def is_a_special_hash? true end diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt index 77e3a3561f..83717c7ac8 100644 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ b/railties/doc/guides/source/creating_plugins/preparation.txt @@ -2,11 +2,12 @@ === Create the basic app === -In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: +The examples in this guide require that you have a working rails application. To create a simple rails app execute: ------------------------------------------------ -rails plugin_demo -cd plugin_demo +gem install rails +rails yaffle_guide +cd yaffle_guide script/generate scaffold bird name:string rake db:migrate script/server @@ -14,25 +15,28 @@ script/server Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. +.Editor's note: NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. -=== Create the plugin === +=== Generate the plugin skeleton === -The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. Examples: ---------------------------------------------- -./script/generate plugin BrowserFilters -./script/generate plugin BrowserFilters --with-generator +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator ---------------------------------------------- -Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now: +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: ---------------------------------------------- -script/generate plugin yaffle --with-generator +./script/generate plugin yaffle --with-generator ---------------------------------------------- You should see the following output: @@ -57,19 +61,10 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE ---------------------------------------------- -For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that. - ----------------------------------------------- -rm vendor/plugins/yaffle/lib/yaffle.rb ----------------------------------------------- - -.Editor's note: -NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean - === Setup the plugin for testing === -Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. +In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. To setup your plugin to allow for easy testing you'll need to add 3 files: @@ -77,8 +72,6 @@ To setup your plugin to allow for easy testing you'll need to add 3 files: * A 'schema.rb' file with your table definitions. * A test helper that sets up the database before your tests. -For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: - *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- @@ -105,7 +98,9 @@ mysql: :database: yaffle_plugin_test ---------------------------------------------- -*vendor/plugins/yaffle/test/test_helper.rb:* +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* [source, ruby] ---------------------------------------------- @@ -121,9 +116,12 @@ ActiveRecord::Schema.define(:version => 0) do t.datetime :last_tweeted_at end end +---------------------------------------------- -# File: vendor/plugins/yaffle/test/test_helper.rb +*vendor/plugins/yaffle/test/test_helper.rb:* +[source, ruby] +---------------------------------------------- ENV['RAILS_ENV'] = 'test' ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' @@ -135,7 +133,6 @@ ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") db_adapter = ENV['DB'] -# no db passed, try one of these fine config-free DBs before bombing. db_adapter ||= begin require 'rubygems' @@ -160,10 +157,8 @@ load(File.dirname(__FILE__) + "/schema.rb") require File.dirname(__FILE__) + '/../init.rb' class Hickwall < ActiveRecord::Base - acts_as_yaffle end class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at end ---------------------------------------------- -- cgit v1.2.3 From 6b143ab86f88cf9e0572352c9afec4936995b4a4 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:33:53 -0500 Subject: Plugins Guide: added example of how to run tests, including how to run with multiple databases --- railties/doc/guides/html/creating_plugins.html | 54 ++++++++++++++++++++ .../guides/source/creating_plugins/preparation.txt | 58 ++++++++++++++++++++++ 2 files changed, 112 insertions(+) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 349986c0d3..4c5f72c4d2 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -208,6 +208,8 @@ ul#navMain {
  • Setup the plugin for testing
  • +
  • Run the plugin tests
  • +
  • @@ -544,6 +546,58 @@ ActiveRecord::Baseclass Wickwall < ActiveRecord::Base end +

    1.4. Run the plugin tests

    +

    Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:

    +

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

    +
    +
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +
    +class YaffleTest < Test::Unit::TestCase
    +
    +  def test_active_record_classes_from_test_helper
    +    assert_kind_of Hickwall, Hickwall.new
    +    assert_kind_of Wickwall, Wickwall.new
    +  end
    +
    +end
    +
    +

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

    +
    +
    +
    cd vendor/plugins/yaffle
    +rake
    +
    +

    You should see output like:

    +
    +
    +
    /opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb"
    +-- create_table(:hickwalls, {:force=>true})
    +   -> 0.0220s
    +-- create_table(:wickwalls, {:force=>true})
    +   -> 0.0077s
    +-- initialize_schema_migrations_table()
    +   -> 0.0007s
    +-- assume_migrated_upto_version(0)
    +   -> 0.0007s
    +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader
    +Started
    +.
    +Finished in 0.002236 seconds.
    +
    +1 test, 1 assertion, 0 failures, 0 errors
    +
    +

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

    +
    +
    +
    rake DB=sqlite
    +rake DB=sqlite3
    +rake DB=mysql
    +rake DB=postgresql
    +

    2. Add a to_squawk method to String

    diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt index 83717c7ac8..dc9ef6bc29 100644 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ b/railties/doc/guides/source/creating_plugins/preparation.txt @@ -162,3 +162,61 @@ end class Wickwall < ActiveRecord::Base end ---------------------------------------------- + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + + def test_active_record_classes_from_test_helper + assert_kind_of Hickwall, Hickwall.new + assert_kind_of Wickwall, Wickwall.new + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3 From 7f24653e7a39da9eb85b282e929d0712b2f1c9b7 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 01:48:02 -0500 Subject: Plugins guide: Cleanup the intro --- railties/doc/guides/html/creating_plugins.html | 112 +++++++++------------ .../doc/guides/source/creating_plugins/index.txt | 88 +++++----------- 2 files changed, 74 insertions(+), 126 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 4c5f72c4d2..32bcab1359 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -267,113 +267,96 @@ ul#navMain {

    The Basics of Creating Rails Plugins

    -

    Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.

    -

    In this tutorial you will learn how to create a plugin that includes:

    +

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

    • -Core Extensions - extending String with a to_squawk method: +a way for developers to share bleeding-edge ideas without hurting the stable code base

      -
      -
      -
      # Anywhere
      -"hello!".to_squawk # => "squawk! hello!"
      -
    • -An acts_as_yaffle method for ActiveRecord models that adds a squawk method: +a segmented architecture so that units of code can be fixed or updated on their own release schedule

      -
      -
      -
      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: +an outlet for the core developers so that they don’t have to include every cool new feature under the sun

      -
      -
      -
      squawk_info_for(@hickwall)
      -
    • +
    +

    After reading this guide you should be familiar with:

    +
    • -A generator that creates a migration to add squawk columns to a model: +Creating a plugin from scratch

      -
      -
      -
      script/generate yaffle hickwall
      -
    • -A custom generator command: +Writing and running tests for the plugin

      -
      -
      -
      class YaffleGenerator < Rails::Generator::NamedBase
      -  def manifest
      -    m.yaffle_definition
      -  end
      -end
      -
    • -A custom route method: +Storing models, views, controllers, helpers and even other plugins in your plugins +

      +
    • +
    • +

      +Writing generators +

      +
    • +
    • +

      +Writing custom Rake tasks in your plugin +

      +
    • +
    • +

      +Generating RDoc documentation for your plugin +

      +
    • +
    • +

      +Avoiding common pitfalls with init.rb

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

    In addition you'll learn how to:

    +

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

    • -test your plugins. +Extend core ruby classes like Hash and String +

      +
    • +
    • +

      +Add methods to ActiveRecord::Base in the tradition of the acts_as plugins +

      +
    • +
    • +

      +Add a view helper that can be used in erb templates

    • -work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins. +Add a new generator that will generate a migration

    • -create documentation for your plugin. +Add a custom generator command

    • -write custom Rake tasks in your plugin. +A custom route method that can be used in routes.rb

    +

    For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.

    1. Preparation

    @@ -590,7 +573,7 @@ Finished in 0.002236 seconds. 1 test, 1 assertion, 0 failures, 0 errors
    -

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

    +

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

    rake DB=sqlite
    @@ -598,6 +581,7 @@ rake DB=sqlite3
     rake DB=mysql
     rake DB=postgresql
    +

    Now you are ready to test-drive your plugin!

    2. Add a to_squawk method to String

    diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index f2ed6ed8bb..d3042f8d56 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -1,68 +1,32 @@ The Basics of Creating Rails Plugins ==================================== -Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. - -In this tutorial you will learn how to create a plugin that includes: - - * Core Extensions - extending String with a `to_squawk` method: -+ -[source, ruby] -------------------------------------------- -# Anywhere -"hello!".to_squawk # => "squawk! hello!" -------------------------------------------- - -* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method: -+ -[source, ruby] -------------------------------------------- -class Hickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_sang_at -end - -Hickwall.new.squawk("Hello World") -------------------------------------------- - -* A view helper that will print out squawking info: -+ -[source, ruby] -------------------------------------------- -squawk_info_for(@hickwall) -------------------------------------------- - -* A generator that creates a migration to add squawk columns to a model: -+ -------------------------------------------- -script/generate yaffle hickwall -------------------------------------------- - -* A custom generator command: -+ -[source, ruby] -------------------------------------------- -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end -------------------------------------------- - -* A custom route method: -+ -[source, ruby] -------------------------------------------- -ActionController::Routing::Routes.draw do |map| - map.yaffles -end -------------------------------------------- - -In addition you'll learn how to: - - * test your plugins. - * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins. - * create documentation for your plugin. - * write custom Rake tasks in your plugin. +A Rails plugin is either an extension or a modification of the core framework. Plugins provide: + + * a way for developers to share bleeding-edge ideas without hurting the stable code base + * a segmented architecture so that units of code can be fixed or updated on their own release schedule + * an outlet for the core developers so that they don’t have to include every cool new feature under the sun + +After reading this guide you should be familiar with: + + * Creating a plugin from scratch + * Writing and running tests for the plugin + * Storing models, views, controllers, helpers and even other plugins in your plugins + * Writing generators + * Writing custom Rake tasks in your plugin + * Generating RDoc documentation for your plugin + * Avoiding common pitfalls with 'init.rb' + +This guide describes how to build a test-driven plugin that will: + + * Extend core ruby classes like Hash and String + * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins + * Add a view helper that can be used in erb templates + * Add a new generator that will generate a migration + * Add a custom generator command + * A custom route method that can be used in routes.rb + +For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. include::preparation.txt[] -- cgit v1.2.3 From 40bc386ed8cc403050292ab19428f1e467fa1737 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Wed, 12 Nov 2008 02:05:19 -0500 Subject: Plugin Guide: cleaned up file paths, made formatting more consistent --- railties/doc/guides/html/creating_plugins.html | 142 +++++++++------------ .../source/creating_plugins/acts_as_yaffle.txt | 29 +++-- .../source/creating_plugins/custom_generator.txt | 14 +- .../source/creating_plugins/custom_route.txt | 16 +-- .../creating_plugins/migration_generator.txt | 20 ++- .../source/creating_plugins/odds_and_ends.txt | 4 +- .../source/creating_plugins/string_to_squawk.txt | 21 ++- .../guides/source/creating_plugins/view_helper.txt | 12 +- 8 files changed, 125 insertions(+), 133 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 32bcab1359..97e14965a5 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -605,14 +605,13 @@ Require that file from your init.rb.

    Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is lib/core_ext.rb.

    First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:

    +

    vendor/plugins/yaffle/test/core_ext_test.rb

    -
    # File: vendor/plugins/yaffle/test/core_ext_test.rb
    -
    -require 'test/unit'
    +
    require 'test/unit'
     
     class CoreExtTest < Test::Unit::TestCase
       # Replace this with your real tests.
    @@ -622,15 +621,13 @@ http://www.gnu.org/software/src-highlite -->
     end
     

    Start off by removing the default test, and adding a require statement for your test helper.

    +

    vendor/plugins/yaffle/test/core_ext_test.rb

    -
    # File: vendor/plugins/yaffle/test/core_ext_test.rb
    -
    -require 'test/unit'
    -require File.dirname(__FILE__) + '/test_helper.rb'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class CoreExtTest < Test::Unit::TestCase
     end
    @@ -648,14 +645,13 @@ rake test
    No tests were specified

    Great - now you are ready to start development. The first thing we'll do is to add a method to String called to_squawk which will prefix the string with the word “squawk!”. The test will look something like this:

    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -class CoreExtTest < Test::Unit::TestCase
    +
    class CoreExtTest < Test::Unit::TestCase
       def test_string_should_respond_to_squawk
         assert_equal true, "".respond_to?(:to_squawk)
       end
    @@ -669,23 +665,21 @@ http://www.gnu.org/software/src-highlite -->
       end
     end
     
    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -require "core_ext"
    +
    require "core_ext"
     
    +

    vendor/plugins/yaffle/lib/core_ext.rb

    -
    # File: vendor/plugins/yaffle/lib/core_ext.rb
    -
    -String.class_eval do
    +
    String.class_eval do
       def to_squawk
         "squawk! #{self}".strip
       end
    @@ -705,14 +699,13 @@ String.class_eval 
     

    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.

    +

    vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

    -
    # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
    -require File.dirname(__FILE__) + '/test_helper.rb'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class Hickwall < ActiveRecord::Base
       acts_as_yaffle
    @@ -721,17 +714,17 @@ http://www.gnu.org/software/src-highlite -->
     class ActsAsYaffleTest < Test::Unit::TestCase
     end
     
    +

    vendor/plugins/lib/acts_as_yaffle.rb

    -
    # File: vendor/plugins/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    module Yaffle
     end
     

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

    +

    vendor/plugins/lib/acts_as_yaffle.rb

    end

    Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:

    +

    vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

    -
    # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
    -require File.dirname(__FILE__) + '/test_helper.rb'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class ActsAsYaffleTest < Test::Unit::TestCase
       def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
    @@ -797,14 +789,13 @@ http://www.gnu.org/software/src-highlite -->
     end
     

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

    +

    vendor/plugins/yaffle/lib/acts_as_yaffle.rb

    -
    # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    module Yaffle
       def self.included(base)
         base.send :extend, ClassMethods
       end
    @@ -823,14 +814,13 @@ http://www.gnu.org/software/src-highlite -->
     end
     

    Now you can add tests for the instance methods, and the instance method itself:

    +

    vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

    -
    # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
    -require File.dirname(__FILE__) + '/test_helper.rb'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class ActsAsYaffleTest < Test::Unit::TestCase
     
    @@ -871,14 +861,13 @@ http://www.gnu.org/software/src-highlite -->
       end
     end
     
    +

    vendor/plugins/yaffle/lib/acts_as_yaffle.rb

    -
    # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    module Yaffle
       def self.included(base)
         base.send :extend, ClassMethods
       end
    @@ -900,7 +889,15 @@ http://www.gnu.org/software/src-highlite -->
       end
     end
     
    -

    Note the use of write_attribute to write to the field in model.

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

    4. Create a squawk_info_for view helper

    @@ -923,14 +920,13 @@ Write the tests.
  • First, create the test to define the functionality you want:

    +

    vendor/plugins/yaffle/test/view_helpers_test.rb

    -
    # File: vendor/plugins/yaffle/test/view_helpers_test.rb
    -
    -require File.dirname(__FILE__) + '/test_helper.rb'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     include YaffleViewHelper
     
     class ViewHelpersTest < Test::Unit::TestCase
    @@ -944,25 +940,23 @@ http://www.gnu.org/software/src-highlite -->
     end
     

    Then add the following statements to init.rb:

    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -require "view_helpers"
    +
    require "view_helpers"
     ActionView::Base.send :include, YaffleViewHelper
     

    Then add the view helpers file and

    +

    vendor/plugins/yaffle/lib/view_helpers.rb

    -
    # File: vendor/plugins/yaffle/lib/view_helpers.rb
    -
    -module YaffleViewHelper
    +
    module YaffleViewHelper
       def squawk_info_for(yaffle)
         returning "" do |result|
           result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
    @@ -984,12 +978,12 @@ http://www.gnu.org/software/src-highlite -->
     

    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
    @@ -1006,14 +1000,13 @@ Example: db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall

    Now you can add code to your generator:

    +

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

    -
    # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
    -
    -class YaffleGenerator < Rails::Generator::NamedBase
    +
    class YaffleGenerator < Rails::Generator::NamedBase
       def manifest
         record do |m|
           m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
    @@ -1054,19 +1047,18 @@ Reuses the built-in rails migration template.
     
     

    When you run the generator like

    -
    +
    script/generate yaffle bird

    You will see a new file:

    +

    db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

    -
    # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
    -
    -class AddYaffleFieldsToBirds < ActiveRecord::Migration
    +
    class AddYaffleFieldsToBirds < ActiveRecord::Migration
       def self.up
         add_column :birds, :last_squawk, :string
         add_column :birds, :last_squawked_at, :datetime
    @@ -1100,25 +1092,24 @@ Add the method to your generator.
     
     

    Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:

    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -require "commands"
    +
    require "commands"
     Rails::Generator::Commands::Create.send   :include,  Yaffle::Generator::Commands::Create
     Rails::Generator::Commands::Destroy.send  :include,  Yaffle::Generator::Commands::Destroy
     Rails::Generator::Commands::List.send     :include,  Yaffle::Generator::Commands::List
     
    +

    vendor/plugins/yaffle/lib/commands.rb

    -
    # File: vendor/plugins/yaffle/lib/commands.rb
    -
    -require 'rails_generator'
    +
    require 'rails_generator'
     require 'rails_generator/commands'
     
     module Yaffle #:nodoc:
    @@ -1145,20 +1136,18 @@ http://www.gnu.org/software/src-highlite -->
       end
     end
     
    +

    vendor/plugins/yaffle/generators/yaffle/templates/definition.txt

    -
    # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
    -
    -Yaffle is a bird
    +
    Yaffle is a bird
    +

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

    -
    # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
    -
    -class YaffleGenerator < Rails::Generator::NamedBase
    +
    class YaffleGenerator < Rails::Generator::NamedBase
       def manifest
         m.yaffle_definition
       end
    @@ -1169,14 +1158,13 @@ http://www.gnu.org/software/src-highlite -->
     

    7. Add a Custom Route

    Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.

    +

    vendor/plugins/yaffle/test/routing_test.rb

    -
    # File: vendor/plugins/yaffle/test/routing_test.rb
    -
    -require "#{File.dirname(__FILE__)}/test_helper"
    +
    require "#{File.dirname(__FILE__)}/test_helper"
     
     class RoutingTest < Test::Unit::TestCase
     
    @@ -1202,24 +1190,22 @@ http://www.gnu.org/software/src-highlite -->
         end
     end
     
    +

    vendor/plugins/yaffle/init.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -require "routing"
    +
    require "routing"
     ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
     
    +

    vendor/plugins/yaffle/lib/routing.rb

    -
    # File: vendor/plugins/yaffle/lib/routing.rb
    -
    -module Yaffle #:nodoc:
    +
    module Yaffle #:nodoc:
       module Routing #:nodoc:
         module MapperExtensions
           def yaffles
    @@ -1229,14 +1215,13 @@ http://www.gnu.org/software/src-highlite -->
       end
     end
     
    +

    config/routes.rb

    -
    # File: config/routes.rb
    -
    -ActionController::Routing::Routes.draw do |map|
    +
    ActionController::Routing::Routes.draw do |map|
       ...
       map.yaffles
     end
    @@ -1328,14 +1313,13 @@ http://www.gnu.org/software/src-highlite -->
     

    8.4. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    +

    vendor/plugins/yaffle/tasks/yaffle.rake

    -
    # File: vendor/plugins/yaffle/tasks/yaffle.rake
    -
    -namespace :yaffle do
    +
    namespace :yaffle do
       desc "Prints out the word 'Yaffle'"
       task :squawk => :environment do
         puts "squawk!"
    diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
    index 12d40deb18..06878543e4 100644
    --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
    +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt
    @@ -4,10 +4,10 @@ A common pattern in plugins is to add a method called `acts_as_something` to mod
     
     To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
     
    +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
     require File.dirname(__FILE__) + '/test_helper.rb'
     
     class Hickwall < ActiveRecord::Base
    @@ -18,16 +18,18 @@ class ActsAsYaffleTest < Test::Unit::TestCase
     end
     ------------------------------------------------------
     
    +*vendor/plugins/lib/acts_as_yaffle.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/lib/acts_as_yaffle.rb
    -
     module Yaffle
     end
     ------------------------------------------------------
     
     One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
     
    +*vendor/plugins/lib/acts_as_yaffle.rb*
    +
     [source, ruby]
     ------------------------------------------------------
     module Yaffle
    @@ -65,10 +67,10 @@ end
     
     Now that test should pass.  Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict.  You can write a few simple tests for this:
     
    +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
     require File.dirname(__FILE__) + '/test_helper.rb'
     
     class ActsAsYaffleTest < Test::Unit::TestCase
    @@ -92,10 +94,10 @@ end
     
     To make these tests pass, you could modify your `acts_as_yaffle` file like so:
     
    +*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
     module Yaffle
       def self.included(base)
         base.send :extend, ClassMethods
    @@ -117,10 +119,10 @@ end
     
     Now you can add tests for the instance methods, and the instance method itself:
     
    +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
    -
     require File.dirname(__FILE__) + '/test_helper.rb'
     
     class ActsAsYaffleTest < Test::Unit::TestCase
    @@ -163,10 +165,10 @@ class ActsAsYaffleTest < Test::Unit::TestCase
     end
     ------------------------------------------------------
     
    +*vendor/plugins/yaffle/lib/acts_as_yaffle.rb*
    +
     [source, ruby]
     ------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
     module Yaffle
       def self.included(base)
         base.send :extend, ClassMethods
    @@ -190,4 +192,5 @@ module Yaffle
     end
     ------------------------------------------------------
     
    -Note the use of `write_attribute` to write to the field in model.
    +.Editor's note:
    +NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use.  For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`.
    diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt
    index 6d9613ea01..a8cf1b48ce 100644
    --- a/railties/doc/guides/source/creating_plugins/custom_generator.txt
    +++ b/railties/doc/guides/source/creating_plugins/custom_generator.txt
    @@ -8,19 +8,20 @@ You may have noticed above that you can used one of the built-in rails migration
     
     Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
     
    +*vendor/plugins/yaffle/init.rb*
    +
     [source, ruby]
     -----------------------------------------------------------
    -# File: vendor/plugins/yaffle/init.rb
     require "commands"
     Rails::Generator::Commands::Create.send   :include,  Yaffle::Generator::Commands::Create
     Rails::Generator::Commands::Destroy.send  :include,  Yaffle::Generator::Commands::Destroy
     Rails::Generator::Commands::List.send     :include,  Yaffle::Generator::Commands::List
     -----------------------------------------------------------
     
    +*vendor/plugins/yaffle/lib/commands.rb*
    +
     [source, ruby]
     -----------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/commands.rb
    -
     require 'rails_generator'
     require 'rails_generator/commands'
     
    @@ -49,16 +50,15 @@ module Yaffle #:nodoc:
     end
     -----------------------------------------------------------
     
    +*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt*
     -----------------------------------------------------------
    -# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
    -
     Yaffle is a bird
     -----------------------------------------------------------
     
    +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
    +
     [source, ruby]
     -----------------------------------------------------------
    -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
    -
     class YaffleGenerator < Rails::Generator::NamedBase
       def manifest
         m.yaffle_definition
    diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt
    index 7e399247ee..1fce902a4e 100644
    --- a/railties/doc/guides/source/creating_plugins/custom_route.txt
    +++ b/railties/doc/guides/source/creating_plugins/custom_route.txt
    @@ -2,10 +2,10 @@
     
     Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself.  Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.
     
    +*vendor/plugins/yaffle/test/routing_test.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/routing_test.rb
    -
     require "#{File.dirname(__FILE__)}/test_helper"
     
     class RoutingTest < Test::Unit::TestCase
    @@ -33,18 +33,18 @@ class RoutingTest < Test::Unit::TestCase
     end
     --------------------------------------------------------
     
    +*vendor/plugins/yaffle/init.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/init.rb
    -
     require "routing"
     ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
     --------------------------------------------------------
     
    +*vendor/plugins/yaffle/lib/routing.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/routing.rb
    -
     module Yaffle #:nodoc:
       module Routing #:nodoc:
         module MapperExtensions
    @@ -56,10 +56,10 @@ module Yaffle #:nodoc:
     end
     --------------------------------------------------------
     
    +*config/routes.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: config/routes.rb
    -
     ActionController::Routing::Routes.draw do |map|
       ...
       map.yaffles
    diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt
    index 598a0c8437..1a477a69ab 100644
    --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt
    +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt
    @@ -6,11 +6,15 @@ We'll be relying on the built-in rails generate template for this tutorial.  Goi
     
     Type:
     
    -    script/generate
    +------------------------------------------------------------------
    +script/generate
    +------------------------------------------------------------------
     
     You should see the line:
     
    -    Plugins (vendor/plugins): yaffle
    +------------------------------------------------------------------
    +Plugins (vendor/plugins): yaffle
    +------------------------------------------------------------------
     
     When you run `script/generate yaffle` you should see the contents of your USAGE file.  For this plugin, the USAGE file looks like this:
     
    @@ -27,10 +31,10 @@ Example:
     
     Now you can add code to your generator:
     
    +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb*
    +
     [source, ruby]
     ------------------------------------------------------------------
    -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
    -
     class YaffleGenerator < Rails::Generator::NamedBase
       def manifest
         record do |m|
    @@ -67,14 +71,16 @@ This does a few things:
     
     When you run the generator like
     
    -    script/generate yaffle bird
    +------------------------------------------------------------------
    +script/generate yaffle bird
    +------------------------------------------------------------------
     
     You will see a new file:
     
    +*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb*
    +
     [source, ruby]
     ------------------------------------------------------------------
    -# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
    -
     class AddYaffleFieldsToBirds < ActiveRecord::Migration
       def self.up
         add_column :birds, :last_squawk, :string
    diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
    index 32da7ed7f3..88cd4fe9ed 100644
    --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
    +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt
    @@ -81,10 +81,10 @@ When you created the plugin with the built-in rails generator, it generated a ra
     
     Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
     
    +*vendor/plugins/yaffle/tasks/yaffle.rake*
    +
     [source, ruby]
     ---------------------------------------------------------
    -# File: vendor/plugins/yaffle/tasks/yaffle.rake
    -
     namespace :yaffle do
       desc "Prints out the word 'Yaffle'"
       task :squawk => :environment do
    diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
    index 50516cef69..63f1131442 100644
    --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
    +++ b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt
    @@ -10,10 +10,10 @@ Most plugins store their code classes in the plugin's lib directory.  When you a
     
     First, you need to write the tests.  Testing plugins is very similar to testing rails apps.  The generated test file should look something like this:
     
    +*vendor/plugins/yaffle/test/core_ext_test.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/core_ext_test.rb
    -
     require 'test/unit'
     
     class CoreExtTest < Test::Unit::TestCase
    @@ -26,11 +26,10 @@ end
     
     Start off by removing the default test, and adding a require statement for your test helper.
     
    +*vendor/plugins/yaffle/test/core_ext_test.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/core_ext_test.rb
    -
    -require 'test/unit'
     require File.dirname(__FILE__) + '/test_helper.rb'
     
     class CoreExtTest < Test::Unit::TestCase
    @@ -53,10 +52,10 @@ No tests were specified
     
     Great - now you are ready to start development.  The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''.  The test will look something like this:
     
    +*vendor/plugins/yaffle/init.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/init.rb
    -
     class CoreExtTest < Test::Unit::TestCase
       def test_string_should_respond_to_squawk
         assert_equal true, "".respond_to?(:to_squawk)
    @@ -72,17 +71,17 @@ class CoreExtTest < Test::Unit::TestCase
     end
     --------------------------------------------------------
     
    +*vendor/plugins/yaffle/init.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/init.rb
    -
     require "core_ext"
     --------------------------------------------------------
     
    +*vendor/plugins/yaffle/lib/core_ext.rb*
    +
     [source, ruby]
     --------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/core_ext.rb
    -
     String.class_eval do
       def to_squawk
         "squawk! #{self}".strip
    diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt
    index b03a190e1a..4eaec93824 100644
    --- a/railties/doc/guides/source/creating_plugins/view_helper.txt
    +++ b/railties/doc/guides/source/creating_plugins/view_helper.txt
    @@ -8,10 +8,10 @@ Creating a view helper is a 3-step process:
     
     First, create the test to define the functionality you want:
     
    +*vendor/plugins/yaffle/test/view_helpers_test.rb*
    +
     [source, ruby]
     ---------------------------------------------------------------
    -# File: vendor/plugins/yaffle/test/view_helpers_test.rb
    -
     require File.dirname(__FILE__) + '/test_helper.rb'
     include YaffleViewHelper
     
    @@ -28,20 +28,20 @@ end
     
     Then add the following statements to init.rb:
     
    +*vendor/plugins/yaffle/init.rb*
    +
     [source, ruby]
     ---------------------------------------------------------------
    -# File: vendor/plugins/yaffle/init.rb
    -
     require "view_helpers"
     ActionView::Base.send :include, YaffleViewHelper
     ---------------------------------------------------------------
     
     Then add the view helpers file and
     
    +*vendor/plugins/yaffle/lib/view_helpers.rb*
    +
     [source, ruby]
     ---------------------------------------------------------------
    -# File: vendor/plugins/yaffle/lib/view_helpers.rb
    -
     module YaffleViewHelper
       def squawk_info_for(yaffle)
         returning "" do |result|
    -- 
    cgit v1.2.3
    
    
    From 7f023b5e3bd62c1f91ee341c1af155c0953e693a Mon Sep 17 00:00:00 2001
    From: Ryan Bigg 
    Date: Wed, 12 Nov 2008 21:45:42 +1030
    Subject: Updated finders guide
    
    ---
     railties/doc/guides/source/finders.txt | 2 +-
     1 file changed, 1 insertion(+), 1 deletion(-)
    
    diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt
    index 2e6b368e3f..d26711fce2 100644
    --- a/railties/doc/guides/source/finders.txt
    +++ b/railties/doc/guides/source/finders.txt
    @@ -120,7 +120,7 @@ To find all the clients you would simply type +Client.all+ and that would find a
       created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50">, 
       # "Michael", locked: false, orders_count: 3, 
       created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">]
    --------------------------------------------------------
    +------------------------------------------------------- 
     
     As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively.
     
    -- 
    cgit v1.2.3
    
    
    From 44a3009ff068bf080de6764a8c884fbf0ceb920e Mon Sep 17 00:00:00 2001
    From: Tom Stuart 
    Date: Wed, 12 Nov 2008 11:00:17 +0000
    Subject: Add :only/:except options to map.resources
    
    This allows people with huge numbers of resource routes to cut down on the memory consumption caused by the generated code.
    
    Signed-off-by: Michael Koziarski 
    [#1215 state:committed]
    ---
     actionpack/lib/action_controller/resources.rb | 122 +++++++++++++------
     actionpack/test/controller/resources_test.rb  | 162 ++++++++++++++++++++++++++
     2 files changed, 247 insertions(+), 37 deletions(-)
    
    diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb
    index 872b0dab3d..de529e23ff 100644
    --- a/actionpack/lib/action_controller/resources.rb
    +++ b/actionpack/lib/action_controller/resources.rb
    @@ -42,7 +42,11 @@ module ActionController
       #
       # Read more about REST at http://en.wikipedia.org/wiki/Representational_State_Transfer
       module Resources
    +    INHERITABLE_OPTIONS = :namespace, :shallow, :only, :except
    +
         class Resource #:nodoc:
    +      DEFAULT_ACTIONS = :index, :create, :new, :edit, :show, :update, :destroy
    +
           attr_reader :collection_methods, :member_methods, :new_methods
           attr_reader :path_prefix, :name_prefix, :path_segment
           attr_reader :plural, :singular
    @@ -57,6 +61,7 @@ module ActionController
     
             arrange_actions
             add_default_actions
    +        set_allowed_actions
             set_prefixes
           end
     
    @@ -113,6 +118,10 @@ module ActionController
             @singular.to_s == @plural.to_s
           end
     
    +      def has_action?(action)
    +        !DEFAULT_ACTIONS.include?(action) || action_allowed?(action)
    +      end
    +
           protected
             def arrange_actions
               @collection_methods = arrange_actions_by_methods(options.delete(:collection))
    @@ -125,6 +134,30 @@ module ActionController
               add_default_action(new_methods, :get, :new)
             end
     
    +        def set_allowed_actions
    +          only, except = @options.values_at(:only, :except)
    +          @allowed_actions ||= {}
    +
    +          if only == :all || except == :none
    +            only = nil
    +            except = []
    +          elsif only == :none || except == :all
    +            only = []
    +            except = nil
    +          end
    +
    +          if only
    +            @allowed_actions[:only] = Array(only).map(&:to_sym)
    +          elsif except
    +            @allowed_actions[:except] = Array(except).map(&:to_sym)
    +          end
    +        end
    +
    +        def action_allowed?(action)
    +          only, except = @allowed_actions.values_at(:only, :except)
    +          (!only || only.include?(action)) && (!except || !except.include?(action))
    +        end
    +
             def set_prefixes
               @path_prefix = options.delete(:path_prefix)
               @name_prefix = options.delete(:name_prefix)
    @@ -353,6 +386,25 @@ module ActionController
         #
         #   map.resources :users, :has_many => { :posts => :comments }, :shallow => true
         #
    +    # * :only and :except - Specify which of the seven default actions should be routed to.
    +    #
    +    # :only and :except may be set to :all, :none, an action name or a
    +    # list of action names. By default, routes are generated for all seven actions.
    +    #
    +    # For example:
    +    #
    +    #   map.resources :posts, :only => [:index, :show] do |post|
    +    #     post.resources :comments, :except => [:update, :destroy]
    +    #   end
    +    #   # --> GET /posts (maps to the PostsController#index action)
    +    #   # --> POST /posts (fails)
    +    #   # --> GET /posts/1 (maps to the PostsController#show action)
    +    #   # --> DELETE /posts/1 (fails)
    +    #   # --> POST /posts/1/comments (maps to the CommentsController#create action)
    +    #   # --> PUT /posts/1/comments/1 (fails)
    +    #
    +    # The :only and :except options are inherited by any nested resource(s).
    +    #
         # If map.resources is called with multiple resources, they all get the same options applied.
         #
         # Examples:
    @@ -478,7 +530,7 @@ module ActionController
               map_associations(resource, options)
     
               if block_given?
    -            with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
    +            with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
               end
             end
           end
    @@ -495,7 +547,7 @@ module ActionController
               map_associations(resource, options)
     
               if block_given?
    -            with_options(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], &block)
    +            with_options(options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix), &block)
               end
             end
           end
    @@ -507,7 +559,7 @@ module ActionController
             name_prefix = "#{options.delete(:name_prefix)}#{resource.nesting_name_prefix}"
     
             Array(options[:has_one]).each do |association|
    -          resource(association, :path_prefix => path_prefix, :name_prefix => name_prefix, :namespace => options[:namespace], :shallow => options[:shallow])
    +          resource(association, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => path_prefix, :name_prefix => name_prefix))
             end
           end
     
    @@ -522,7 +574,7 @@ module ActionController
                 map_has_many_associations(resource, association, options)
               end
             when Symbol, String
    -          resources(associations, :path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :namespace => options[:namespace], :shallow => options[:shallow], :has_many => options[:has_many])
    +          resources(associations, options.slice(*INHERITABLE_OPTIONS).merge(:path_prefix => resource.nesting_path_prefix, :name_prefix => resource.nesting_name_prefix, :has_many => options[:has_many]))
             else
             end
           end
    @@ -531,41 +583,39 @@ module ActionController
             resource.collection_methods.each do |method, actions|
               actions.each do |action|
                 [method].flatten.each do |m|
    -              action_options = action_options_for(action, resource, m)
    -              map_named_routes(map, "#{action}_#{resource.name_prefix}#{resource.plural}", "#{resource.path}#{resource.action_separator}#{action}", action_options)
    +              map_resource_routes(map, resource, action, "#{resource.path}#{resource.action_separator}#{action}", "#{action}_#{resource.name_prefix}#{resource.plural}", m)
                 end
               end
             end
           end
     
           def map_default_collection_actions(map, resource)
    -        index_action_options = action_options_for("index", resource)
             index_route_name = "#{resource.name_prefix}#{resource.plural}"
     
             if resource.uncountable?
               index_route_name << "_index"
             end
     
    -        map_named_routes(map, index_route_name, resource.path, index_action_options)
    -
    -        create_action_options = action_options_for("create", resource)
    -        map_unnamed_routes(map, resource.path, create_action_options)
    +        map_resource_routes(map, resource, :index, resource.path, index_route_name)
    +        map_resource_routes(map, resource, :create, resource.path)
           end
     
           def map_default_singleton_actions(map, resource)
    -        create_action_options = action_options_for("create", resource)
    -        map_unnamed_routes(map, resource.path, create_action_options)
    +        map_resource_routes(map, resource, :create, resource.path)
           end
     
           def map_new_actions(map, resource)
             resource.new_methods.each do |method, actions|
               actions.each do |action|
    -            action_options = action_options_for(action, resource, method)
    -            if action == :new
    -              map_named_routes(map, "new_#{resource.name_prefix}#{resource.singular}", resource.new_path, action_options)
    -            else
    -              map_named_routes(map, "#{action}_new_#{resource.name_prefix}#{resource.singular}", "#{resource.new_path}#{resource.action_separator}#{action}", action_options)
    +            route_path = resource.new_path
    +            route_name = "new_#{resource.name_prefix}#{resource.singular}"
    +
    +            unless action == :new
    +              route_path = "#{route_path}#{resource.action_separator}#{action}"
    +              route_name = "#{action}_#{route_name}"
                 end
    +
    +            map_resource_routes(map, resource, action, route_path, route_name, method)
               end
             end
           end
    @@ -574,34 +624,32 @@ module ActionController
             resource.member_methods.each do |method, actions|
               actions.each do |action|
                 [method].flatten.each do |m|
    -              action_options = action_options_for(action, resource, m)
    -
                   action_path = resource.options[:path_names][action] if resource.options[:path_names].is_a?(Hash)
                   action_path ||= Base.resources_path_names[action] || action
     
    -              map_named_routes(map, "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", "#{resource.member_path}#{resource.action_separator}#{action_path}", action_options)
    +              map_resource_routes(map, resource, action, "#{resource.member_path}#{resource.action_separator}#{action_path}", "#{action}_#{resource.shallow_name_prefix}#{resource.singular}", m)
                 end
               end
             end
     
    -        show_action_options = action_options_for("show", resource)
    -        map_named_routes(map, "#{resource.shallow_name_prefix}#{resource.singular}", resource.member_path, show_action_options)
    -
    -        update_action_options = action_options_for("update", resource)
    -        map_unnamed_routes(map, resource.member_path, update_action_options)
    -
    -        destroy_action_options = action_options_for("destroy", resource)
    -        map_unnamed_routes(map, resource.member_path, destroy_action_options)
    +        map_resource_routes(map, resource, :show, resource.member_path, "#{resource.shallow_name_prefix}#{resource.singular}")
    +        map_resource_routes(map, resource, :update, resource.member_path)
    +        map_resource_routes(map, resource, :destroy, resource.member_path)
           end
     
    -      def map_unnamed_routes(map, path_without_format, options)
    -        map.connect(path_without_format, options)
    -        map.connect("#{path_without_format}.:format", options)
    -      end
    -
    -      def map_named_routes(map, name, path_without_format, options)
    -        map.named_route(name, path_without_format, options)
    -        map.named_route("formatted_#{name}", "#{path_without_format}.:format", options)
    +      def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil)
    +        if resource.has_action?(action)
    +          action_options = action_options_for(action, resource, method)
    +          formatted_route_path = "#{route_path}.:format"
    +
    +          if route_name
    +            map.named_route(route_name, route_path, action_options)
    +            map.named_route("formatted_#{route_name}", formatted_route_path, action_options)
    +          else
    +            map.connect(route_path, action_options)
    +            map.connect(formatted_route_path, action_options)
    +          end
    +        end
           end
     
           def add_conditions_for(conditions, method)
    diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb
    index 1fea82e564..2a86577d8c 100644
    --- a/actionpack/test/controller/resources_test.rb
    +++ b/actionpack/test/controller/resources_test.rb
    @@ -14,6 +14,8 @@ class LogosController < ResourcesController; end
     
     class AccountsController <  ResourcesController; end
     class AdminController   <  ResourcesController; end
    +class ProductsController < ResourcesController; end
    +class ImagesController < ResourcesController; end
     
     module Backoffice
       class ProductsController < ResourcesController; end
    @@ -776,6 +778,121 @@ class ResourcesTest < Test::Unit::TestCase
         end
       end
     
    +  def test_resource_has_only_show_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :only => :show
    +      end
    +
    +      assert_resource_allowed_routes('products', {},                    { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
    +      assert_resource_allowed_routes('products', { :format => 'xml' },  { :id => '1' }, :show, [:index, :new, :create, :edit, :update, :destroy])
    +    end
    +  end
    +
    +  def test_singleton_resource_has_only_show_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resource :account, :only => :show
    +      end
    +
    +      assert_singleton_resource_allowed_routes('accounts', {},                    :show, [:index, :new, :create, :edit, :update, :destroy])
    +      assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' },  :show, [:index, :new, :create, :edit, :update, :destroy])
    +    end
    +  end
    +
    +  def test_resource_does_not_have_destroy_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :except => :destroy
    +      end
    +
    +      assert_resource_allowed_routes('products', {},                    { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
    +      assert_resource_allowed_routes('products', { :format => 'xml' },  { :id => '1' }, [:index, :new, :create, :show, :edit, :update], :destroy)
    +    end
    +  end
    +
    +  def test_singleton_resource_does_not_have_destroy_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resource :account, :except => :destroy
    +      end
    +
    +      assert_singleton_resource_allowed_routes('accounts', {},                    [:new, :create, :show, :edit, :update], :destroy)
    +      assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' },  [:new, :create, :show, :edit, :update], :destroy)
    +    end
    +  end
    +
    +  def test_resource_has_only_collection_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :except => :all, :collection => { :sale => :get }
    +      end
    +
    +      assert_resource_allowed_routes('products', {},                    { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
    +      assert_resource_allowed_routes('products', { :format => 'xml' },  { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
    +
    +      assert_recognizes({ :controller => 'products', :action => 'sale' },                   :path => 'products/sale',     :method => :get)
    +      assert_recognizes({ :controller => 'products', :action => 'sale', :format => 'xml' }, :path => 'products/sale.xml', :method => :get)
    +    end
    +  end
    +
    +  def test_resource_has_only_member_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :except => :all, :member => { :preview => :get }
    +      end
    +
    +      assert_resource_allowed_routes('products', {},                    { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
    +      assert_resource_allowed_routes('products', { :format => 'xml' },  { :id => '1' }, [], [:index, :new, :create, :show, :edit, :update, :destroy])
    +
    +      assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1' },                    :path => 'products/1/preview',      :method => :get)
    +      assert_recognizes({ :controller => 'products', :action => 'preview', :id => '1', :format => 'xml' },  :path => 'products/1/preview.xml',  :method => :get)
    +    end
    +  end
    +
    +  def test_singleton_resource_has_only_member_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resource :account, :except => :all, :member => { :signup => :get }
    +      end
    +
    +      assert_singleton_resource_allowed_routes('accounts', {},                    [], [:new, :create, :show, :edit, :update, :destroy])
    +      assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' },  [], [:new, :create, :show, :edit, :update, :destroy])
    +
    +      assert_recognizes({ :controller => 'accounts', :action => 'signup' },                   :path => 'account/signup',      :method => :get)
    +      assert_recognizes({ :controller => 'accounts', :action => 'signup', :format => 'xml' }, :path => 'account/signup.xml',  :method => :get)
    +    end
    +  end
    +
    +  def test_nested_resource_inherits_only_show_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :only => :show do |product|
    +          product.resources :images
    +        end
    +      end
    +
    +      assert_resource_allowed_routes('images', { :product_id => '1' },                    { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
    +      assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' },  { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
    +    end
    +  end
    +
    +  def test_nested_resource_has_only_show_and_member_action
    +    with_routing do |set|
    +      set.draw do |map|
    +        map.resources :products, :only => [:index, :show] do |product|
    +          product.resources :images, :member => { :thumbnail => :get }, :only => :show
    +        end
    +      end
    +
    +      assert_resource_allowed_routes('images', { :product_id => '1' },                    { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
    +      assert_resource_allowed_routes('images', { :product_id => '1', :format => 'xml' },  { :id => '2' }, :show, [:index, :new, :create, :edit, :update, :destroy], 'products/1/images')
    +
    +      assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2' },                    :path => 'products/1/images/2/thumbnail', :method => :get)
    +      assert_recognizes({ :controller => 'images', :action => 'thumbnail', :product_id => '1', :id => '2', :format => 'jpg' },  :path => 'products/1/images/2/thumbnail.jpg', :method => :get)
    +    end
    +  end
    +
       protected
         def with_restful_routing(*args)
           with_routing do |set|
    @@ -979,6 +1096,51 @@ class ResourcesTest < Test::Unit::TestCase
           end
         end
     
    +    def assert_resource_allowed_routes(controller, options, shallow_options, allowed, not_allowed, path = controller)
    +      shallow_path = "#{path}/#{shallow_options[:id]}"
    +      format = options[:format] && ".#{options[:format]}"
    +      options.merge!(:controller => controller)
    +      shallow_options.merge!(options)
    +
    +      assert_whether_allowed(allowed, not_allowed, options,         'index',    "#{path}#{format}",               :get)
    +      assert_whether_allowed(allowed, not_allowed, options,         'new',      "#{path}/new#{format}",           :get)
    +      assert_whether_allowed(allowed, not_allowed, options,         'create',   "#{path}#{format}",               :post)
    +      assert_whether_allowed(allowed, not_allowed, shallow_options, 'show',     "#{shallow_path}#{format}",       :get)
    +      assert_whether_allowed(allowed, not_allowed, shallow_options, 'edit',     "#{shallow_path}/edit#{format}",  :get)
    +      assert_whether_allowed(allowed, not_allowed, shallow_options, 'update',   "#{shallow_path}#{format}",       :put)
    +      assert_whether_allowed(allowed, not_allowed, shallow_options, 'destroy',  "#{shallow_path}#{format}",       :delete)
    +    end
    +
    +    def assert_singleton_resource_allowed_routes(controller, options, allowed, not_allowed, path = controller.singularize)
    +      format = options[:format] && ".#{options[:format]}"
    +      options.merge!(:controller => controller)
    +
    +      assert_whether_allowed(allowed, not_allowed, options, 'new',      "#{path}/new#{format}",   :get)
    +      assert_whether_allowed(allowed, not_allowed, options, 'create',   "#{path}#{format}",       :post)
    +      assert_whether_allowed(allowed, not_allowed, options, 'show',     "#{path}#{format}",       :get)
    +      assert_whether_allowed(allowed, not_allowed, options, 'edit',     "#{path}/edit#{format}",  :get)
    +      assert_whether_allowed(allowed, not_allowed, options, 'update',   "#{path}#{format}",       :put)
    +      assert_whether_allowed(allowed, not_allowed, options, 'destroy',  "#{path}#{format}",       :delete)
    +    end
    +
    +    def assert_whether_allowed(allowed, not_allowed, options, action, path, method)
    +      action = action.to_sym
    +      options = options.merge(:action => action.to_s)
    +      path_options = { :path => path, :method => method }
    +
    +      if Array(allowed).include?(action)
    +        assert_recognizes options, path_options
    +      elsif Array(not_allowed).include?(action)
    +        assert_not_recognizes options, path_options
    +      end
    +    end
    +
    +    def assert_not_recognizes(expected_options, path)
    +      assert_raise ActionController::RoutingError, ActionController::MethodNotAllowed, Test::Unit::AssertionFailedError do
    +        assert_recognizes(expected_options, path)
    +      end
    +    end
    +
         def distinct_routes? (r1, r2)
           if r1.conditions == r2.conditions and r1.requirements == r2.requirements then
             if r1.segments.collect(&:to_s) == r2.segments.collect(&:to_s) then
    -- 
    cgit v1.2.3
    
    
    From 02df503d3b4db7a3e7fabe1403c388a059f905b8 Mon Sep 17 00:00:00 2001
    From: Phil Ross 
    Date: Wed, 12 Nov 2008 13:42:56 +0000
    Subject: TimeZone: Caracas GMT offset changed to -4:30 [#1361 state:resolved]
    
    ---
     activesupport/CHANGELOG                              | 2 ++
     activesupport/lib/active_support/values/time_zone.rb | 3 ++-
     2 files changed, 4 insertions(+), 1 deletion(-)
    
    diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG
    index e77affc315..12b300d3ae 100644
    --- a/activesupport/CHANGELOG
    +++ b/activesupport/CHANGELOG
    @@ -1,5 +1,7 @@
     *2.2.1 [RC2 or 2.2 final]*
     
    +* TimeZone: Caracas GMT offset changed to -4:30 [#1361 state:resolved] [Phil Ross]
    +
     * Added render :js for people who want to render inline JavaScript replies without using RJS [DHH]
     
     * Fixed the option merging in Array#to_xml #1126 [Rudolf Gavlas]
    diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
    index 4991f71683..335d75d218 100644
    --- a/activesupport/lib/active_support/values/time_zone.rb
    +++ b/activesupport/lib/active_support/values/time_zone.rb
    @@ -304,7 +304,8 @@ module ActiveSupport
                      "Mexico City", "Monterrey", "Central America" ],
            [-18_000, "Eastern Time (US & Canada)", "Indiana (East)", "Bogota",
                      "Lima", "Quito" ],
    -       [-14_400, "Atlantic Time (Canada)", "Caracas", "La Paz", "Santiago" ],
    +       [-16_200, "Caracas" ],
    +       [-14_400, "Atlantic Time (Canada)", "La Paz", "Santiago" ],
            [-12_600, "Newfoundland" ],
            [-10_800, "Brasilia", "Buenos Aires", "Georgetown", "Greenland" ],
            [ -7_200, "Mid-Atlantic" ],
    -- 
    cgit v1.2.3
    
    
    From ff359af86505b4d317b7467e7f79aa2ef2c5e795 Mon Sep 17 00:00:00 2001
    From: athonlab 
    Date: Thu, 13 Nov 2008 09:31:10 +0530
    Subject: Rails testing guide revised based on feedback from Pratik and few
     miscellaneous fixes. [#8]
    
    ---
     .../guides/source/testing_rails_applications.txt   | 390 +++++++++++++--------
     1 file changed, 249 insertions(+), 141 deletions(-)
    
    diff --git a/railties/doc/guides/source/testing_rails_applications.txt b/railties/doc/guides/source/testing_rails_applications.txt
    index 31b6fc2cfa..6cced2fdd1 100644
    --- a/railties/doc/guides/source/testing_rails_applications.txt
    +++ b/railties/doc/guides/source/testing_rails_applications.txt
    @@ -11,18 +11,17 @@ This guide won't teach you to write a Rails application; it assumes basic famili
     
     == Why Write Tests for your Rails Applications? ==
     
    - * Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors.
    - * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
    - * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
      * Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.
    + * By simply running your Rails tests you can ensure your code adheres to the desired functionality even after some major code refactoring.
    + * Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.
     
    -== Before you Start Writing Tests ==
    +== Introduction to Testing ==
     
    -Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
    +Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.
     
     === The 3 Environments ===
     
    -Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
    +Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.
     
     One place you'll find this distinction is in the +config/database.yml+ file. This YAML configuration file has 3 different sections defining 3 unique database setups:
     
    @@ -55,11 +54,11 @@ For good tests, you'll need to give some thought to setting up test data. In Rai
     
     ==== What Are Fixtures? ====
     
    -_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*.
    +_Fixtures_ is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: *YAML* or *CSV*. In this guide we will use *YAML* which is the preferred format.
     
     You'll find fixtures under your +test/fixtures+ directory. When you run +script/generate model+ to create a new model, fixture stubs will be automatically created and placed in this directory.
     
    -==== YAML the Camel is a Mammal with Enamel ====
    +==== YAML ====
     
     YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the *.yml* file extension (as in +users.yml+).
     
    @@ -69,13 +68,11 @@ Here's a sample YAML fixture file:
     ---------------------------------------------
     # low & behold!  I am a YAML comment!
     david:
    - id: 1
      name: David Heinemeier Hansson
      birthday: 1979-10-15
      profession: Systems development
     
     steve:
    - id: 2
      name: Steve Ross Kellock
      birthday: 1974-09-27
      profession: guy with keyboard
    @@ -83,55 +80,24 @@ steve:
     
     Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.
     
    -==== Comma Seperated ====
    -
    -Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the 'test/fixtures' directory, but these end with the +.csv+ file extension (as in +celebrity_holiday_figures.csv+).
    -
    -A CSV fixture looks like this:
    -
    ---------------------------------------------------------------
    -id, username, password, stretchable, comments
    -1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
    -2, ebunny, ihateeggs, true, Hoppity hop y'all
    -3, tfairy, ilovecavities, true, "Pull your teeth, I will"
    ---------------------------------------------------------------
    -
    -The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:
    -
    - * Leading and trailing spaces are trimmed from each value when it is imported
    - * If you use a comma as data, the cell must be encased in quotes
    - * If you use a quote as data, you must escape it with a 2nd quote
    - * Don't use blank lines
    - * Nulls can be defined by including no data between a pair of commas
    -
    -Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:
    -
    -* +celebrity-holiday-figures-1+
    -* +celebrity-holiday-figures-2+
    -* +celebrity-holiday-figures-3+
    -
    -The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.
    -
     ==== ERb'in It Up ====
     
     ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.
     
    -I'll demonstrate with a YAML file:
    -
     [source, ruby]
     --------------------------------------------------------------
     <% earth_size = 20 -%>
     mercury:
    -  id: 1
       size: <%= earth_size / 50 %>
    +  brightest_on: <%= 113.days.ago.to_s(:db) %>
     
     venus:
    -  id: 2
       size: <%= earth_size / 2 %>
    +  brightest_on: <%= 67.days.ago.to_s(:db) %>
     
     mars:
    -  id: 3
       size: <%= earth_size - 69 %>
    +  brightest_on: <%= 13.days.from_now.to_s(:db) %>
     --------------------------------------------------------------
     
     Anything encased within the
    @@ -141,7 +107,7 @@ Anything encased within the
     <% %>
     ------------------------
     
    -tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.
    +tag is considered Ruby code. When this fixture is loaded, the +size+ attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The +brightest_on+ attribute will also be evaluated and formatted by Rails to be compatible with the database.
     
     ==== Fixtures in Action ====
     
    @@ -164,9 +130,7 @@ users(:david)
     users(:david).id
     --------------------------------------------------------------
     
    -But, by there's another side to fixtures... at night, if the moon is full and the wind completely still, fixtures can also transform themselves into the form of the original class!
    -
    -Now you can get at the methods only available to that class.
    +Fixtures can also transform themselves into the form of the original class. Thus, you can get at the methods only available to that class.
     
     [source, ruby]
     --------------------------------------------------------------
    @@ -177,14 +141,18 @@ david = users(:david).find
     email(david.girlfriend.email, david.location_tonight)
     --------------------------------------------------------------
     
    -== Unit Testing Your Models ==
    +== Unit Testing your Models ==
     
     In Rails, unit tests are what you write to test your models.
     
    -When you create a model using +script/generate+, among other things it creates a test stub in the +test/unit+ folder, as well as a fixture for the model:
    +For this guide we will be using Rails _scaffolding_. It will create the model, a migration, controller and views for the new resource in a single operation. It will also create a full test suite following Rails best practises. I will be using examples from this generated code and would be supplementing it with additional examples where necessary.
    +
    +NOTE: For more information on Rails _scaffolding_, refer to link:../getting_started_with_rails.html[Getting Started with Rails]
    +
    +When you use +script/generate scaffold+, for a resource among other things it creates a test stub in the +test/unit+ folder:
     
     -------------------------------------------------------
    -$ script/generate model Post
    +$ script/generate scaffold post title:string body:text
     ...
     create  app/models/post.rb
     create  test/unit/post_test.rb
    @@ -243,6 +211,36 @@ This line of code is called an _assertion_. An assertion is a line of code that
     
     Every test contains one or more assertions. Only when all the assertions are successful the test passes.
     
    +=== Preparing you Application for Testing ===
    +
    +Before you can run your tests you need to ensure that the test database structure is current. For this you can use the following rake commands:
    +
    +[source, shell]
    +-------------------------------------------------------
    +$ rake db:migrate
    +...
    +$ rake db:test:load
    +-------------------------------------------------------
    +
    +Above +rake db:migrate+ runs any pending migrations on the _developemnt_ environment and updates +db/schema.rb+. +rake db:test:load+ recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run +db:test:prepare+ as it first checks for pending migrations and warns you appropriately.
    +
    +NOTE: +db:test:prepare+ will fail with an error if db/schema.rb doesn't exists.
    +
    +==== Rake Tasks for Preparing you Application for Testing ==
    +
    +[grid="all"]
    +--------------------------------`----------------------------------------------------
    +Tasks                           Description
    +------------------------------------------------------------------------------------
    ++rake db:test:clone+            Recreate the test database from the current environment's database schema
    ++rake db:test:clone_structure+  Recreate the test databases from the development structure
    ++rake db:test:load+             Recreate the test database from the current +schema.rb+
    ++rake db:test:prepare+          Check for pending migrations and load the test schema
    ++rake db:test:purge+            Empty the test database.
    +------------------------------------------------------------------------------------
    +
    +TIP: You can see all these rake tasks and their descriptions by running +rake --tasks --describe+
    +
     === Running Tests ===
     
     Running a test is as simple as invoking the file containing the test cases through Ruby:
    @@ -277,65 +275,90 @@ Finished in 0.023513 seconds.
     
     The +.+ (dot) above indicates a passing test. When a test fails you see an +F+; when a test throws an error you see an +E+ in its place. The last line of the output is the summary. 
     
    -To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case:
    +To see how a test failure is reported, you can add a failing test to the +post_test.rb+ test case.
     
     [source,ruby]
     --------------------------------------------------
    -def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post
    +def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save
     end
     --------------------------------------------------
     
    -If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:
    +Let us run this newly added test.
     
     -------------------------------------------------------
    -$ ruby unit/post_test.rb              
    +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.027274 seconds.
    +F
    +Finished in 0.197094 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    - expected to not be nil.
    + is not true.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    +1 tests, 1 assertions, 1 failures, 0 errors
     -------------------------------------------------------
     
     In the output, +F+ denotes a failure. You can see the corresponding trace shown under +1)+ along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:
     
     [source,ruby]
     --------------------------------------------------
    -def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
    +def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save, "Saved the post without a title"
     end
     --------------------------------------------------
     
     Running this test shows the friendlier assertion message:
     
     -------------------------------------------------------
    -$ ruby unit/post_test.rb
    +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.024727 seconds.
    +F
    +Finished in 0.198093 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    - expected to not be nil.
    +Saved the post without a title.
    + is not true.
    +
    +1 tests, 1 assertions, 1 failures, 0 errors
    +-------------------------------------------------------
    +
    +Now to get this test to pass we can add a model level validation for the _title_ field.
    +
    +[source,ruby]
    +--------------------------------------------------
    +class Post < ActiveRecord::Base
    +  validates_presence_of :title
    +end
    +--------------------------------------------------
    +
    +Now the test should pass. Let us verify by running the test again:
    +
    +-------------------------------------------------------
    +$ ruby unit/post_test.rb -n test_should_not_save_post_without_title
    +Loaded suite unit/post_test
    +Started
    +.
    +Finished in 0.193608 seconds.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    +1 tests, 1 assertions, 0 failures, 0 errors
     -------------------------------------------------------
     
    +Now if you noticed we first wrote a test which fails for a desired functionality, then we wrote some code which adds the functionality and finally we ensured that our test passes. This approach to software development is referred to as _Test-Driven Development_ (TDD). 
    +
    +TIP: Many Rails developers practice _Test-Driven Development_ (TDD). This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
    +
     To see how an error gets reported, here's a test containing an error:
     
     [source,ruby]
    @@ -350,29 +373,21 @@ end
     Now you can see even more output in the console from running the tests:
     
     -------------------------------------------------------
    -$ ruby unit/post_test.rb
    +$ ruby unit/post_test.rb -n test_should_report_error
     Loaded suite unit/post_test
     Started
    -FE.
    -Finished in 0.108389 seconds.
    -
    -  1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    - expected to not be nil.
    +E
    +Finished in 0.195757 seconds.
     
    -  2) Error:
    +  1) Error:
     test_should_report_error(PostTest):
    -NameError: undefined local variable or method `some_undefined_variable' for #
    +NameError: undefined local variable or method `some_undefined_variable' for #
         /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
    -    unit/post_test.rb:15:in `test_should_report_error'
    +    unit/post_test.rb:16:in `test_should_report_error'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
     
    -3 tests, 2 assertions, 1 failures, 1 errors
    +1 tests, 0 assertions, 0 failures, 1 errors
     -------------------------------------------------------
     
     Notice the 'E' in the output. It denotes a test with error. 
    @@ -383,8 +398,6 @@ NOTE: The execution of each test method stops as soon as any error or a assertio
     
     Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.
     
    -TIP: Many Rails developers practice _test-driven development_ (TDD), in which the tests are written _before_ the code that they are testing. This is an excellent way to build up a test suite that exercises every part of your application. TDD is beyond the scope of this guide, but one place to start is with link:http://andrzejonsoftware.blogspot.com/2007/05/15-tdd-steps-to-create-rails.html[15 TDD steps to create a Rails application].
    -
     === Assertions Available ===
     
     By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.
    @@ -454,32 +467,9 @@ You should test for things such as:
      * was the correct object stored in the response template?
      * was the appropriate message displayed to the user in the view
     
    -When you use +script/generate+ to create a controller, it automatically creates a functional test for that controller in +test/functional+. For example, if you create a post controller:
    -
    -[source, shell]
    --------------------------------------------------------
    -$ script/generate controller post
    -...
    -      create  app/controllers/post_controller.rb
    -      create  test/functional/post_controller_test.rb
    -...
    --------------------------------------------------------
    -
    -Now if you take a look at the file +posts_controller_test.rb+ in the +test/functional+ directory, you should see:
    -
    -[source,ruby]
    ---------------------------------------------------
    -require 'test_helper'
    -
    -class PostsControllerTest < ActionController::TestCase
    -  # Replace this with your real tests.
    -  def test_truth
    -    assert true
    -  end
    -end
    ---------------------------------------------------
    +Now that we have used Rails scaffold generator for our +Post+ resource, it has already created the controller code and functional tests. You can take look at the file +posts_controller_test.rb+ in the +test/functional+ directory.
     
    -Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:
    +Let me take you through one such test, +test_should_get_index+ from the file +posts_controller_test.rb+.
     
     [source,ruby]
     --------------------------------------------------
    @@ -513,6 +503,23 @@ Another example: Calling the +:view+ action, passing an +id+ of 12 as the +param
     get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
     --------------------------------------------------
     
    +NOTE: If you try running +test_should_create_post+ test from +posts_controller_test.rb+ it will fail on account of the newly added model level validation and rightly so.
    +
    +Let us modify +test_should_create_post+ test in +posts_controller_test.rb+ so that all our test pass:
    +
    +[source,ruby]
    +--------------------------------------------------
    +def test_should_create_post
    +  assert_difference('Post.count') do
    +    post :create, :post => { :title => 'Some title'}
    +  end
    +
    +  assert_redirected_to post_path(assigns(:post))
    +end
    +--------------------------------------------------
    +
    +Now you can try running all the tests and they should pass.
    +
     === Available Request Types for Functional Tests ===
     
     If you're familiar with the HTTP protocol, you'll know that +get+ is a type of request. There are 5 request types supported in Rails functional tests:
    @@ -756,6 +763,130 @@ class UserFlowsTest < ActionController::IntegrationTest
     end
     --------------------------------------------------
     
    +== Rake Tasks for Running your Tests ==
    +
    +You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
    +
    +[grid="all"]
    +--------------------------------`----------------------------------------------------
    +Tasks                           Description
    +------------------------------------------------------------------------------------
    ++rake test+                     Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
    ++rake test:units+               Runs all the unit tests from +test/unit+
    ++rake test:functionals+         Runs all the functional tests from +test/functional+
    ++rake test:integration+         Runs all the integration tests from +test/integration+
    ++rake test:recent+              Tests recent changes
    ++rake test:uncommitted+         Runs all the tests which are uncommitted. Only supports Subversion
    ++rake test:plugins+             Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
    +------------------------------------------------------------------------------------
    +
    +
    +== Brief Note About Test::Unit ==
    +
    +Ruby ships with a boat load of libraries. One little gem of a library is +Test::Unit+, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in +Test::Unit::Assertions+. The class +ActiveSupport::TestCase+ which we have been using in our unit and functional tests extends +Test::Unit::TestCase+ that it is how we can use all the basic assertions in our tests.
    +
    +NOTE: For more information on +Test::Unit+, refer to link:http://ruby-doc.org/stdlib/libdoc/test/unit/rdoc/[test/unit Documentation]
    +
    +== Setup and Teardown ==
    +
    +If you would like to run a block of code before the start of each test and another block of code after the end of each test you have two special callbacks for your rescue. Let's take note of this by looking at an example for our functional test in +Posts+ controller:
    +
    +[source,ruby]
    +--------------------------------------------------
    +require 'test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  def setup
    +    @post = posts(:one)
    +  end
    +
    +  # called after every single test
    +  def teardown
    +    # as we are re-initializing @post before every test
    +    # setting it to nil here is not essential but I hope 
    +    # you understand how you can use the teardown method
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +  
    +end
    +--------------------------------------------------
    +
    +Above, the +setup+ method is called before each test and so +@post+ is available for each of the tests. Rails implements +setup+ and +teardown+ as ActiveSupport::Callbacks. Which essentially means you need not only use +setup+ and +teardown+ as methods in your tests. You could specify them by using:
    +
    + * a block
    + * a method (like in the earlier example)
    + * a method name as a symbol
    + * a lambda
    + 
    +Let's see the earlier example by specifying +setup+ callback by specifying a method name as a symbol:
    +
    +[source,ruby]
    +--------------------------------------------------
    +require '../test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  setup :initialize_post
    +
    +  # called after every single test
    +  def teardown
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +  
    +  def test_should_update_post
    +    put :update, :id => @post.id, :post => { }
    +    assert_redirected_to post_path(assigns(:post))
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +  
    +  private 
    +  
    +  def initialize_post
    +    @post = posts(:one)
    +  end
    +  
    +end
    +--------------------------------------------------
    +
    +== Testing Routes ==
    +
    +Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default +show+ action of +Posts+ controller above should look like:
    +
    +[source,ruby]
    +--------------------------------------------------
    +def test_should_route_to_post
    +  assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
    +end
    +--------------------------------------------------
    +
     == Testing Your Mailers ==
     
     Testing mailer classes requires some specific tools to do a thorough job.
    @@ -845,30 +976,6 @@ class UserControllerTest < ActionController::TestCase
     end
     ----------------------------------------------------------------
     
    -== Rake Tasks for Testing
    -
    -You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.
    -
    -[grid="all"]
    ---------------------------------`----------------------------------------------------
    -Tasks                           Description
    -------------------------------------------------------------------------------------
    -+rake test+                     Runs all unit, functional and integration tests. You can also simply run +rake+ as the _test_ target is the default.
    -+rake test:units+               Runs all the unit tests from +test/unit+
    -+rake test:functionals+         Runs all the functional tests from +test/functional+
    -+rake test:integration+         Runs all the integration tests from +test/integration+
    -+rake test:recent+              Tests recent changes
    -+rake test:uncommitted+         Runs all the tests which are uncommitted. Only supports Subversion
    -+rake test:plugins+             Run all the plugin tests from +vendor/plugins/*/**/test+ (or specify with +PLUGIN=_name_+)
    -+rake db:test:clone+            Recreate the test database from the current environment's database schema
    -+rake db:test:clone_structure+  Recreate the test databases from the development structure
    -+rake db:test:load+             Recreate the test database from the current +schema.rb+
    -+rake db:test:prepare+          Check for pending migrations and load the test schema
    -+rake db:test:purge+            Empty the test database.
    -------------------------------------------------------------------------------------
    -
    -TIP: You can see all these rake task and their descriptions by running +rake --tasks --describe+
    -
     == Other Testing Approaches
     
     The built-in +test/unit+ based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:
    @@ -882,6 +989,7 @@ The built-in +test/unit+ based testing is not the only way to test Rails applica
     
     http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/8[Lighthouse ticket]
     
    +* November 13, 2008: Revised based on feedback from Pratik Naik by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
     * October 14, 2008: Edit and formatting pass by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication)
    -* October 12, 2008: First draft by link:../authors.html#asurve[Akashay Surve] (not yet approved for publication)
    +* October 12, 2008: First draft by link:../authors.html#asurve[Akshay Surve] (not yet approved for publication)
     
    -- 
    cgit v1.2.3
    
    
    From bc75de8e4f60a774423290872aeb25d09561531b Mon Sep 17 00:00:00 2001
    From: Jeff Dean 
    Date: Thu, 13 Nov 2008 00:51:54 -0500
    Subject: Plugin Guide: updated core_extensions section
    
    ---
     .../html/activerecord_validations_callbacks.html   |   2 +-
     railties/doc/guides/html/command_line.html         | 434 +++++++++++++++++
     railties/doc/guides/html/creating_plugins.html     | 151 +++---
     railties/doc/guides/html/routing_outside_in.html   |   2 +-
     .../guides/html/testing_rails_applications.html    | 541 +++++++++++++--------
     .../guides/source/creating_plugins/core_ext.txt    | 126 +++++
     .../doc/guides/source/creating_plugins/index.txt   |   4 +-
     .../source/creating_plugins/odds_and_ends.txt      |  34 --
     .../guides/source/creating_plugins/preparation.txt | 222 ---------
     .../source/creating_plugins/string_to_squawk.txt   | 102 ----
     .../guides/source/creating_plugins/test_setup.txt  | 222 +++++++++
     11 files changed, 1191 insertions(+), 649 deletions(-)
     create mode 100644 railties/doc/guides/html/command_line.html
     create mode 100644 railties/doc/guides/source/creating_plugins/core_ext.txt
     delete mode 100644 railties/doc/guides/source/creating_plugins/preparation.txt
     delete mode 100644 railties/doc/guides/source/creating_plugins/string_to_squawk.txt
     create mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt
    
    diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html
    index 45eec6ffa1..0aa507a9b9 100644
    --- a/railties/doc/guides/html/activerecord_validations_callbacks.html
    +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html
    @@ -726,7 +726,7 @@ by Lorenzo Bettini
     http://www.lorenzobettini.it
     http://www.gnu.org/software/src-highlite -->
     
    class Invoice < ActiveRecord::Base
    -  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_be_more_than_total_value
    +  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
     
       def expiration_date_cannot_be_in_the_past
         errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
    diff --git a/railties/doc/guides/html/command_line.html b/railties/doc/guides/html/command_line.html
    new file mode 100644
    index 0000000000..2add20446e
    --- /dev/null
    +++ b/railties/doc/guides/html/command_line.html
    @@ -0,0 +1,434 @@
    +
    +
    +
    +	
    +	A Guide to The Rails Command Line
    +	
    +	
    +	
    +	
    +	
    +
    +
    +	
    +
    +	
    + + + +
    +

    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.

    +
    +
    +

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

    +

    1.1. 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.
    +
    +
    +
    +
    $ 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!
    +
    +

    1.2. server

    +

    Let's try it! The server command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser.

    +
    + + + +
    +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:

    +
    +
    +
    $ 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.

    +

    1.3. generate

    +

    The generate command uses templates to create a whole lot of things. You can always find out what's available by running generate by itself. Let's do that:

    +
    +
    +
    $ ./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.
    +
    +
    +
    +
    $ ./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.

    +
    +
    +
    $ ./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/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 97e14965a5..bbb4719b0f 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -213,7 +213,16 @@ ul#navMain {
  • - Add a to_squawk method to String + Extending core classes +
  • Add an acts_as_yaffle method to ActiveRecord @@ -234,8 +243,6 @@ ul#navMain { Odds and ends
  • Now you are ready to test-drive your plugin!

    -

    2. Add a to_squawk method to String

    +

    2. Extending core classes

    -

    To update a core class you will have to:

    +

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

    • -Write tests for the desired functionality. -

      -
    • -
    • -

      -Create a file for the code you wish to use. +Writing tests for the desired behavior

    • -Require that file from your init.rb. +Creating and requiring the correct files

    -

    Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is lib/core_ext.rb.

    -

    First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:

    -

    vendor/plugins/yaffle/test/core_ext_test.rb

    +

    2.1. Working with init.rb

    +

    When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    +

    Under certain circumstances if you reopen classes or modules in init.rb itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb.

    +

    If you must reopen a class in init.rb you can use module_eval or class_eval:

    +

    vendor/plugins/yaffle/init.rb

    -
    require 'test/unit'
    -
    -class CoreExtTest < Test::Unit::TestCase
    -  # Replace this with your real tests.
    -  def test_this_plugin
    -    flunk
    +
    Hash.class_eval do
    +  def is_a_special_hash?
    +    true
       end
     end
     
    -

    Start off by removing the default test, and adding a require statement for your test helper.

    +

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

    +

    vendor/plugins/yaffle/init.rb

    +
    +
    +
    class ::Hash
    +  def is_a_special_hash?
    +    true
    +  end
    +end
    +
    +

    2.2. Creating the test

    +

    In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:

    vendor/plugins/yaffle/test/core_ext_test.rb

    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:

    @@ -638,42 +656,45 @@ http://www.gnu.org/software/src-highlite -->
    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:

    +

    The test above should fail with the message:

    -
    1.) Failure ...
    -No tests were specified
    +
     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. The first thing we'll do is to add a method to String called to_squawk which will prefix the string with the word “squawk!”. The test will look something like this:

    +

    Great - now you are ready to start development.

    +

    2.3. Organize your files

    +

    A common pattern in rails plugins is to set up the file structure something like this:

    +
    +
    +
    |-- init.rb
    +|-- lib
    +|   |-- yaffle
    +|   |   `-- core_ext.rb
    +|   `-- yaffle.rb
    +
    +

    The first thing we need to to is to require our lib/yaffle.rb file from init.rb:

    vendor/plugins/yaffle/init.rb

    -
    class CoreExtTest < Test::Unit::TestCase
    -  def test_string_should_respond_to_squawk
    -    assert_equal true, "".respond_to?(:to_squawk)
    -  end
    -
    -  def test_string_prepend_empty_strings_with_the_word_squawk
    -    assert_equal "squawk!", "".to_squawk
    -  end
    -
    -  def test_string_prepend_non_empty_strings_with_the_word_squawk
    -    assert_equal "squawk! Hello World", "Hello World".to_squawk
    -  end
    -end
    +
    require 'yaffle'
     
    -

    vendor/plugins/yaffle/init.rb

    +

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

    +

    vendor/plugins/yaffle/lib/yaffle.rb

    -
    require "core_ext"
    +
    require "yaffle/core_ext"
     
    -

    vendor/plugins/yaffle/lib/core_ext.rb

    +

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

    +

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

    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:

    +

    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"
    -

    If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.

    3. Add an acts_as_yaffle method to ActiveRecord

    @@ -1230,37 +1249,7 @@ http://www.gnu.org/software/src-highlite -->

    8. Odds and ends

    -

    8.1. Work with init.rb

    -

    The plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    -

    If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in init.rb, and it makes the plugin more difficult to turn into a gem.

    -

    A better alternative is to reopen the class in a different file, and require that file from init.rb.

    -

    If you must reopen a class in init.rb, there are various techniques. One way is to use module_eval or class_eval:

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    Hash.class_eval do
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

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

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    class ::Hash
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

    8.2. Generate RDoc Documentation

    +

    8.1. Generate RDoc Documentation

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

      @@ -1292,7 +1281,7 @@ Warning, gotchas or tips that might help save users time.
      rake rdoc
    -

    8.3. Store models, views, helpers, and controllers in your plugins

    +

    8.2. Store models, views, helpers, and controllers in your plugins

    You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:

    Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.

    Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.

    -

    8.4. Write custom Rake tasks in your plugin

    +

    8.3. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    vendor/plugins/yaffle/tasks/yaffle.rake

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

    -

    8.5. Store plugins in alternate locations

    +

    8.4. 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!

    @@ -1343,9 +1332,9 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
     
    -

    8.6. Create your own Plugin Loaders and Plugin Locators

    +

    8.5. Create your own Plugin Loaders and Plugin Locators

    If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.

    -

    8.7. Use Custom Plugin Generators

    +

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

    9. Appendix

    diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index 8add4e7789..947d0836ce 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -1448,7 +1448,7 @@ http://www.gnu.org/software/src-highlite -->
    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 :accept options.

    +

    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.

    diff --git a/railties/doc/guides/html/testing_rails_applications.html b/railties/doc/guides/html/testing_rails_applications.html index 666d1dff85..b8a99767ee 100644 --- a/railties/doc/guides/html/testing_rails_applications.html +++ b/railties/doc/guides/html/testing_rails_applications.html @@ -202,7 +202,7 @@ ul#navMain { Why Write Tests for your Rails Applications?
  • - Before you Start Writing Tests + Introduction to Testing
  • - Unit Testing Your Models + Unit Testing your Models
  • + Rake Tasks for Running your Tests +
  • +
  • + Brief Note About Test::Unit +
  • +
  • + Setup and Teardown +
  • +
  • + Testing Routes +
  • +
  • Testing Your Mailers
      @@ -268,9 +282,6 @@ ul#navMain {
  • - Rake Tasks for Testing -
  • -
  • Other Testing Approaches
  • @@ -309,12 +320,7 @@ Identify other popular testing approaches and plugins
    • -Because Ruby code that you write in your Rails application is interpreted, you may only find that it's broken when you actually run your application server and use it through the browser. Writing tests is a clean way of running through your code in advance and catching syntactical and logic errors. -

      -
    • -
    • -

      -Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser. +Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers.

    • @@ -324,16 +330,16 @@ By simply running your Rails tests you can ensure your code adheres to the desir
    • -Rails makes it super easy to write your tests. It starts by producing skeleton test code in background while you are creating your models and controllers. +Rails tests can also simulate browser requests and thus you can test your application's response without having to test it through your browser.

    -

    2. Before you Start Writing Tests

    +

    2. Introduction to Testing

    -

    Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.

    +

    Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. Just about every Rails application interacts heavily with a database - and, as a result, your tests will need a database to interact with as well. To write efficient tests, you'll need to understand how to set up this database and populate it with sample data.

    2.1. The 3 Environments

    -

    Testing support was woven into the Rails fabric from the beginning. It wasn't an "oh! let's bolt on support for running tests because they're new and cool" epiphany. One of the consequences of this design decision is that every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.

    +

    Every Rails application you build has 3 sides: a side for production, a side for development, and a side for testing.

    One place you'll find this distinction is in the config/database.yml file. This YAML configuration file has 3 different sections defining 3 unique database setups:

    • @@ -370,9 +376,9 @@ fixtures/ functional2.3. The Low-Down on Fixtures

      For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures.

      2.3.1. What Are Fixtures?

      -

      Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV.

      +

      Fixtures is a fancy word for sample data. Fixtures allow you to populate your testing database with predefined data before your tests run. Fixtures are database independent and assume one of two formats: YAML or CSV. In this guide we will use YAML which is the preferred format.

      You'll find fixtures under your test/fixtures directory. When you run script/generate model to create a new model, fixture stubs will be automatically created and placed in this directory.

      -

      2.3.2. YAML the Camel is a Mammal with Enamel

      +

      2.3.2. YAML

      YAML-formatted fixtures are a very human-friendly way to describe your sample data. These types of fixtures have the .yml file extension (as in users.yml).

      Here's a sample YAML fixture file:

      @@ -382,78 +388,18 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
      # low & behold!  I am a YAML comment!
       david:
      - id: 1
        name: David Heinemeier Hansson
        birthday: 1979-10-15
        profession: Systems development
       
       steve:
      - id: 2
        name: Steve Ross Kellock
        birthday: 1974-09-27
        profession: guy with keyboard
       

    Each fixture is given a name followed by an indented list of colon-separated key/value pairs. Records are separated by a blank space. You can place comments in a fixture file by using the # character in the first column.

    -

    2.3.3. Comma Seperated

    -

    Fixtures can also be described using the all-too-familiar comma-separated value (CSV) file format. These files, just like YAML fixtures, are placed in the test/fixtures directory, but these end with the .csv file extension (as in celebrity_holiday_figures.csv).

    -

    A CSV fixture looks like this:

    -
    -
    -
    id, username, password, stretchable, comments
    -1, sclaus, ihatekids, false, I like to say ""Ho! Ho! Ho!""
    -2, ebunny, ihateeggs, true, Hoppity hop y'all
    -3, tfairy, ilovecavities, true, "Pull your teeth, I will"
    -
    -

    The first line is the header. It is a comma-separated list of fields. The rest of the file is the payload: 1 record per line. A few notes about this format:

    -
      -
    • -

      -Leading and trailing spaces are trimmed from each value when it is imported -

      -
    • -
    • -

      -If you use a comma as data, the cell must be encased in quotes -

      -
    • -
    • -

      -If you use a quote as data, you must escape it with a 2nd quote -

      -
    • -
    • -

      -Don't use blank lines -

      -
    • -
    • -

      -Nulls can be defined by including no data between a pair of commas -

      -
    • -
    -

    Unlike the YAML format where you give each record in a fixture a name, CSV fixture names are automatically generated. They follow a pattern of "model-name-counter". In the above example, you would have:

    -
      -
    • -

      -celebrity-holiday-figures-1 -

      -
    • -
    • -

      -celebrity-holiday-figures-2 -

      -
    • -
    • -

      -celebrity-holiday-figures-3 -

      -
    • -
    -

    The CSV format is great to use if you have existing data in a spreadsheet or database and you are able to save it (or export it) as a CSV.

    -

    2.3.4. ERb'in It Up

    +

    2.3.3. ERb'in It Up

    ERb allows you embed ruby code within templates. Both the YAML and CSV fixture formats are pre-processed with ERb when you load fixtures. This allows you to use Ruby to help you generate some sample data.

    -

    I'll demonstrate with a YAML file:

    <% 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

    @@ -480,8 +426,8 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    <% %>
     
    -

    tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively.

    -

    2.3.5. Fixtures in Action

    +

    tag is considered Ruby code. When this fixture is loaded, the size attribute of the three records will be set to 20/50, 20/2, and 20-69 respectively. The brightest_on attribute will also be evaluated and formatted by Rails to be compatible with the database.

    +

    2.3.4. Fixtures in Action

    Rails by default automatically loads all fixtures from the test/fixtures folder for your unit and functional test. Loading involves three steps:

    • @@ -500,7 +446,7 @@ Dump the fixture data into a variable in case you want to access it directly

    -

    2.3.6. Hashes with Special Powers

    +

    2.3.5. Hashes with Special Powers

    Fixtures are basically Hash objects. As mentioned in point #3 above, you can access the hash object directly because it is automatically setup as a local variable of the test case. For example:

    +
    $ rake db:migrate
    +...
    +$ rake db:test:load
    +
    +

    Above rake db:migrate runs any pending migrations on the developemnt environment and updates db/schema.rb. rake db:test:load recreates the test database from the current db/schema.rb. On subsequent attempts it is a good to first run db:test:prepare as it first checks for pending migrations and warns you appropriately.

    +
    + + + +
    +Note +db:test:prepare will fail with an error if db/schema.rb doesn't exists.
    +
    +

    3.1.1. Rake Tasks for Preparing you Application for Testing ==

    +

    --------------------------------`---------------------------------------------------- +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
    +
    +

    3.2. Running Tests

    Running a test is as simple as invoking the file containing the test cases through Ruby:

    -
    def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post
    +
    def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save
     end
     
    -

    If you haven't added any data to the test fixture for posts, this test will fail. You can see this by running it:

    +

    Let us run this newly added test.

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.027274 seconds.
    +F
    +Finished in 0.197094 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:12:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -<nil> expected to not be nil.
    +<false> is not true.
     
    -2 tests, 2 assertions, 1 failures, 0 errors
    +1 tests, 1 assertions, 1 failures, 0 errors

    In the output, F denotes a failure. You can see the corresponding trace shown under 1) along with the name of the failing test. The next few lines contain the stack trace followed by a message which mentions the actual value and the expected value by the assertion. The default assertion messages provide just enough information to help pinpoint the error. To make the assertion failure message more readable every assertion provides an optional message parameter, as shown here:

    @@ -677,30 +670,60 @@ test_should_have_atleast_one_post(PostTest) by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    def test_should_have_atleast_one_post
    -  post = Post.find(:first)
    -  assert_not_nil post, "Should not be nil as Posts table should have atleast one post"
    +
    def test_should_not_save_post_without_title
    +  post = Post.new
    +  assert !post.save, "Saved the post without a title"
     end
     

    Running this test shows the friendlier assertion message:

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_not_save_post_without_title
     Loaded suite unit/post_test
     Started
    -F.
    -Finished in 0.024727 seconds.
    +F
    +Finished in 0.198093 seconds.
     
       1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    +test_should_not_save_post_without_title(PostTest)
    +    [unit/post_test.rb:11:in `test_should_not_save_post_without_title'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
          /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    -<nil> expected to not be nil.
    +Saved the post without a title.
    +<false> is not true.
    +
    +1 tests, 1 assertions, 1 failures, 0 errors
    +
    +

    Now to get this test to pass we can add a model level validation for the title field.

    +
    +
    +
    class Post < ActiveRecord::Base
    +  validates_presence_of :title
    +end
    +
    +

    Now the test should pass. Let us verify by running the test again:

    +
    +
    +
    $ 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 15 TDD steps to create a Rails application.
    +

    To see how an error gets reported, here's a test containing an error:

    Now you can see even more output in the console from running the tests:

    -
    $ ruby unit/post_test.rb
    +
    $ ruby unit/post_test.rb -n test_should_report_error
     Loaded suite unit/post_test
     Started
    -FE.
    -Finished in 0.108389 seconds.
    +E
    +Finished in 0.195757 seconds.
     
    -  1) Failure:
    -test_should_have_atleast_one_post(PostTest)
    -    [unit/post_test.rb:11:in `test_should_have_atleast_one_post'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
    -     /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run']:
    -Should not be nil as Posts table should have atleast one post.
    -<nil> expected to not be nil.
    -
    -  2) Error:
    +  1) Error:
     test_should_report_error(PostTest):
    -NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x304a7b0>
    +NameError: undefined local variable or method `some_undefined_variable' for #<PostTest:0x2cc9de8>
         /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.1/lib/action_controller/test_process.rb:467:in `method_missing'
    -    unit/post_test.rb:15:in `test_should_report_error'
    +    unit/post_test.rb:16:in `test_should_report_error'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `__send__'
         /opt/local/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/testing/setup_and_teardown.rb:33:in `run'
     
    -3 tests, 2 assertions, 1 failures, 1 errors
    +1 tests, 0 assertions, 0 failures, 1 errors

    Notice the E in the output. It denotes a test with error.

    @@ -749,17 +764,9 @@ NameError: undefined local variable or method `some_undefined_variable' for #<
  • The execution of each test method stops as soon as any error or a assertion failure is encountered, and the test suite continues with the next method. All test methods are executed in alphabetical order.
    -

    3.2. What to Include in Your Unit Tests

    +

    3.3. What to Include in Your Unit Tests

    Ideally you would like to include a test for everything which could possibly break. It's a good practice to have at least one test for each of your validations and at least one test for every method in your model.

    -
    - - - -
    -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 15 TDD steps to create a Rails application.
    -
    -

    3.3. Assertions Available

    +

    3.4. Assertions Available

    By now you've caught a glimpse of some of the assertions that are available. Assertions are the worker bees of testing. They are the ones that actually perform the checks to ensure that things are going as planned.

    There are a bunch of different types of assertions you can use. Here's the complete list of assertions that ship with test/unit, the testing library used by Rails. The [msg] parameter is an optional string message you can specify to make your test failure messages clearer. It's not required.

    @@ -943,7 +950,7 @@ cellspacing="0" cellpadding="4"> Creating your own assertions is an advanced topic that we won't cover in this tutorial.
    -

    3.4. Rails Specific Assertions

    +

    3.5. Rails Specific Assertions

    Rails adds some custom assertions of its own to the test/unit framework:

    -

    When you use script/generate to create a controller, it automatically creates a functional test for that controller in test/functional. For example, if you create a post controller:

    -
    -
    -
    $ 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:

    -
    -
    -
    require 'test_helper'
    -
    -class PostsControllerTest < ActionController::TestCase
    -  # Replace this with your real tests.
    -  def test_truth
    -    assert true
    -  end
    -end
    -
    -

    Of course, you need to replace the simple assertion with real testing. Here's a starting example of a functional test:

    +

    Now that we have used Rails scaffold generator for our Post resource, it has already created the controller code and functional tests. You can take look at the file posts_controller_test.rb in the test/functional directory.

    +

    Let me take you through one such test, test_should_get_index from the file posts_controller_test.rb.

    get(:view, {'id' => '12'}, nil, {'message' => 'booya!'})
     
    +
    +
    + + +
    +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:

    +
    +
    +
    def test_should_create_post
    +  assert_difference('Post.count') do
    +    post :create, :post => { :title => 'Some title'}
    +  end
    +
    +  assert_redirected_to post_path(assigns(:post))
    +end
    +
    +

    Now you can try running all the tests and they should pass.

    4.2. Available Request Types for Functional Tests

    If you're familiar with the HTTP protocol, you'll know that get is a type of request. There are 5 request types supported in Rails functional tests:

      @@ -1564,10 +1568,159 @@ http://www.gnu.org/software/src-highlite --> end
    -

    6. Testing Your Mailers

    +

    6. Rake Tasks for Running your Tests

    +
    +

    You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.

    +

    --------------------------------`---------------------------------------------------- +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_+)
    +
    +
    +

    7. Brief Note About Test::Unit

    +
    +

    Ruby ships with a boat load of libraries. One little gem of a library is Test::Unit, a framework for unit testing in Ruby. All the basic assertions discussed above are actually defined in Test::Unit::Assertions. The class ActiveSupport::TestCase which we have been using in our unit and functional tests extends Test::Unit::TestCase that it is how we can use all the basic assertions in our tests.

    +
    + + + +
    +Note +For more information on Test::Unit, refer to test/unit Documentation
    +
    +
    +

    8. 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:

    +
    +
    +
    require 'test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  def setup
    +    @post = posts(:one)
    +  end
    +
    +  # called after every single test
    +  def teardown
    +    # as we are re-initializing @post before every test
    +    # setting it to nil here is not essential but I hope
    +    # you understand how you can use the teardown method
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +
    +end
    +
    +

    Above, the setup method is called before each test and so @post is available for each of the tests. Rails implements setup and teardown as ActiveSupport::Callbacks. Which essentially means you need not only use setup and teardown as methods in your tests. You could specify them by using:

    +
      +
    • +

      +a block +

      +
    • +
    • +

      +a method (like in the earlier example) +

      +
    • +
    • +

      +a method name as a symbol +

      +
    • +
    • +

      +a lambda +

      +
    • +
    +

    Let's see the earlier example by specifying setup callback by specifying a method name as a symbol:

    +
    +
    +
    require '../test_helper'
    +
    +class PostsControllerTest < ActionController::TestCase
    +
    +  # called before every single test
    +  setup :initialize_post
    +
    +  # called after every single test
    +  def teardown
    +    @post = nil
    +  end
    +
    +  def test_should_show_post
    +    get :show, :id => @post.id
    +    assert_response :success
    +  end
    +
    +  def test_should_update_post
    +    put :update, :id => @post.id, :post => { }
    +    assert_redirected_to post_path(assigns(:post))
    +  end
    +
    +  def test_should_destroy_post
    +    assert_difference('Post.count', -1) do
    +      delete :destroy, :id => @post.id
    +    end
    +
    +    assert_redirected_to posts_path
    +  end
    +
    +  private
    +
    +  def initialize_post
    +    @post = posts(:one)
    +  end
    +
    +end
    +
    +
    +

    9. Testing Routes

    +
    +

    Like everything else in you Rails application, it's recommended to test you routes. An example test for a route in the default show action of Posts controller above should look like:

    +
    +
    +
    def test_should_route_to_post
    +  assert_routing '/posts/1', { :controller => "posts", :action => "show", :id => "1" }
    +end
    +
    +
    +

    10. Testing Your Mailers

    Testing mailer classes requires some specific tools to do a thorough job.

    -

    6.1. Keeping the Postman in Check

    +

    10.1. Keeping the Postman in Check

    Your ActionMailer classes — like every other part of your Rails application — should be tested to ensure that it is working as expected.

    The goals of testing your ActionMailer classes are to ensure that:

      @@ -1587,14 +1740,14 @@ the right emails are being sent at the right times

    -

    6.1.1. From All Sides

    +

    10.1.1. From All Sides

    There are two aspects of testing your mailer, the unit tests and the functional tests. In the unit tests, you run the mailer in isolation with tightly controlled inputs and compare the output to a knownvalue (a fixture — yay! more fixtures!). In the functional tests you don't so much test the minute details produced by the mailer Instead we test that our controllers and models are using the mailer in the right way. You test to prove that the right email was sent at the right time.

    -

    6.2. Unit Testing

    +

    10.2. Unit Testing

    In order to test that your mailer is working as expected, you can use unit tests to compare the actual results of the mailer with pre-written examples of what should be produced.

    -

    6.2.1. Revenge of the Fixtures

    +

    10.2.1. Revenge of the Fixtures

    For the purposes of unit testing a mailer, fixtures are used to provide an example of how the output should look. Because these are example emails, and not Active Record data like the other fixtures, they are kept in their own subdirectory apart from the other fixtures. The name of the directory within test/fixtures directly corresponds to the name of the mailer. So, for a mailer named UserMailer, the fixtures should reside in test/fixtures/user_mailer directory.

    When you generated your mailer, the generator creates stub fixtures for each of the mailers actions. If you didn't use the generator you'll have to make those files yourself.

    -

    6.2.2. The Basic Test case

    +

    10.2.2. The Basic Test case

    Here's a unit test to test a mailer named UserMailer whose action invite is used to send an invitation to a friend. It is an adapted version of the base test created by the generator for an invite action.

    end
    -

    7. Rake Tasks for Testing

    -
    -

    You don't need to set up and run your tests by hand on a test-by-test basis. Rails comes with a number of rake tasks to help in testing. The table below lists all rake tasks that come along in the default Rakefile when you initiate a Rail project.

    -

    --------------------------------`---------------------------------------------------- -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
    -
    -
    -

    8. Other Testing Approaches

    +

    11. Other Testing Approaches

    The built-in test/unit based testing is not the only way to test Rails applications. Rails developers have come up with a wide variety of other approaches and aids for testing, including:

      @@ -1707,18 +1831,23 @@ link: RSpec, a behavior-driven development fram
    -

    9. Changelog

    +

    12. Changelog

    • +November 13, 2008: Revised based on feedback from Pratik Naik by Akshay Surve (not yet approved for publication) +

      +
    • +
    • +

      October 14, 2008: Edit and formatting pass by Mike Gunderloy (not yet approved for publication)

    • -October 12, 2008: First draft by Akashay Surve (not yet approved for publication) +October 12, 2008: First draft by Akshay Surve (not yet approved for publication)

    diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt new file mode 100644 index 0000000000..33d3dc8ce7 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -0,0 +1,126 @@ +== Extending core classes == + +This section will explain how to add a method to String that will be available anywhere in your rails app by: + + * Writing tests for the desired behavior + * Creating and requiring the correct files + + +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`. + +If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +=== Creating the test === + +In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: + +*vendor/plugins/yaffle/test/core_ext_test.rb* + +[source, ruby] +-------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class CoreExtTest < Test::Unit::TestCase + def test_to_squawk_prepends_the_word_squawk + assert_equal "squawk! Hello World", "Hello World".to_squawk + end +end +-------------------------------------------------------- + +Navigate to your plugin directory and run `rake test`: + +-------------------------------------------------------- +cd vendor/plugins/yaffle +rake test +-------------------------------------------------------- + +The test above should fail with the message: + +-------------------------------------------------------- + 1) Error: +test_to_squawk_prepends_the_word_squawk(CoreExtTest): +NoMethodError: undefined method `to_squawk' for "Hello World":String + ./test/core_ext_test.rb:5:in `test_to_squawk_prepends_the_word_squawk' +-------------------------------------------------------- + +Great - now you are ready to start development. + +=== Organize your files === + +A common pattern in rails plugins is to set up the file structure something like this: + +-------------------------------------------------------- +|-- init.rb +|-- lib +| |-- yaffle +| | `-- core_ext.rb +| `-- yaffle.rb +-------------------------------------------------------- + +The first thing we need to to is to require our 'lib/yaffle.rb' file from 'init.rb': + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +-------------------------------------------------------- +require "yaffle/core_ext" +-------------------------------------------------------- + +Finally, create the 'core_ext.rb' file and add the 'to_squawk' method: + +*vendor/plugins/yaffle/lib/yaffle/core_ext.rb* + +[source, ruby] +-------------------------------------------------------- +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +-------------------------------------------------------- + +To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking: + +-------------------------------------------------------- +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +-------------------------------------------------------- + diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index d3042f8d56..91d7027323 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,9 +29,9 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::preparation.txt[] +include::test_setup.txt[] -include::string_to_squawk.txt[] +include::core_ext.txt[] include::acts_as_yaffle.txt[] diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index 88cd4fe9ed..a52e1c8fdb 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -1,39 +1,5 @@ == Odds and ends == -=== Work with init.rb === - -The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. - -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. As a rule, it's better not to open any classes in `init.rb`, and it makes the plugin more difficult to turn into a gem. - -A better alternative is to reopen the class in a different file, and require that file from `init.rb`. - -If you must reopen a class in `init.rb`, there are various techniques. One way is to use `module_eval` or `class_eval`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Generate RDoc Documentation === Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. diff --git a/railties/doc/guides/source/creating_plugins/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt deleted file mode 100644 index dc9ef6bc29..0000000000 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ /dev/null @@ -1,222 +0,0 @@ -== Preparation == - -=== Create the basic app === - -The examples in this guide require that you have a working rails application. To create a simple rails app execute: - ------------------------------------------------- -gem install rails -rails yaffle_guide -cd yaffle_guide -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -.Editor's note: -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Generate the plugin skeleton === - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin yaffle -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -To get more detailed help on the plugin generator, type `./script/generate plugin`. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: - ----------------------------------------------- -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -You should see the following output: - ----------------------------------------------- -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/tasks -create vendor/plugins/yaffle/test -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib/yaffle.rb -create vendor/plugins/yaffle/tasks/yaffle_tasks.rake -create vendor/plugins/yaffle/test/core_ext_test.rb -create vendor/plugins/yaffle/generators -create vendor/plugins/yaffle/generators/yaffle -create vendor/plugins/yaffle/generators/yaffle/templates -create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb -create vendor/plugins/yaffle/generators/yaffle/USAGE ----------------------------------------------- - - -=== Setup the plugin for testing === - -In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A 'database.yml' file with all of your connection strings. - * A 'schema.rb' file with your table definitions. - * A test helper that sets up the database before your tests. - -*vendor/plugins/yaffle/test/database.yml:* - ----------------------------------------------- -sqlite: - :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: yaffle_plugin_test ----------------------------------------------- - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -*vendor/plugins/yaffle/test/schema.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end -end ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - -db_adapter = ENV['DB'] - -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -end - -ActiveRecord::Base.establish_connection(config[db_adapter]) - -load(File.dirname(__FILE__) + "/schema.rb") - -require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base -end - -class Wickwall < ActiveRecord::Base -end ----------------------------------------------- - -=== Run the plugin tests === - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: - -*vendor/plugins/yaffle/test/yaffle_test.rb:* - -[source, ruby] ----------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class YaffleTest < Test::Unit::TestCase - - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new - end - -end ----------------------------------------------- - -To run this, go to the plugin directory and run `rake`: - ----------------------------------------------- -cd vendor/plugins/yaffle -rake ----------------------------------------------- - -You should see output like: - ----------------------------------------------- -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" --- create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors ----------------------------------------------- - -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: - ----------------------------------------------- -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql ----------------------------------------------- - -Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt deleted file mode 100644 index 63f1131442..0000000000 --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt +++ /dev/null @@ -1,102 +0,0 @@ -== Add a `to_squawk` method to String == - -To update a core class you will have to: - - * Write tests for the desired functionality. - * Create a file for the code you wish to use. - * Require that file from your 'init.rb'. - -Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'. - -First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -require 'test/unit' - -class CoreExtTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end -end --------------------------------------------------------- - -Start off by removing the default test, and adding a require statement for your test helper. - -*vendor/plugins/yaffle/test/core_ext_test.rb* - -[source, ruby] --------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class CoreExtTest < Test::Unit::TestCase -end --------------------------------------------------------- - -Navigate to your plugin directory and run `rake test`: - --------------------------------------------------------- -cd vendor/plugins/yaffle -rake test --------------------------------------------------------- - -Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message: - --------------------------------------------------------- -1.) Failure ... -No tests were specified --------------------------------------------------------- - -Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -class CoreExtTest < Test::Unit::TestCase - def test_string_should_respond_to_squawk - assert_equal true, "".respond_to?(:to_squawk) - end - - def test_string_prepend_empty_strings_with_the_word_squawk - assert_equal "squawk!", "".to_squawk - end - - def test_string_prepend_non_empty_strings_with_the_word_squawk - assert_equal "squawk! Hello World", "Hello World".to_squawk - end -end --------------------------------------------------------- - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -require "core_ext" --------------------------------------------------------- - -*vendor/plugins/yaffle/lib/core_ext.rb* - -[source, ruby] --------------------------------------------------------- -String.class_eval do - def to_squawk - "squawk! #{self}".strip - end -end --------------------------------------------------------- - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - --------------------------------------------------------- -$ ./script/console ->> "Hello World".to_squawk -=> "squawk! Hello World" --------------------------------------------------------- - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt new file mode 100644 index 0000000000..dc9ef6bc29 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -0,0 +1,222 @@ +== Preparation == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +You should see the following output: + +---------------------------------------------- +create vendor/plugins/yaffle/lib +create vendor/plugins/yaffle/tasks +create vendor/plugins/yaffle/test +create vendor/plugins/yaffle/README +create vendor/plugins/yaffle/MIT-LICENSE +create vendor/plugins/yaffle/Rakefile +create vendor/plugins/yaffle/init.rb +create vendor/plugins/yaffle/install.rb +create vendor/plugins/yaffle/uninstall.rb +create vendor/plugins/yaffle/lib/yaffle.rb +create vendor/plugins/yaffle/tasks/yaffle_tasks.rake +create vendor/plugins/yaffle/test/core_ext_test.rb +create vendor/plugins/yaffle/generators +create vendor/plugins/yaffle/generators/yaffle +create vendor/plugins/yaffle/generators/yaffle/templates +create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb +create vendor/plugins/yaffle/generators/yaffle/USAGE +---------------------------------------------- + + +=== Setup the plugin for testing === + +In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. + +To setup your plugin to allow for easy testing you'll need to add 3 files: + + * A 'database.yml' file with all of your connection strings. + * A 'schema.rb' file with your table definitions. + * A test helper that sets up the database before your tests. + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: rails + :password: + :database: yaffle_plugin_test +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) +ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + +db_adapter = ENV['DB'] + +db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + +if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." +end + +ActiveRecord::Base.establish_connection(config[db_adapter]) + +load(File.dirname(__FILE__) + "/schema.rb") + +require File.dirname(__FILE__) + '/../init.rb' + +class Hickwall < ActiveRecord::Base +end + +class Wickwall < ActiveRecord::Base +end +---------------------------------------------- + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + + def test_active_record_classes_from_test_helper + assert_kind_of Hickwall, Hickwall.new + assert_kind_of Wickwall, Wickwall.new + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! -- cgit v1.2.3 From 41d0dbcb8661a866ddf4b3534b8b1efd724ecba1 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 01:44:34 -0500 Subject: Plugin guide: update acts_as section --- railties/doc/guides/html/creating_plugins.html | 207 ++++++++++----------- .../source/creating_plugins/acts_as_yaffle.txt | 121 ++++++------ .../guides/source/creating_plugins/core_ext.txt | 66 ++++--- .../guides/source/creating_plugins/test_setup.txt | 18 +- 4 files changed, 197 insertions(+), 215 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index bbb4719b0f..793cd2b7a7 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -216,16 +216,23 @@ ul#navMain { Extending core classes
  • - Add an acts_as_yaffle method to ActiveRecord + Add an acts_as_yaffle method to Active Record +
  • Create a squawk_info_for view helper @@ -529,12 +536,6 @@ ActiveRecord::Baseload(File.dirname(__FILE__) + "/schema.rb") require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base -end - -class Wickwall < ActiveRecord::Base -end
  • 1.4. Run the plugin tests

    Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:

    @@ -548,9 +549,15 @@ http://www.gnu.org/software/src-highlite --> class YaffleTest < Test::Unit::TestCase - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all end end @@ -605,36 +612,7 @@ Creating and requiring the correct files

    -

    2.1. Working with init.rb

    -

    When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script init.rb is invoked via eval (not require) so it has slightly different behavior.

    -

    Under certain circumstances if you reopen classes or modules in init.rb itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb.

    -

    If you must reopen a class in init.rb you can use module_eval or class_eval:

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    Hash.class_eval do
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

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

    -

    vendor/plugins/yaffle/init.rb

    -
    -
    -
    class ::Hash
    -  def is_a_special_hash?
    -    true
    -  end
    -end
    -
    -

    2.2. Creating the test

    +

    2.1. Creating the test

    In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:

    vendor/plugins/yaffle/test/core_ext_test.rb

    @@ -665,8 +643,8 @@ 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.

    -

    2.3. Organize your files

    -

    A common pattern in rails plugins is to set up the file structure something like this:

    +

    2.2. Organize your files

    +

    A common pattern in rails plugins is to set up the file structure like this:

    |-- init.rb
    @@ -713,11 +691,40 @@ http://www.gnu.org/software/src-highlite -->
     >> "Hello World".to_squawk
     => "squawk! Hello World"
    +

    2.3. Working with init.rb

    +

    When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.

    +

    Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.

    +

    If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:

    +

    vendor/plugins/yaffle/init.rb

    +
    +
    +
    Hash.class_eval do
    +  def is_a_special_hash?
    +    true
    +  end
    +end
    +
    +

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

    +

    vendor/plugins/yaffle/init.rb

    +
    +
    +
    class ::Hash
    +  def is_a_special_hash?
    +    true
    +  end
    +end
    +
    -

    3. Add an acts_as_yaffle method to ActiveRecord

    +

    3. Add an acts_as_yaffle method to Active Record

    -

    A common pattern in plugins is to add a method called acts_as_something to models. In this case, you want to write a method called acts_as_yaffle that adds a squawk method to your models.

    -

    To keep things clean, create a new test file called acts_as_yaffle_test.rb in your plugin's test directory and require your test helper.

    +

    A common pattern in plugins is to add a method called acts_as_something to models. In this case, you want to write a method called acts_as_yaffle that adds a squawk method to your models.

    +

    To begin, set up your files so that you have:

    vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

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

    vendor/plugins/lib/acts_as_yaffle.rb

    +

    vendor/plugins/yaffle/lib/yaffle.rb

    +
    +
    +
    require 'yaffle/acts_as_yaffle'
    +
    +

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

    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:

    -

    vendor/plugins/lib/acts_as_yaffle.rb

    +

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

    +

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

    +

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

    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:

    +

    3.1. Add a class method

    +

    This plugin will expect that you've added a method to your model named last_squawk. However, the plugin users might have already defined a method on their model named last_squawk that they use for something else. This plugin will allow the name to be changed by adding a class method called yaffle_text_field.

    +

    To start out, write a failing test that shows the behavior you'd like:

    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
       def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
         assert_equal "last_squawk", Hickwall.yaffle_text_field
       end
     
    -  def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
    -    assert_equal "last_squawked_at", Hickwall.yaffle_date_field
    -  end
    -
       def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
         assert_equal "last_tweet", Wickwall.yaffle_text_field
       end
    -
    -  def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
    -    assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
    -  end
     end
     

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

    -

    vendor/plugins/yaffle/lib/acts_as_yaffle.rb

    +

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

    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:

    +

    3.2. Add an instance method

    +

    This plugin will add a method named squawk to any Active Record objects that call acts_as_yaffle. The squawk method will simply set the value of one of the fields in the database.

    +

    To start out, write a failing test that shows the behavior you'd like:

    vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

    require File.dirname(__FILE__) + '/test_helper.rb'
     
    -class ActsAsYaffleTest < Test::Unit::TestCase
    +class Hickwall < ActiveRecord::Base
    +  acts_as_yaffle
    +end
     
    +class Wickwall < ActiveRecord::Base
    +  acts_as_yaffle :yaffle_text_field => :last_tweet
    +end
    +
    +class ActsAsYaffleTest < Test::Unit::TestCase
       def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
         assert_equal "last_squawk", Hickwall.yaffle_text_field
       end
    -  def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
    -    assert_equal "last_squawked_at", Hickwall.yaffle_date_field
    -  end
     
    -  def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
    +  def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
         assert_equal "last_tweet", Wickwall.yaffle_text_field
       end
    -  def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
    -    assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
    -  end
     
       def test_hickwalls_squawk_should_populate_last_squawk
         hickwall = Hickwall.new
         hickwall.squawk("Hello World")
         assert_equal "squawk! Hello World", hickwall.last_squawk
       end
    -  def test_hickwalls_squawk_should_populate_last_squawked_at
    -    hickwall = Hickwall.new
    -    hickwall.squawk("Hello World")
    -    assert_equal Date.today, hickwall.last_squawked_at
    -  end
     
    -  def test_wickwalls_squawk_should_populate_last_tweet
    -    wickwall = Wickwall.new
    -    wickwall.squawk("Hello World")
    -    assert_equal "squawk! Hello World", wickwall.last_tweet
    -  end
       def test_wickwalls_squawk_should_populate_last_tweeted_at
         wickwall = Wickwall.new
         wickwall.squawk("Hello World")
    -    assert_equal Date.today, wickwall.last_tweeted_at
    +    assert_equal "squawk! Hello World", wickwall.last_tweet
       end
     end
     
    -

    vendor/plugins/yaffle/lib/acts_as_yaffle.rb

    +

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

    +

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

    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 @@ -903,10 +895,11 @@ http://www.gnu.org/software/src-highlite --> 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
    diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 06878543e4..41ffa61537 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,8 +1,8 @@ -== Add an `acts_as_yaffle` method to ActiveRecord == +== Add an `acts_as_yaffle` method to Active Record == -A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a `squawk` method to your models. +A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. -To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper. +To begin, set up your files so that you have: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -10,25 +10,31 @@ To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end - class ActsAsYaffleTest < Test::Unit::TestCase end ------------------------------------------------------ -*vendor/plugins/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +------------------------------------------------------ +require 'yaffle/acts_as_yaffle' +------------------------------------------------------ + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ module Yaffle + # your code will go here end ------------------------------------------------------ -One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: +Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. + +One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: -*vendor/plugins/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -52,20 +58,11 @@ end With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`). -Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. +=== Add a class method === -Back in your `acts_as_yaffle` file, update ClassMethods like so: +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. -[source, ruby] ------------------------------------------------------- -module ClassMethods - def acts_as_yaffle(options = {}) - send :include, InstanceMethods - end -end ------------------------------------------------------- - -Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: +To start out, write a failing test that shows the behavior you'd like: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -73,28 +70,28 @@ Now that test should pass. Since your plugin is going to work with field names, ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + class ActsAsYaffleTest < Test::Unit::TestCase def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end - - def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end end ------------------------------------------------------ To make these tests pass, you could modify your `acts_as_yaffle` file like so: -*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -105,19 +102,20 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_field self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods end end - - module InstanceMethods - end end + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ -Now you can add tests for the instance methods, and the instance method itself: +=== Add an instance method === + +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. + +To start out, write a failing test that shows the behavior you'd like: *vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* @@ -125,47 +123,40 @@ Now you can add tests for the instance methods, and the instance method itself: ------------------------------------------------------ require File.dirname(__FILE__) + '/test_helper.rb' -class ActsAsYaffleTest < Test::Unit::TestCase +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end +class ActsAsYaffleTest < Test::Unit::TestCase def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_squawk + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end - def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - + def test_hickwalls_squawk_should_populate_last_squawk hickwall = Hickwall.new hickwall.squawk("Hello World") assert_equal "squawk! Hello World", hickwall.last_squawk - end - def test_hickwalls_squawk_should_populate_last_squawked_at - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal Date.today, hickwall.last_squawked_at - end - - def test_wickwalls_squawk_should_populate_last_tweet - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal "squawk! Hello World", wickwall.last_tweet - end + end + def test_wickwalls_squawk_should_populate_last_tweeted_at wickwall = Wickwall.new wickwall.squawk("Hello World") - assert_equal Date.today, wickwall.last_tweeted_at - end + assert_equal "squawk! Hello World", wickwall.last_tweet + end end ------------------------------------------------------ -*vendor/plugins/yaffle/lib/acts_as_yaffle.rb* +Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -176,9 +167,8 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_field self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s send :include, InstanceMethods end end @@ -186,10 +176,11 @@ module Yaffle module InstanceMethods def squawk(string) write_attribute(self.class.yaffle_text_field, string.to_squawk) - write_attribute(self.class.yaffle_date_field, Date.today) end end end + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ .Editor's note: diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index 33d3dc8ce7..9bb7691b83 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -5,39 +5,6 @@ This section will explain how to add a method to String that will be available a * Writing tests for the desired behavior * Creating and requiring the correct files - -=== Working with init.rb === - -When rails loads plugins it looks for the file named init.rb. However, the plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. - -Under certain circumstances if you reopen classes or modules in 'init.rb' itself, you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`. - -If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------- -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Creating the test === In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: @@ -75,7 +42,7 @@ Great - now you are ready to start development. === Organize your files === -A common pattern in rails plugins is to set up the file structure something like this: +A common pattern in rails plugins is to set up the file structure like this: -------------------------------------------------------- |-- init.rb @@ -124,3 +91,34 @@ $ ./script/console => "squawk! Hello World" -------------------------------------------------------- +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. + +Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above. + +If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +Hash.class_eval do + def is_a_special_hash? + true + end +end +--------------------------------------------------- + +Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +--------------------------------------------------- +class ::Hash + def is_a_special_hash? + true + end +end +--------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index dc9ef6bc29..583d058494 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -155,12 +155,6 @@ ActiveRecord::Base.establish_connection(config[db_adapter]) load(File.dirname(__FILE__) + "/schema.rb") require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base -end - -class Wickwall < ActiveRecord::Base -end ---------------------------------------------- === Run the plugin tests === @@ -175,9 +169,15 @@ require File.dirname(__FILE__) + '/test_helper.rb' class YaffleTest < Test::Unit::TestCase - def test_active_record_classes_from_test_helper - assert_kind_of Hickwall, Hickwall.new - assert_kind_of Wickwall, Wickwall.new + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all end end -- cgit v1.2.3 From fbbcd6f29aeccc938b97b5c01717365f8b67912c Mon Sep 17 00:00:00 2001 From: Jeff Cohen Date: Fri, 31 Oct 2008 23:10:44 -0500 Subject: Changed request forgery protection to only worry about HTML-formatted content requests. Signed-off-by: Michael Koziarski --- actionpack/lib/action_controller/mime_type.rb | 4 +- .../request_forgery_protection.rb | 2 +- actionpack/lib/action_controller/test_process.rb | 1 + .../controller/request_forgery_protection_test.rb | 118 ++++++++++++--------- 4 files changed, 70 insertions(+), 55 deletions(-) diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb index 26edca3b69..f43ae721c6 100644 --- a/actionpack/lib/action_controller/mime_type.rb +++ b/actionpack/lib/action_controller/mime_type.rb @@ -19,7 +19,7 @@ module Mime # end # end class Type - @@html_types = Set.new [:html, :all] + @@html_types = Set.new [:html, :url_encoded_form, :multipart_form, :all] @@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml] cattr_reader :html_types, :unverifiable_types @@ -167,7 +167,7 @@ module Mime # Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See # ActionController::RequestForgerProtection. def verify_request? - !@@unverifiable_types.include?(to_sym) + html? end def html? diff --git a/actionpack/lib/action_controller/request_forgery_protection.rb b/actionpack/lib/action_controller/request_forgery_protection.rb index 05a6d8bb79..3e0e94a06b 100644 --- a/actionpack/lib/action_controller/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/request_forgery_protection.rb @@ -99,7 +99,7 @@ module ActionController #:nodoc: end def verifiable_request_format? - request.content_type.nil? || request.content_type.verify_request? + !request.content_type.nil? && request.content_type.verify_request? end # Sets the token value for the current session. Pass a :secret option diff --git a/actionpack/lib/action_controller/test_process.rb b/actionpack/lib/action_controller/test_process.rb index 7a31f0e8d5..1e3a646bc9 100644 --- a/actionpack/lib/action_controller/test_process.rb +++ b/actionpack/lib/action_controller/test_process.rb @@ -395,6 +395,7 @@ module ActionController #:nodoc: @html_document = nil @request.env['REQUEST_METHOD'] ||= "GET" + @request.action = action.to_s parameters ||= {} diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index f7adaa7d4e..5669b8f358 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -77,57 +77,61 @@ module RequestForgeryProtectionTests ActionController::Base.request_forgery_protection_token = nil end + def test_should_render_form_with_token_tag - get :index - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + get :index + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + end + + def test_should_render_button_to_with_token_tag + get :show_button + assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token + end + + def test_should_render_remote_form_with_only_one_token_parameter + get :remote_form + assert_equal 1, @response.body.scan(@token).size + end + + def test_should_allow_get + get :index + assert_response :success + end + + def test_should_allow_post_without_token_on_unsafe_action + post :unsafe + assert_response :success + end + + def test_should_not_allow_html_post_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { post :index, :format => :html } end - def test_should_render_button_to_with_token_tag - get :show_button - assert_select 'form>div>input[name=?][value=?]', 'authenticity_token', @token - end - - def test_should_render_remote_form_with_only_one_token_parameter - get :remote_form - assert_equal 1, @response.body.scan(@token).size - end - - def test_should_allow_get - get :index - assert_response :success + def test_should_not_allow_html_put_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { put :index, :format => :html } end - def test_should_allow_post_without_token_on_unsafe_action - post :unsafe - assert_response :success + def test_should_not_allow_html_delete_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raises(ActionController::InvalidAuthenticityToken) { delete :index, :format => :html } end - def test_should_not_allow_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { post :index } - end - - def test_should_not_allow_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { put :index } - end - - def test_should_not_allow_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { delete :index } - end - - def test_should_not_allow_api_formatted_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + def test_should_allow_api_formatted_post_without_token + assert_nothing_raised do post :index, :format => 'xml' end end def test_should_not_allow_api_formatted_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + assert_nothing_raised do put :index, :format => 'xml' end end - def test_should_not_allow_api_formatted_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) do + def test_should_allow_api_formatted_delete_without_token + assert_nothing_raised do delete :index, :format => 'xml' end end @@ -174,16 +178,20 @@ module RequestForgeryProtectionTests end end - def test_should_not_allow_xhr_post_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :post, :index } + def test_should_allow_xhr_post_without_token + assert_nothing_raised { xhr :post, :index } + end + def test_should_not_allow_xhr_post_with_html_without_token + @request.env['CONTENT_TYPE'] = Mime::URL_ENCODED_FORM.to_s + assert_raise(ActionController::InvalidAuthenticityToken) { xhr :post, :index } end - def test_should_not_allow_xhr_put_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :put, :index } + def test_should_allow_xhr_put_without_token + assert_nothing_raised { xhr :put, :index } end - def test_should_not_allow_xhr_delete_without_token - assert_raises(ActionController::InvalidAuthenticityToken) { xhr :delete, :index } + def test_should_allow_xhr_delete_without_token + assert_nothing_raised { xhr :delete, :index } end def test_should_allow_post_with_token @@ -227,6 +235,7 @@ class RequestForgeryProtectionControllerTest < Test::Unit::TestCase def setup @controller = RequestForgeryProtectionController.new @request = ActionController::TestRequest.new + @request.format = :html @response = ActionController::TestResponse.new class << @request.session def session_id() '123' end @@ -248,11 +257,11 @@ class RequestForgeryProtectionWithoutSecretControllerTest < Test::Unit::TestCase ActionController::Base.request_forgery_protection_token = :authenticity_token end - def test_should_raise_error_without_secret - assert_raises ActionController::InvalidAuthenticityToken do - get :index - end - end + # def test_should_raise_error_without_secret + # assert_raises ActionController::InvalidAuthenticityToken do + # get :index + # end + # end end class CsrfCookieMonsterControllerTest < Test::Unit::TestCase @@ -304,10 +313,15 @@ class SessionOffControllerTest < Test::Unit::TestCase @token = OpenSSL::HMAC.hexdigest(OpenSSL::Digest::Digest.new('SHA1'), 'abc', '123') end - def test_should_raise_correct_exception - @request.session = {} # session(:off) doesn't appear to work with controller tests - assert_raises(ActionController::InvalidAuthenticityToken) do - post :index, :authenticity_token => @token - end - end + # TODO: Rewrite this test. + # This test was passing but for the wrong reason. + # Sessions aren't really being turned off, so an exception was raised + # because sessions weren't on - not because the token didn't match. + # + # def test_should_raise_correct_exception + # @request.session = {} # session(:off) doesn't appear to work with controller tests + # assert_raises(ActionController::InvalidAuthenticityToken) do + # post :index, :authenticity_token => @token, :format => :html + # end + # end end -- cgit v1.2.3 From 00c46b5eeb858629ef1c7ab50f022aecccca42c3 Mon Sep 17 00:00:00 2001 From: rick Date: Wed, 12 Nov 2008 13:34:29 -0800 Subject: fix two MimeType failing test cases Signed-off-by: Michael Koziarski --- actionpack/lib/action_controller/mime_type.rb | 5 ++++- actionpack/test/controller/mime_type_test.rb | 12 ++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb index f43ae721c6..48c4c1ee1e 100644 --- a/actionpack/lib/action_controller/mime_type.rb +++ b/actionpack/lib/action_controller/mime_type.rb @@ -20,8 +20,11 @@ module Mime # end class Type @@html_types = Set.new [:html, :url_encoded_form, :multipart_form, :all] + cattr_reader :html_types + + # UNUSED, deprecate? @@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml] - cattr_reader :html_types, :unverifiable_types + cattr_reader :unverifiable_types # A simple helper class used in parsing the accept header class AcceptItem #:nodoc: diff --git a/actionpack/test/controller/mime_type_test.rb b/actionpack/test/controller/mime_type_test.rb index f16a3c68b4..4cfaf38ac7 100644 --- a/actionpack/test/controller/mime_type_test.rb +++ b/actionpack/test/controller/mime_type_test.rb @@ -61,7 +61,9 @@ class MimeTypeTest < Test::Unit::TestCase types.each do |type| mime = Mime.const_get(type.to_s.upcase) assert mime.send("#{type}?"), "#{mime.inspect} is not #{type}?" - (types - [type]).each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } + invalid_types = types - [type] + invalid_types.delete(:html) if Mime::Type.html_types.include?(type) + invalid_types.each { |other_type| assert !mime.send("#{other_type}?"), "#{mime.inspect} is #{other_type}?" } end end @@ -71,14 +73,12 @@ class MimeTypeTest < Test::Unit::TestCase end def test_verifiable_mime_types - unverified_types = Mime::Type.unverifiable_types all_types = Mime::SET.to_a.map(&:to_sym) all_types.uniq! # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } - - unverified, verified = all_types.partition { |type| Mime::Type.unverifiable_types.include? type } - assert verified.all? { |type| Mime.const_get(type.to_s.upcase).verify_request? }, "Not all Mime Types are verified: #{verified.inspect}" - assert unverified.all? { |type| !Mime.const_get(type.to_s.upcase).verify_request? }, "Some Mime Types are verified: #{unverified.inspect}" + verified, unverified = all_types.partition { |type| Mime::Type.html_types.include? type } + assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is not verified: #{type.inspect}" } + assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is verified: #{type.inspect}" } end end -- cgit v1.2.3 From f1ad8b48aae3ee26613b3e77bc0056e120096846 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Thu, 13 Nov 2008 11:19:53 +0100 Subject: Instead of overriding html_types, base the verification on browser_generated_types. Also Deprecate the old unverifiable types. [#1145 state:committed] --- actionpack/lib/action_controller/mime_type.rb | 21 +++++++++++++++++---- actionpack/test/controller/mime_type_test.rb | 6 +++--- 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/actionpack/lib/action_controller/mime_type.rb b/actionpack/lib/action_controller/mime_type.rb index 48c4c1ee1e..8ca3a70341 100644 --- a/actionpack/lib/action_controller/mime_type.rb +++ b/actionpack/lib/action_controller/mime_type.rb @@ -19,12 +19,21 @@ module Mime # end # end class Type - @@html_types = Set.new [:html, :url_encoded_form, :multipart_form, :all] + @@html_types = Set.new [:html, :all] cattr_reader :html_types - # UNUSED, deprecate? + # These are the content types which browsers can generate without using ajax, flash, etc + # i.e. following a link, getting an image or posting a form. CSRF protection + # only needs to protect against these types. + @@browser_generated_types = Set.new [:html, :url_encoded_form, :multipart_form] + cattr_reader :browser_generated_types + + @@unverifiable_types = Set.new [:text, :json, :csv, :xml, :rss, :atom, :yaml] - cattr_reader :unverifiable_types + def self.unverifiable_types + ActiveSupport::Deprecation.warn("unverifiable_types is deprecated and has no effect", caller) + @@unverifiable_types + end # A simple helper class used in parsing the accept header class AcceptItem #:nodoc: @@ -170,13 +179,17 @@ module Mime # Returns true if Action Pack should check requests using this Mime Type for possible request forgery. See # ActionController::RequestForgerProtection. def verify_request? - html? + browser_generated? end def html? @@html_types.include?(to_sym) || @string =~ /html/ end + def browser_generated? + @@browser_generated_types.include?(to_sym) + end + private def method_missing(method, *args) if method.to_s =~ /(\w+)\?$/ diff --git a/actionpack/test/controller/mime_type_test.rb b/actionpack/test/controller/mime_type_test.rb index 4cfaf38ac7..21ae0419f1 100644 --- a/actionpack/test/controller/mime_type_test.rb +++ b/actionpack/test/controller/mime_type_test.rb @@ -77,8 +77,8 @@ class MimeTypeTest < Test::Unit::TestCase all_types.uniq! # Remove custom Mime::Type instances set in other tests, like Mime::GIF and Mime::IPHONE all_types.delete_if { |type| !Mime.const_defined?(type.to_s.upcase) } - verified, unverified = all_types.partition { |type| Mime::Type.html_types.include? type } - assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is not verified: #{type.inspect}" } - assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Mime Type is verified: #{type.inspect}" } + verified, unverified = all_types.partition { |type| Mime::Type.browser_generated_types.include? type } + assert verified.each { |type| assert Mime.const_get(type.to_s.upcase).verify_request?, "Verifiable Mime Type is not verified: #{type.inspect}" } + assert unverified.each { |type| assert !Mime.const_get(type.to_s.upcase).verify_request?, "Nonverifiable Mime Type is verified: #{type.inspect}" } end end -- cgit v1.2.3 From 020a4113048be7166346cba6c59bbbca819de911 Mon Sep 17 00:00:00 2001 From: gbuesing Date: Thu, 13 Nov 2008 09:04:06 -0600 Subject: TimeZone: fix base offset for Sri Jayawardenepura. Anchor tests for zone offsets to more current date --- activesupport/CHANGELOG | 2 ++ activesupport/lib/active_support/values/time_zone.rb | 4 ++-- activesupport/test/time_zone_test.rb | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/activesupport/CHANGELOG b/activesupport/CHANGELOG index 12b300d3ae..1475586cde 100644 --- a/activesupport/CHANGELOG +++ b/activesupport/CHANGELOG @@ -1,5 +1,7 @@ *2.2.1 [RC2 or 2.2 final]* +* TimeZone: fix offset for Sri Jayawardenepura. Anchor tests for zone offsets to more current date [Geoff Buesing] + * TimeZone: Caracas GMT offset changed to -4:30 [#1361 state:resolved] [Phil Ross] * Added render :js for people who want to render inline JavaScript replies without using RJS [DHH] diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index 335d75d218..1d87fa64b5 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -326,9 +326,9 @@ module ActiveSupport [ 14_400, "Abu Dhabi", "Muscat", "Baku", "Tbilisi", "Yerevan" ], [ 16_200, "Kabul" ], [ 18_000, "Ekaterinburg", "Islamabad", "Karachi", "Tashkent" ], - [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi" ], + [ 19_800, "Chennai", "Kolkata", "Mumbai", "New Delhi", "Sri Jayawardenepura" ], [ 20_700, "Kathmandu" ], - [ 21_600, "Astana", "Dhaka", "Sri Jayawardenepura", "Almaty", + [ 21_600, "Astana", "Dhaka", "Almaty", "Novosibirsk" ], [ 23_400, "Rangoon" ], [ 25_200, "Bangkok", "Hanoi", "Jakarta", "Krasnoyarsk" ], diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb index 515ffcf0bf..d999b9f2a8 100644 --- a/activesupport/test/time_zone_test.rb +++ b/activesupport/test/time_zone_test.rb @@ -51,7 +51,7 @@ class TimeZoneTest < Test::Unit::TestCase define_method("test_utc_offset_for_#{name}") do silence_warnings do # silence warnings raised by tzinfo gem - period = zone.tzinfo.period_for_utc(Time.utc(2006,1,1,0,0,0)) + period = zone.tzinfo.period_for_utc(Time.utc(2009,1,1,0,0,0)) assert_equal period.utc_offset, zone.utc_offset end end -- cgit v1.2.3 From 57d795bad43d4a3e5eef7151099a8e40808a1031 Mon Sep 17 00:00:00 2001 From: Ken Collins Date: Thu, 13 Nov 2008 10:45:57 -0600 Subject: Make sure any Fixnum returned by a DB sum is type cast to a Float before standard converstion to a BigDecimal [#8994 state:resolved] Signed-off-by: Joshua Peek --- activerecord/lib/active_record/calculations.rb | 2 +- activerecord/test/cases/calculations_test.rb | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/calculations.rb b/activerecord/lib/active_record/calculations.rb index 6f4e02b430..65512d534a 100644 --- a/activerecord/lib/active_record/calculations.rb +++ b/activerecord/lib/active_record/calculations.rb @@ -286,7 +286,7 @@ module ActiveRecord case operation when 'count' then value.to_i when 'sum' then type_cast_using_column(value || '0', column) - when 'avg' then value && (value == 0 ? 0.0.to_d : value.to_d) + when 'avg' then value && (value.is_a?(Fixnum) ? value.to_f : value).to_d else type_cast_using_column(value, column) end end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index 0fa61500c0..8bd0dd0f6e 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -25,6 +25,11 @@ class CalculationsTest < ActiveRecord::TestCase def test_should_return_nil_as_average assert_nil NumericData.average(:bank_balance) end + + def test_type_cast_calculated_value_should_convert_db_averages_of_fixnum_class_to_decimal + assert_equal 0, NumericData.send(:type_cast_calculated_value, 0, nil, 'avg') + assert_equal 53.0, NumericData.send(:type_cast_calculated_value, 53, nil, 'avg') + end def test_should_get_maximum_of_field assert_equal 60, Account.maximum(:credit_limit) -- cgit v1.2.3 From 4c0921024471c0463d67f8b8fb6a115a94d343aa Mon Sep 17 00:00:00 2001 From: Tom Stuart Date: Thu, 13 Nov 2008 14:31:36 +0000 Subject: Fix map.resources to always generate named routes if they're needed Signed-off-by: Michael Koziarski --- actionpack/lib/action_controller/resources.rb | 13 ++--- actionpack/test/controller/resources_test.rb | 78 +++++++++++++++++++++++++++ 2 files changed, 85 insertions(+), 6 deletions(-) diff --git a/actionpack/lib/action_controller/resources.rb b/actionpack/lib/action_controller/resources.rb index de529e23ff..d6cc4aa418 100644 --- a/actionpack/lib/action_controller/resources.rb +++ b/actionpack/lib/action_controller/resources.rb @@ -597,11 +597,11 @@ module ActionController end map_resource_routes(map, resource, :index, resource.path, index_route_name) - map_resource_routes(map, resource, :create, resource.path) + map_resource_routes(map, resource, :create, resource.path, index_route_name) end def map_default_singleton_actions(map, resource) - map_resource_routes(map, resource, :create, resource.path) + map_resource_routes(map, resource, :create, resource.path, "#{resource.shallow_name_prefix}#{resource.singular}") end def map_new_actions(map, resource) @@ -632,9 +632,10 @@ module ActionController end end - map_resource_routes(map, resource, :show, resource.member_path, "#{resource.shallow_name_prefix}#{resource.singular}") - map_resource_routes(map, resource, :update, resource.member_path) - map_resource_routes(map, resource, :destroy, resource.member_path) + route_path = "#{resource.shallow_name_prefix}#{resource.singular}" + map_resource_routes(map, resource, :show, resource.member_path, route_path) + map_resource_routes(map, resource, :update, resource.member_path, route_path) + map_resource_routes(map, resource, :destroy, resource.member_path, route_path) end def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil) @@ -642,7 +643,7 @@ module ActionController action_options = action_options_for(action, resource, method) formatted_route_path = "#{route_path}.:format" - if route_name + if route_name && @set.named_routes[route_name.to_sym].nil? map.named_route(route_name, route_path, action_options) map.named_route("formatted_#{route_name}", formatted_route_path, action_options) else diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 2a86577d8c..1f1f7b8a2c 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -822,6 +822,84 @@ class ResourcesTest < Test::Unit::TestCase end end + def test_resource_has_only_create_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :create + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :create, [:index, :new, :show, :edit, :update, :destroy]) + + assert_not_nil set.named_routes[:products] + end + end + + def test_resource_has_only_update_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :update + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :update, [:index, :new, :create, :show, :edit, :destroy]) + + assert_not_nil set.named_routes[:product] + end + end + + def test_resource_has_only_destroy_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resources :products, :only => :destroy + end + + assert_resource_allowed_routes('products', {}, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update]) + assert_resource_allowed_routes('products', { :format => 'xml' }, { :id => '1' }, :destroy, [:index, :new, :create, :show, :edit, :update]) + + assert_not_nil set.named_routes[:product] + end + end + + def test_singleton_resource_has_only_create_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :create + end + + assert_singleton_resource_allowed_routes('accounts', {}, :create, [:new, :show, :edit, :update, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :create, [:new, :show, :edit, :update, :destroy]) + + assert_not_nil set.named_routes[:account] + end + end + + def test_singleton_resource_has_only_update_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :update + end + + assert_singleton_resource_allowed_routes('accounts', {}, :update, [:new, :create, :show, :edit, :destroy]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :update, [:new, :create, :show, :edit, :destroy]) + + assert_not_nil set.named_routes[:account] + end + end + + def test_singleton_resource_has_only_destroy_action_and_named_route + with_routing do |set| + set.draw do |map| + map.resource :account, :only => :destroy + end + + assert_singleton_resource_allowed_routes('accounts', {}, :destroy, [:new, :create, :show, :edit, :update]) + assert_singleton_resource_allowed_routes('accounts', { :format => 'xml' }, :destroy, [:new, :create, :show, :edit, :update]) + + assert_not_nil set.named_routes[:account] + end + end + def test_resource_has_only_collection_action with_routing do |set| set.draw do |map| -- cgit v1.2.3 From 4e9abdd7f1b4e05f8d1b50ddaa080b3ff63b92d9 Mon Sep 17 00:00:00 2001 From: "Hongli Lai (Phusion)" Date: Thu, 13 Nov 2008 21:49:23 +0100 Subject: Tag helper should output an attribute with the value 'false' instead of omitting the attribute, if the associated option is false but not nil. --- actionpack/lib/action_view/helpers/tag_helper.rb | 10 ++++++---- actionpack/test/template/form_tag_helper_test.rb | 2 +- actionpack/test/template/tag_helper_test.rb | 4 ++++ 3 files changed, 11 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index de08672d2d..d37ca766af 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -133,10 +133,12 @@ module ActionView unless options.blank? attrs = [] if escape - options.each do |key, value| - next unless value - value = BOOLEAN_ATTRIBUTES.include?(key) ? key : escape_once(value) - attrs << %(#{key}="#{value}") + options.each_pair do |key, value| + if BOOLEAN_ATTRIBUTES.include?(key) + attrs << %(#{key}="#{key}") if value + else + attrs << %(#{key}="#{escape_once(value)}") if !value.nil? + end end else attrs = options.map { |key, value| %(#{key}="#{value}") } diff --git a/actionpack/test/template/form_tag_helper_test.rb b/actionpack/test/template/form_tag_helper_test.rb index de82647813..f8add0bab1 100644 --- a/actionpack/test/template/form_tag_helper_test.rb +++ b/actionpack/test/template/form_tag_helper_test.rb @@ -235,7 +235,7 @@ class FormTagHelperTest < ActionView::TestCase assert_match VALID_HTML_ID, label_elem['for'] end - def test_boolean_optios + def test_boolean_options assert_dom_equal %(), check_box_tag("admin", 1, true, 'disabled' => true, :readonly => "yes") assert_dom_equal %(), check_box_tag("admin", 1, true, :disabled => false, :readonly => nil) assert_dom_equal %(), select_tag("people", "", :multiple => true) diff --git a/actionpack/test/template/tag_helper_test.rb b/actionpack/test/template/tag_helper_test.rb index fc49d340ef..ef88cae5b8 100644 --- a/actionpack/test/template/tag_helper_test.rb +++ b/actionpack/test/template/tag_helper_test.rb @@ -19,6 +19,10 @@ class TagHelperTest < ActionView::TestCase assert_equal "

    ", tag("p", :ignored => nil) end + def test_tag_options_accepts_false_option + assert_equal "

    ", tag("p", :value => false) + end + def test_tag_options_accepts_blank_option assert_equal "

    ", tag("p", :included => '') end -- cgit v1.2.3 From 9a88ab64bb45ddb2bdcf80fab9203111d8f8abb4 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 12 Nov 2008 11:33:09 -0800 Subject: Move fixtures settings from AR::TestCase to railties test_help --- activerecord/lib/active_record/test_case.rb | 10 +--------- railties/lib/test_help.rb | 19 +++++++++++++++---- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/activerecord/lib/active_record/test_case.rb b/activerecord/lib/active_record/test_case.rb index eabf06fc3b..d5f43f56e6 100644 --- a/activerecord/lib/active_record/test_case.rb +++ b/activerecord/lib/active_record/test_case.rb @@ -1,15 +1,7 @@ require "active_support/test_case" -module ActiveRecord +module ActiveRecord class TestCase < ActiveSupport::TestCase #:nodoc: - self.fixture_path = FIXTURES_ROOT - self.use_instantiated_fixtures = false - self.use_transactional_fixtures = true - - def create_fixtures(*table_names, &block) - Fixtures.create_fixtures(FIXTURES_ROOT, table_names, {}, &block) - end - def assert_date_from_db(expected, actual, message = nil) # SQL Server doesn't have a separate column type just for dates, # so the time is in the string and incorrectly formatted diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 3cc61d7932..367533cf0f 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -11,11 +11,22 @@ require 'action_controller/test_case' require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -Test::Unit::TestCase.fixture_path = RAILS_ROOT + "/test/fixtures/" -ActionController::IntegrationTest.fixture_path = Test::Unit::TestCase.fixture_path +if defined?(ActiveRecord) + require 'active_record/test_case' + require 'active_record/fixtures' -def create_fixtures(*table_names) - Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) + class ActiveSupport::TestCase + include ActiveRecord::TestFixtures + self.fixture_path = "#{RAILS_ROOT}/test/fixtures/" + self.use_instantiated_fixtures = false + self.use_transactional_fixtures = true + end + + ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path + + def create_fixtures(*table_names, &block) + Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block) + end end begin -- cgit v1.2.3 From 4146efc380255319768031f26e63210fd4158e99 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Thu, 13 Nov 2008 23:29:46 -0500 Subject: Plugin guide: update generator guide to include tests --- railties/doc/guides/html/creating_plugins.html | 231 ++++-- .../source/creating_plugins/acts_as_yaffle.txt | 4 + .../guides/source/creating_plugins/basics.markdown | 861 --------------------- .../creating_plugins/migration_generator.txt | 120 ++- .../guides/source/creating_plugins/test_setup.txt | 58 +- railties/lib/rails_generator/commands.rb | 2 + 6 files changed, 291 insertions(+), 985 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/basics.markdown diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 793cd2b7a7..5589971ec5 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -239,6 +239,17 @@ ul#navMain {

  • Create a migration generator +
  • Add a custom generator command @@ -433,22 +444,22 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE

    1.3. Setup the plugin for testing

    -

    In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

    +

    If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

    To setup your plugin to allow for easy testing you'll need to add 3 files:

    • -A database.yml file with all of your connection strings. +A database.yml file with all of your connection strings

    • -A schema.rb file with your table definitions. +A schema.rb file with your table definitions

    • -A test helper that sets up the database before your tests. +A test helper method that sets up the database

    @@ -457,11 +468,11 @@ A test helper that sets up the database before your tests.
    sqlite:
       :adapter: sqlite
    -  :dbfile: yaffle_plugin.sqlite.db
    +  :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db
     
     sqlite3:
       :adapter: sqlite3
    -  :dbfile: yaffle_plugin.sqlite3.db
    +  :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db
     
     postgresql:
       :adapter: postgresql
    @@ -473,8 +484,8 @@ postgresql:
     mysql:
       :adapter: mysql
       :host: localhost
    -  :username: rails
    -  :password:
    +  :username: root
    +  :password: password
       :database: yaffle_plugin_test

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

    @@ -509,34 +520,38 @@ ENV['RAILS_ROOT require 'test/unit' require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") -db_adapter = ENV['DB'] + db_adapter = ENV['DB'] -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= begin - require 'sqlite3' - 'sqlite3' + require 'rubygems' + require 'sqlite' + 'sqlite' rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end end - end -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -end + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end -ActiveRecord::Base.establish_connection(config[db_adapter]) + ActiveRecord::Base.establish_connection(config[db_adapter]) -load(File.dirname(__FILE__) + "/schema.rb") + load(File.dirname(__FILE__) + "/schema.rb") -require File.dirname(__FILE__) + '/../init.rb' + require File.dirname(__FILE__) + '/../init.rb' +end +

    Now whenever you write a test that requires the database, you can call load_schema.

    1.4. Run the plugin tests

    Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:

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

    @@ -548,6 +563,7 @@ http://www.gnu.org/software/src-highlite -->
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class YaffleTest < Test::Unit::TestCase
    +  load_schema
     
       class Hickwall < ActiveRecord::Base
       end
    @@ -800,6 +816,8 @@ http://www.gnu.org/software/src-highlite -->
     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
    @@ -851,6 +869,8 @@ http://www.gnu.org/software/src-highlite -->
     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
    @@ -987,31 +1007,92 @@ http://www.gnu.org/software/src-highlite -->
     
     

    5. 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:

    +

    Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.

    +

    Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.

    +

    To create a generator you must:

    +
      +
    • +

      +Add your instructions to the manifest method of the generator +

      +
    • +
    • +

      +Add any necessary template files to the templates directory +

      +
    • +
    • +

      +Test the generator manually by running various combinations of script/generate and script/destroy +

      +
    • +
    • +

      +Update the USAGE file to add helpful documentation for your generator +

      +
    • +
    +

    5.1. Testing generators

    +

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

    +
      +
    • +

      +Creates a new fake rails root directory that will serve as destination +

      +
    • +
    • +

      +Runs the generator forward and backward, making whatever assertions are necessary +

      +
    • +
    • +

      +Removes the fake rails root +

      +
    • +
    +

    For the generator in this section, the test could look something like this:

    +

    vendor/plugins/yaffle/test/yaffle_generator_test.rb

    -
    -
    Description:
    -    Creates a migration that adds yaffle squawk fields to the given model
    +
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +require 'rails_generator'
    +require 'rails_generator/scripts/generate'
    +require 'rails_generator/scripts/destroy'
     
    -Example:
    -    ./script/generate yaffle hickwall
    +class YaffleTest < Test::Unit::TestCase
     
    -    This will create:
    -        db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
    -
    -

    Now you can add code to your generator:

    + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_bird/, new_file + end + +end +
    +

    You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.

    +

    5.2. Adding to the manifest

    +

    This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. To start, update your generator file to look like this:

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

    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 @@ -1039,31 +1120,19 @@ http://www.gnu.org/software/src-highlite --> 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

    +

    The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.

    +

    It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.

    +

    5.3. Manually test the generator

    +

    To run the generator, type the following at the command line:

    -
    script/generate yaffle bird
    +
    ./script/generate yaffle bird
    -

    You will see a new file:

    +

    and you will see a new file:

    db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

    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
     
    +

    5.4. The USAGE file

    +

    Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:

    +
    +
    +
    script/generate
    +
    +

    You should see something like this:

    +
    +
    +
    Installed Generators
    +  Plugins (vendor/plugins): yaffle
    +  Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
    +
    +

    When you run script/generate yaffle you should see the contents of your vendor/plugins/yaffle/generators/yaffle/USAGE file.

    +

    For this plugin, update the USAGE file looks like this:

    +
    +
    +
    Description:
    +    Creates a migration that adds yaffle squawk fields to the given model
    +
    +Example:
    +    ./script/generate yaffle hickwall
    +
    +    This will create:
    +        db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
    +

    6. Add a custom generator command

    diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 41ffa61537..de116af7db 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -79,6 +79,8 @@ class Wickwall < ActiveRecord::Base end class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end @@ -132,6 +134,8 @@ class Wickwall < ActiveRecord::Base end class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end diff --git a/railties/doc/guides/source/creating_plugins/basics.markdown b/railties/doc/guides/source/creating_plugins/basics.markdown deleted file mode 100644 index f59e8728d7..0000000000 --- a/railties/doc/guides/source/creating_plugins/basics.markdown +++ /dev/null @@ -1,861 +0,0 @@ -Creating Plugin Basics -==================== - -Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. - -In this tutorial you will learn how to create a plugin that includes: - -Core Extensions - extending String: - - # Anywhere - "hello".squawk # => "squawk! hello! squawk!" - -An `acts_as_yaffle` method for Active Record models that adds a "squawk" method: - - class Hickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_sang_at - end - - Hickwall.new.squawk("Hello World") - -A view helper that will print out squawking info: - - squawk_info_for(@hickwall) - -A generator that creates a migration to add squawk columns to a model: - - script/generate yaffle hickwall - -A custom generator command: - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end - end - end - -A custom route method: - - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - -In addition you'll learn how to: - -* test your plugins -* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins -* create documentation for your plugin. -* write custom rake tasks in your plugin - -Create the basic app ---------------------- - -In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: - -> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - rails plugin_demo - cd plugin_demo - script/generate scaffold bird name:string - rake db:migrate - script/server - -Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing. - -Create the plugin ------------------------ - -The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also. - -This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories. - -Examples: - - ./script/generate plugin BrowserFilters - ./script/generate plugin BrowserFilters --with-generator - -Later in the plugin we will create a generator, so go ahead and add the --with-generator option now: - - script/generate plugin yaffle --with-generator - -You should see the following output: - - create vendor/plugins/yaffle/lib - create vendor/plugins/yaffle/tasks - create vendor/plugins/yaffle/test - create vendor/plugins/yaffle/README - create vendor/plugins/yaffle/MIT-LICENSE - create vendor/plugins/yaffle/Rakefile - create vendor/plugins/yaffle/init.rb - create vendor/plugins/yaffle/install.rb - create vendor/plugins/yaffle/uninstall.rb - create vendor/plugins/yaffle/lib/yaffle.rb - create vendor/plugins/yaffle/tasks/yaffle_tasks.rake - create vendor/plugins/yaffle/test/core_ext_test.rb - create vendor/plugins/yaffle/generators - create vendor/plugins/yaffle/generators/yaffle - create vendor/plugins/yaffle/generators/yaffle/templates - create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - create vendor/plugins/yaffle/generators/yaffle/USAGE - -For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that. - - rm vendor/plugins/yaffle/lib/yaffle.rb - -> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"` -> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean - -Setup the plugin for testing ------------------------- - -Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - -* A database.yml file with all of your connection strings -* A schema.rb file with your table definitions -* A test helper that sets up the database before your tests - -For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: - - # File: vendor/plugins/yaffle/test/database.yml - - sqlite: - :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db - sqlite3: - :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db - postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: yaffle_plugin_test - - # File: vendor/plugins/yaffle/test/test_helper.rb - - ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - end - - # File: vendor/plugins/yaffle/test/test_helper.rb - - ENV['RAILS_ENV'] = 'test' - ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - - require 'test/unit' - require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - - load(File.dirname(__FILE__) + "/schema.rb") - - require File.dirname(__FILE__) + '/../init.rb' - - class Hickwall < ActiveRecord::Base - acts_as_yaffle - end - - class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at - end - -Add a `to_squawk` method to String ------------------------ - -To update a core class you will have to: - -* Write tests for the desired functionality -* Create a file for the code you wish to use -* Require that file from your init.rb - -Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb` - -First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: - - # File: vendor/plugins/yaffle/test/core_ext_test.rb - - require 'test/unit' - - class CoreExtTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end - end - -Start off by removing the default test, and adding a require statement for your test helper. - - # File: vendor/plugins/yaffle/test/core_ext_test.rb - - require 'test/unit' - require File.dirname(__FILE__) + '/test_helper.rb' - - class CoreExtTest < Test::Unit::TestCase - end - -Navigate to your plugin directory and run `rake test` - - cd vendor/plugins/yaffle - rake test - -Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message: - - 1.) Failure ... - No tests were specified - -Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this: - - # File: vendor/plugins/yaffle/init.rb - - class CoreExtTest < Test::Unit::TestCase - def test_string_should_respond_to_squawk - assert_equal true, "".respond_to?(:to_squawk) - end - def test_string_prepend_empty_strings_with_the_word_squawk - assert_equal "squawk!", "".to_squawk - end - def test_string_prepend_non_empty_strings_with_the_word_squawk - assert_equal "squawk! Hello World", "Hello World".to_squawk - end - end - - # File: vendor/plugins/yaffle/init.rb - - require "core_ext" - - # File: vendor/plugins/yaffle/lib/core_ext.rb - - String.class_eval do - def to_squawk - "squawk! #{self}".strip - end - end - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - - script/console - >> "Hello World".to_squawk - => "squawk! Hello World" - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. - -Add an `acts_as_yaffle` method to ActiveRecord ------------------------ - -A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a squawk method to your models. - -To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper. - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class Hickwall < ActiveRecord::Base - acts_as_yaffle - end - - class ActsAsYaffleTest < Test::Unit::TestCase - end - - # File: vendor/plugins/lib/acts_as_yaffle.rb - - module Yaffle - end - -One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - # any method placed here will apply to classes, like Hickwall - def acts_as_something - send :include, InstanceMethods - end - end - - module InstanceMethods - # any method placed here will apply to instaces, like @hickwall - end - end - -With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`). - -Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. - -Back in your `acts_as_yaffle` file, update ClassMethods like so: - - module ClassMethods - def acts_as_yaffle(options = {}) - send :include, InstanceMethods - end - end - -Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class ActsAsYaffleTest < Test::Unit::TestCase - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet - assert_equal "last_tweet", Wickwall.yaffle_text_field - end - def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - end - -To make these tests pass, you could modify your `acts_as_yaffle` file like so: - - # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods - end - end - - module InstanceMethods - end - end - -Now you can add tests for the instance methods, and the instance method itself: - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class ActsAsYaffleTest < Test::Unit::TestCase - - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - - def test_a_wickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_tweet", Wickwall.yaffle_text_field - end - def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - - def test_hickwalls_squawk_should_populate_last_squawk - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal "squawk! Hello World", hickwall.last_squawk - end - def test_hickwalls_squawk_should_populate_last_squawked_at - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal Date.today, hickwall.last_squawked_at - end - - def test_wickwalls_squawk_should_populate_last_tweet - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal "squawk! Hello World", wickwall.last_tweet - end - def test_wickwalls_squawk_should_populate_last_tweeted_at - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal Date.today, wickwall.last_tweeted_at - end - end - - # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods - end - end - - module InstanceMethods - def squawk(string) - write_attribute(self.class.yaffle_text_field, string.to_squawk) - write_attribute(self.class.yaffle_date_field, Date.today) - end - end - end - -Note the use of write_attribute to write to the field in model. - -Create a view helper ------------------------ - -Creating a view helper is a 3-step process: - -* Add an appropriately named file to the lib directory -* Require the file and hooks in init.rb -* Write the tests - -First, create the test to define the functionality you want: - - # File: vendor/plugins/yaffle/test/view_helpers_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - include YaffleViewHelper - - class ViewHelpersTest < Test::Unit::TestCase - def test_squawk_info_for_should_return_the_text_and_date - time = Time.now - hickwall = Hickwall.new - hickwall.last_squawk = "Hello World" - hickwall.last_squawked_at = time - assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) - end - end - -Then add the following statements to init.rb: - - # File: vendor/plugins/yaffle/init.rb - - require "view_helpers" - ActionView::Base.send :include, YaffleViewHelper - -Then add the view helpers file and - - # File: vendor/plugins/yaffle/lib/view_helpers.rb - - module YaffleViewHelper - def squawk_info_for(yaffle) - returning "" do |result| - result << yaffle.read_attribute(yaffle.class.yaffle_text_field) - result << ", " - result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s - end - end - end - -You can also test this in script/console by using the "helper" method: - - script/console - >> helper.squawk_info_for(@some_yaffle_instance) - -Create a migration generator ------------------------ - -When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. - -We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. - -Type: - - script/generate - -You should see the line: - - Plugins (vendor/plugins): yaffle - -When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: - - Description: - Creates a migration that adds yaffle squawk fields to the given model - - Example: - ./script/generate yaffle hickwall - - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall - -Now you can add code to your generator: - - # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - end - - def yaffle_local_assigns - returning(assigns = {}) do - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") - end - end - end - -Note that you need to be aware of whether or not table names are pluralized. - -This does a few things: - -* Reuses the built in rails migration_template method -* Reuses the built-in rails migration template - -When you run the generator like - - script/generate yaffle bird - -You will see a new file: - - # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb - - class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - add_column :birds, :last_squawked_at, :datetime - end - - def self.down - remove_column :birds, :last_squawked_at - remove_column :birds, :last_squawk - end - end - -Add a custom generator command ------------------------- - -You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: - -1. Add the require and hook statements to init.rb -2. Create the commands - creating 3 sets, Create, Destroy, List -3. Add the method to your generator - -Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: - - # File: vendor/plugins/yaffle/init.rb - - require "commands" - Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create - Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy - Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List - - # File: vendor/plugins/yaffle/lib/commands.rb - - require 'rails_generator' - require 'rails_generator/commands' - - module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end - end - - # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt - - Yaffle is a bird - - # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end - end - end - -This example just uses the built-in "file" method, but you could do anything that ruby allows. - -Add a Custom Route ------------------------- - -Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in [http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2) - - # File: vendor/plugins/yaffle/test/routing_test.rb - - require "#{File.dirname(__FILE__)}/test_helper" - - class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end - - private - - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. - def assert_recognition(method, path, options) - result = ActionController::Routing::Routes.recognize_path(path, :method => method) - assert_equal options, result - end - end - - # File: vendor/plugins/yaffle/init.rb - - require "routing" - ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions - - # File: vendor/plugins/yaffle/lib/routing.rb - - module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) - end - end - end - end - - # File: config/routes.rb - - ActionController::Routing::Routes.draw do |map| - ... - map.yaffles - end - -You can also see if your routes work by running `rake routes` from your app directory. - -Generate RDoc Documentation ------------------------ - -Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. - -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - -* Your name -* How to install -* How to add the functionality to the app (several examples of common use cases) -* Warning, gotchas or tips that might help save users time - -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. - -Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. - -Once your comments are good to go, navigate to your plugin directory and run - - rake rdoc - -Work with init.rb ------------------------- - -The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior. - -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: - -The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash - - # File: vendor/plugins/yaffle/init.rb - - class ::Hash - def is_a_special_hash? - true - end - end - -OR you can use `module_eval` or `class_eval` - - # File: vendor/plugins/yaffle/init.rb - - Hash.class_eval do - def is_a_special_hash? - true - end - end - -Store models, views, helpers, and controllers in your plugins ------------------------- - -You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: - - # File: vendor/plugins/yaffle/init.rb - - %w{ models controllers helpers }.each do |dir| - path = File.join(directory, 'lib', dir) - $LOAD_PATH << path - Dependencies.load_paths << path - Dependencies.load_once_paths.delete(path) - end - -Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. - -Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. - -Write custom rake tasks in your plugin -------------------------- - -When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app. - -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: - - # File: vendor/plugins/yaffle/tasks/yaffle.rake - - namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end - end - -When you run `rake -T` from your plugin you will see - - yaffle:squawk "Prints out..." - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -Store plugins in alternate locations -------------------------- - -You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb - -Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. - -You can even store plugins inside of other plugins for complete plugin madness! - - config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") - -Create your own Plugin Loaders and Plugin Locators ------------------------- - -If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. - -Use Custom Plugin Generators ------------------------- - -If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you. - -[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master) - -References ------------------------- - -* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i) -* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii) -* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master) -* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html) - -Appendices ------------------------- - -The final plugin should have a directory structure that looks something like this: - - |-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 1a477a69ab..743d512132 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -1,35 +1,68 @@ == Create a migration generator == -When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. +Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. -We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. -Type: +To create a generator you must: ------------------------------------------------------------------- -script/generate ------------------------------------------------------------------- + * Add your instructions to the 'manifest' method of the generator + * Add any necessary template files to the templates directory + * Test the generator manually by running various combinations of `script/generate` and `script/destroy` + * Update the USAGE file to add helpful documentation for your generator -You should see the line: +=== Testing generators === ------------------------------------------------------------------- -Plugins (vendor/plugins): yaffle ------------------------------------------------------------------- +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator forward and backward, making whatever assertions are necessary + * Removes the fake rails root + +For the generator in this section, the test could look something like this: -When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: +*vendor/plugins/yaffle/test/yaffle_generator_test.rb* +[source, ruby] ------------------------------------------------------------------ -Description: - Creates a migration that adds yaffle squawk fields to the given model +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' -Example: - ./script/generate yaffle hickwall +class YaffleTest < Test::Unit::TestCase - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_bird/, new_file + end + +end ------------------------------------------------------------------ -Now you can add code to your generator: +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +=== Adding to the manifest === + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this: *vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* @@ -40,7 +73,7 @@ class YaffleGenerator < Rails::Generator::NamedBase record do |m| m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } + } end end @@ -56,26 +89,24 @@ class YaffleGenerator < Rails::Generator::NamedBase assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" assigns[:table_name] = custom_file_name assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") end end end ------------------------------------------------------------------ -Note that you need to be aware of whether or not table names are pluralized. +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. -This does a few things: +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - * Reuses the built in rails `migration_template` method. - * Reuses the built-in rails migration template. +=== Manually test the generator === -When you run the generator like +To run the generator, type the following at the command line: ------------------------------------------------------------------ -script/generate yaffle bird +./script/generate yaffle bird ------------------------------------------------------------------ -You will see a new file: +and you will see a new file: *db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* @@ -84,12 +115,43 @@ You will see a new file: class AddYaffleFieldsToBirds < ActiveRecord::Migration def self.up add_column :birds, :last_squawk, :string - add_column :birds, :last_squawked_at, :datetime end def self.down - remove_column :birds, :last_squawked_at remove_column :birds, :last_squawk end end ------------------------------------------------------------------ + + + +=== The USAGE file === + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +------------------------------------------------------------------ +script/generate +------------------------------------------------------------------ + +You should see something like this: + +------------------------------------------------------------------ +Installed Generators + Plugins (vendor/plugins): yaffle + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +------------------------------------------------------------------ + +When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file. + +For this plugin, update the USAGE file looks like this: + +------------------------------------------------------------------ +Description: + Creates a migration that adds yaffle squawk fields to the given model + +Example: + ./script/generate yaffle hickwall + + This will create: + db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall +------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 583d058494..4bcb2d5c2b 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -64,24 +64,24 @@ create vendor/plugins/yaffle/generators/yaffle/USAGE === Setup the plugin for testing === -In this guide you will learn how to test your plugin against multiple different adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. +If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. To setup your plugin to allow for easy testing you'll need to add 3 files: - * A 'database.yml' file with all of your connection strings. - * A 'schema.rb' file with your table definitions. - * A test helper that sets up the database before your tests. + * A 'database.yml' file with all of your connection strings + * A 'schema.rb' file with your table definitions + * A test helper method that sets up the database *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- sqlite: :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db sqlite3: :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db postgresql: :adapter: postgresql @@ -93,8 +93,8 @@ postgresql: mysql: :adapter: mysql :host: localhost - :username: rails - :password: + :username: root + :password: password :database: yaffle_plugin_test ---------------------------------------------- @@ -128,35 +128,40 @@ ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' require 'test/unit' require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") -db_adapter = ENV['DB'] + db_adapter = ENV['DB'] -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= begin - require 'sqlite3' - 'sqlite3' + require 'rubygems' + require 'sqlite' + 'sqlite' rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end end - end -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -end + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end -ActiveRecord::Base.establish_connection(config[db_adapter]) + ActiveRecord::Base.establish_connection(config[db_adapter]) -load(File.dirname(__FILE__) + "/schema.rb") + load(File.dirname(__FILE__) + "/schema.rb") -require File.dirname(__FILE__) + '/../init.rb' + require File.dirname(__FILE__) + '/../init.rb' +end ---------------------------------------------- +Now whenever you write a test that requires the database, you can call 'load_schema'. + === Run the plugin tests === Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: @@ -168,6 +173,7 @@ Once you have these files in place, you can write your first test to ensure that require File.dirname(__FILE__) + '/test_helper.rb' class YaffleTest < Test::Unit::TestCase + load_schema class Hickwall < ActiveRecord::Base end diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb index 6b9a636847..120d428f35 100644 --- a/railties/lib/rails_generator/commands.rb +++ b/railties/lib/rails_generator/commands.rb @@ -73,6 +73,8 @@ module Rails end def existing_migrations(file_name) + puts "#{__FILE__}:#{__LINE__}" + puts @migration_directory Dir.glob("#{@migration_directory}/[0-9]*_*.rb").grep(/[0-9]+_#{file_name}.rb$/) end -- cgit v1.2.3 From 8a9bd56ca0d43c703f330e378474ddbdca2acd8e Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 00:38:52 -0500 Subject: Plugin Guide: updated test setup and generator sections --- railties/doc/guides/html/creating_plugins.html | 65 ++++++++-------- .../source/creating_plugins/custom_generator.txt | 69 ----------------- .../source/creating_plugins/generator_method.txt | 89 ++++++++++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 2 +- .../guides/source/creating_plugins/test_setup.txt | 2 - 5 files changed, 125 insertions(+), 102 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/custom_generator.txt create mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 5589971ec5..3e67c34b4f 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -1178,35 +1178,34 @@ Example:

    6. Add a custom generator command

    -

    You may have noticed above that you can used one of the built-in rails migration commands m.migration_template. You can create your own commands for these, using the following steps:

    -
      -
    1. -

      -Add the require and hook statements to init.rb. -

      -
    2. -
    3. -

      -Create the commands - creating 3 sets, Create, Destroy, List. -

      -
    4. -
    5. -

      -Add the method to your generator. -

      -
    6. -
    -

    Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:

    -

    vendor/plugins/yaffle/init.rb

    +

    You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.

    +

    This section describes how you you can create your own commands to add and remove a line of text from routes.rb. This example creates a very simple method that adds or removes a text file.

    +

    To start, add the following test method:

    +

    vendor/plugins/yaffle/test/generator_test.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
    +
    def test_generates_definition
    +  Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
    +  definition = File.read(File.join(fake_rails_root, "definition.txt"))
    +  assert_match /Yaffle\:/, definition
    +end
    +
    +

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

    +

    vendor/plugins/yaffle/generators/yaffle/templates/definition.txt

    +
    +
    +
    Yaffle: A bird
    +
    +

    vendor/plugins/yaffle/lib/yaffle.rb

    +
    +
    +
    require "yaffle/commands"
     

    vendor/plugins/yaffle/lib/commands.rb

    @@ -1237,15 +1236,22 @@ http://www.gnu.org/software/src-highlite --> file("definition.txt", "definition.txt") end end + + module Update + def yaffle_definition + file("definition.txt", "definition.txt") + end + end end end end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update
    -

    vendor/plugins/yaffle/generators/yaffle/templates/definition.txt

    -
    -
    -
    Yaffle is a bird
    -
    +

    Finally, call your new method in the manifest:

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

    end end
    -

    This example just uses the built-in "file" method, but you could do anything that Ruby allows.

    7. Add a Custom Route

    diff --git a/railties/doc/guides/source/creating_plugins/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt deleted file mode 100644 index a8cf1b48ce..0000000000 --- a/railties/doc/guides/source/creating_plugins/custom_generator.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Add a custom generator command == - -You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: - - 1. Add the require and hook statements to init.rb. - 2. Create the commands - creating 3 sets, Create, Destroy, List. - 3. Add the method to your generator. - -Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ------------------------------------------------------------ -require "commands" -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/commands.rb* - -[source, ruby] ------------------------------------------------------------ -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end ------------------------------------------------------------ - -*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* ------------------------------------------------------------ -Yaffle is a bird ------------------------------------------------------------ - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end ------------------------------------------------------------ - -This example just uses the built-in "file" method, but you could do anything that Ruby allows. diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt new file mode 100644 index 0000000000..126692f2c4 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generator_method.txt @@ -0,0 +1,89 @@ +== Add a custom generator command == + +You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. + +To start, add the following test method: + +*vendor/plugins/yaffle/test/generator_test.rb* + +[source, ruby] +----------------------------------------------------------- +def test_generates_definition + Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) + definition = File.read(File.join(fake_rails_root, "definition.txt")) + assert_match /Yaffle\:/, definition +end +----------------------------------------------------------- + +Run `rake` to watch the test fail, then make the test pass add the following: + +*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* + +----------------------------------------------------------- +Yaffle: A bird +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +----------------------------------------------------------- +require "yaffle/commands" +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/commands.rb* + +[source, ruby] +----------------------------------------------------------- +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Destroy + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module List + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + + module Update + def yaffle_definition + file("definition.txt", "definition.txt") + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +----------------------------------------------------------- + +Finally, call your new method in the manifest: + +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +[source, ruby] +----------------------------------------------------------- +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + m.yaffle_definition + end +end +----------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 91d7027323..bd7dfe65c3 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -39,7 +39,7 @@ include::view_helper.txt[] include::migration_generator.txt[] -include::custom_generator.txt[] +include::generator_method.txt[] include::custom_route.txt[] diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 4bcb2d5c2b..9e6763bc30 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -153,9 +153,7 @@ def load_schema end ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init.rb' end ---------------------------------------------- -- cgit v1.2.3 From 7eb249291d1c8a8af14c52de4767a36ba8f924e3 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 02:29:12 -0500 Subject: Plugin guide: added model and controller sections --- railties/doc/guides/html/creating_plugins.html | 355 ++++++++++++++------- .../guides/source/creating_plugins/controllers.txt | 59 ++++ .../doc/guides/source/creating_plugins/index.txt | 8 +- .../creating_plugins/migration_generator.txt | 5 +- .../doc/guides/source/creating_plugins/models.txt | 76 +++++ .../source/creating_plugins/odds_and_ends.txt | 22 -- .../guides/source/creating_plugins/test_setup.txt | 3 + 7 files changed, 384 insertions(+), 144 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/controllers.txt create mode 100644 railties/doc/guides/source/creating_plugins/models.txt diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 3e67c34b4f..3fa7bff260 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -235,10 +235,7 @@ ul#navMain {
  • - Create a squawk_info_for view helper -
  • -
  • - Create a migration generator + Create a generator
    • Testing generators
    • @@ -255,6 +252,15 @@ ul#navMain { Add a custom generator command
    • + Add a model +
    • +
    • + Add a controller +
    • +
    • + Create a squawk_info_for view helper +
    • +
    • Add a Custom Route
    • @@ -263,8 +269,6 @@ ul#navMain {
    • Generate RDoc Documentation
    • -
    • Store models, views, helpers, and controllers in your plugins
    • -
    • Write custom Rake tasks in your plugin
    • Store plugins in alternate locations
    • @@ -506,6 +510,9 @@ http://www.gnu.org/software/src-highlite --> 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:

      @@ -545,9 +552,7 @@ ENV['RAILS_ROOT end ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init.rb' end @@ -931,81 +936,7 @@ ActiveRecord::Base4. Create a squawk_info_for view helper -
      -

      Creating a view helper is a 3-step process:

      -
        -
      • -

        -Add an appropriately named file to the lib directory. -

        -
      • -
      • -

        -Require the file and hooks in init.rb. -

        -
      • -
      • -

        -Write the tests. -

        -
      • -
      -

      First, create the test to define the functionality you want:

      -

      vendor/plugins/yaffle/test/view_helpers_test.rb

      -
      -
      -
      require File.dirname(__FILE__) + '/test_helper.rb'
      -include YaffleViewHelper
      -
      -class ViewHelpersTest < Test::Unit::TestCase
      -  def test_squawk_info_for_should_return_the_text_and_date
      -    time = Time.now
      -    hickwall = Hickwall.new
      -    hickwall.last_squawk = "Hello World"
      -    hickwall.last_squawked_at = time
      -    assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
      -  end
      -end
      -
      -

      Then add the following statements to init.rb:

      -

      vendor/plugins/yaffle/init.rb

      -
      -
      -
      require "view_helpers"
      -ActionView::Base.send :include, YaffleViewHelper
      -
      -

      Then add the view helpers file and

      -

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

      5. Create a migration generator

      +

      4. Create a generator

      Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.

      Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.

      @@ -1032,7 +963,7 @@ Update the USAGE file to add helpful documentation for your generator

    -

    5.1. Testing generators

    +

    4.1. Testing generators

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

    • @@ -1063,7 +994,7 @@ http://www.gnu.org/software/src-highlite --> require 'rails_generator/scripts/generate' require 'rails_generator/scripts/destroy' -class YaffleTest < Test::Unit::TestCase +class GeneratorTest < Test::Unit::TestCase def fake_rails_root File.join(File.dirname(__FILE__), 'rails_root') @@ -1091,7 +1022,7 @@ http://www.gnu.org/software/src-highlite --> 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.

    -

    5.2. Adding to the manifest

    +

    4.2. Adding to the manifest

    This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. To start, update your generator file to look like this:

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

    @@ -1126,7 +1057,7 @@ http://www.gnu.org/software/src-highlite -->

    The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.

    It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.

    -

    5.3. Manually test the generator

    +

    4.3. Manually test the generator

    To run the generator, type the following at the command line:

    @@ -1149,7 +1080,7 @@ http://www.gnu.org/software/src-highlite --> end end
    -

    5.4. The USAGE file

    +

    4.4. 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:

    @@ -1176,7 +1107,7 @@ Example: db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
    -

    6. Add a custom generator command

    +

    5. Add a custom generator command

    You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.

    This section describes how you you can create your own commands to add and remove a line of text from routes.rb. This example creates a very simple method that adds or removes a text file.

    @@ -1265,7 +1196,215 @@ http://www.gnu.org/software/src-highlite --> end
    -

    7. Add a Custom Route

    +

    6. Add a model

    +
    +

    This section describes how to add a model named Woodpecker to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:

    +
    +
    +
    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:

    +
    +
    +
    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:

    +
    +
    +
    %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:

    +
    +
    +
    class Woodpecker < ActiveRecord::Base
    +end
    +
    +

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

    +

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

    +
    +
    +
    ActiveRecord::Schema.define(:version => 0) do
    +  create_table :woodpeckers, :force => true do |t|
    +    t.string :name
    +  end
    +end
    +
    +

    Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.

    +
    +

    7. Add a controller

    +
    +

    This section describes how to add a controller named woodpeckers to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.

    +

    You can test your plugin's controller as you would test any other controller:

    +

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

    +
    +
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +require 'woodpeckers_controller'
    +require 'action_controller/test_process'
    +
    +class WoodpeckersController; def rescue_action(e) raise e end; end
    +
    +class WoodpeckersControllerTest < Test::Unit::TestCase
    +  def setup
    +    @controller = WoodpeckersController.new
    +    @request = ActionController::TestRequest.new
    +    @response = ActionController::TestResponse.new
    +  end
    +
    +  def test_index
    +    get :index
    +    assert_response :success
    +  end
    +end
    +
    +

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

    +

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

    +
    +
    +
    %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:

    +
    +
    +
    class WoodpeckersController < ActionController::Base
    +
    +  def index
    +    render :text => "Squawk!"
    +  end
    +
    +end
    +
    +

    Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.

    +
    +

    8. Create a squawk_info_for view helper

    +
    +

    Creating a view helper is a 3-step process:

    +
      +
    • +

      +Add an appropriately named file to the lib directory. +

      +
    • +
    • +

      +Require the file and hooks in init.rb. +

      +
    • +
    • +

      +Write the tests. +

      +
    • +
    +

    First, create the test to define the functionality you want:

    +

    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:

    +

    vendor/plugins/yaffle/init.rb

    +
    +
    +
    require "view_helpers"
    +ActionView::Base.send :include, YaffleViewHelper
    +
    +

    Then add the view helpers file and

    +

    vendor/plugins/yaffle/lib/view_helpers.rb

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

    9. Add a Custom Route

    Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.

    vendor/plugins/yaffle/test/routing_test.rb

    @@ -1338,9 +1477,9 @@ http://www.gnu.org/software/src-highlite -->

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

    -

    8. Odds and ends

    +

    10. Odds and ends

    -

    8.1. Generate RDoc Documentation

    +

    10.1. Generate RDoc Documentation

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

      @@ -1372,25 +1511,7 @@ Warning, gotchas or tips that might help save users time.
      rake rdoc
    -

    8.2. Store models, views, helpers, and controllers in your plugins

    -

    You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:

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

    -

    8.3. Write custom Rake tasks in your plugin

    +

    10.2. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    vendor/plugins/yaffle/tasks/yaffle.rake

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

    -

    8.4. Store plugins in alternate locations

    +

    10.3. Store plugins in alternate locations

    You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.

    Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.

    You can even store plugins inside of other plugins for complete plugin madness!

    @@ -1423,14 +1544,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
     
    -

    8.5. Create your own Plugin Loaders and Plugin Locators

    +

    10.4. Create your own Plugin Loaders and Plugin Locators

    If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.

    -

    8.6. Use Custom Plugin Generators

    +

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

    -

    9. Appendix

    +

    11. Appendix

    -

    9.1. References

    +

    11.1. References

    • @@ -1453,7 +1574,7 @@ http://www.gnu.org/software/src-highlite -->

    -

    9.2. Final plugin directory structure

    +

    11.2. Final plugin directory structure

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

    diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt new file mode 100644 index 0000000000..ee408adb1d --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -0,0 +1,59 @@ +== Add a controller == + +This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. + +You can test your plugin's controller as you would test any other controller: + +*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +require 'woodpeckers_controller' +require 'action_controller/test_process' + +class WoodpeckersController; def rescue_action(e) raise e end; end + +class WoodpeckersControllerTest < Test::Unit::TestCase + def setup + @controller = WoodpeckersController.new + @request = ActionController::TestRequest.new + @response = ActionController::TestResponse.new + end + + def test_index + get :index + assert_response :success + end +end +---------------------------------------------- + +This is just a simple test to make sure the controller is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models controllers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +---------------------------------------------- + + +*vendor/plugins/yaffle/lib/app/controllers/woodpeckers_controller.rb:* + +[source, ruby] +---------------------------------------------- +class WoodpeckersController < ActionController::Base + + def index + render :text => "Squawk!" + end + +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index bd7dfe65c3..67e6aec39c 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -35,12 +35,16 @@ include::core_ext.txt[] include::acts_as_yaffle.txt[] -include::view_helper.txt[] - include::migration_generator.txt[] include::generator_method.txt[] +include::models.txt[] + +include::controllers.txt[] + +include::view_helper.txt[] + include::custom_route.txt[] include::odds_and_ends.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 743d512132..f4fc32481c 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -1,4 +1,4 @@ -== Create a migration generator == +== Create a generator == Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. @@ -30,7 +30,7 @@ require 'rails_generator' require 'rails_generator/scripts/generate' require 'rails_generator/scripts/destroy' -class YaffleTest < Test::Unit::TestCase +class GeneratorTest < Test::Unit::TestCase def fake_rails_root File.join(File.dirname(__FILE__), 'rails_root') @@ -124,7 +124,6 @@ end ------------------------------------------------------------------ - === The USAGE file === Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt new file mode 100644 index 0000000000..458edec80a --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -0,0 +1,76 @@ +== Add a model == + +This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: + +--------------------------------------------------------- +vendor/plugins/yaffle/ +|-- lib +| |-- app +| | |-- controllers +| | |-- helpers +| | |-- models +| | | `-- woodpecker.rb +| | `-- views +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +--------------------------------------------------------- + +As always, start with a test: + +*vendor/plugins/yaffle/yaffle/woodpecker_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class WoodpeckerTest < Test::Unit::TestCase + load_schema + + def test_woodpecker + assert_kind_of Woodpecker, Woodpecker.new + end +end +---------------------------------------------- + +This is just a simple test to make sure the class is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end +---------------------------------------------- + +Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. Removing directories from the 'load_once_paths' allow those changes to picked up as soon as you save the file - without having to restart the web server. This is particularly useful as you develop the plugin. + + +*vendor/plugins/yaffle/lib/app/models/woodpecker.rb:* + +[source, ruby] +---------------------------------------------- +class Woodpecker < ActiveRecord::Base +end +---------------------------------------------- + +Finally, add the following to your plugin's 'schema.rb': + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt index a52e1c8fdb..e328c04a79 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -19,28 +19,6 @@ Once your comments are good to go, navigate to your plugin directory and run: rake rdoc - -=== Store models, views, helpers, and controllers in your plugins === - -You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: - -[source, ruby] ---------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -%w{ models controllers helpers }.each do |dir| - path = File.join(directory, 'lib', dir) - $LOAD_PATH << path - Dependencies.load_paths << path - Dependencies.load_once_paths.delete(path) -end ---------------------------------------------------------- - -Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. - -Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. - - === Write custom Rake tasks in your plugin === When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt index 9e6763bc30..6ea2a37fa7 100644 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -115,6 +115,9 @@ ActiveRecord::Schema.define(:version => 0) do t.string :last_tweet t.datetime :last_tweeted_at end + create_table :woodpeckers, :force => true do |t| + t.string :name + end end ---------------------------------------------- -- cgit v1.2.3 From 88a13fad4fae2c2088188008248e15498a2ca466 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 03:02:05 -0500 Subject: Rails plugin: Expanded helpers section --- railties/doc/guides/html/creating_plugins.html | 75 ++++++++-------------- .../doc/guides/source/creating_plugins/helpers.txt | 51 +++++++++++++++ .../doc/guides/source/creating_plugins/index.txt | 2 +- .../guides/source/creating_plugins/view_helper.txt | 61 ------------------ 4 files changed, 78 insertions(+), 111 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/helpers.txt delete mode 100644 railties/doc/guides/source/creating_plugins/view_helper.txt diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 3fa7bff260..023a4ddbab 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -258,7 +258,7 @@ ul#navMain { Add a controller
  • - Create a squawk_info_for view helper + Add a helper
  • Add a Custom Route @@ -1330,79 +1330,56 @@ http://www.gnu.org/software/src-highlite -->

    Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.

    -

    8. Create a squawk_info_for view helper

    +

    8. Add a helper

    -

    Creating a view helper is a 3-step process:

    -
      -
    • -

      -Add an appropriately named file to the lib directory. -

      -
    • -
    • -

      -Require the file and hooks in init.rb. -

      -
    • -
    • -

      -Write the tests. -

      -
    • -
    -

    First, create the test to define the functionality you want:

    -

    vendor/plugins/yaffle/test/view_helpers_test.rb

    +

    This section describes how to add a helper named WoodpeckersHelper to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.

    +

    You can test your plugin's helper as you would test any other helper:

    +

    vendor/plugins/yaffle/test/woodpeckers_helper_test.rb

    require File.dirname(__FILE__) + '/test_helper.rb'
    -include YaffleViewHelper
    +include WoodpeckersHelper
     
    -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)
    +class WoodpeckersHelperTest < Test::Unit::TestCase
    +  def test_tweet
    +    assert_equal "Tweet! Hello", tweet("Hello")
       end
     end
     
    -

    Then add the following statements to init.rb:

    -

    vendor/plugins/yaffle/init.rb

    +

    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:

    -
    require "view_helpers"
    -ActionView::Base.send :include, YaffleViewHelper
    +
    %w{ models controllers helpers }.each do |dir|
    +  path = File.join(File.dirname(__FILE__), 'app', dir)
    +  $LOAD_PATH << path
    +  ActiveSupport::Dependencies.load_paths << path
    +  ActiveSupport::Dependencies.load_once_paths.delete(path)
    +end
    +
    +ActionView::Base.send :include, WoodpeckersHelper
     
    -

    Then add the view helpers file and

    -

    vendor/plugins/yaffle/lib/view_helpers.rb

    +

    vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.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
    +
    module WoodpeckersHelper
    +
    +  def tweet(text)
    +    "Tweet! #{text}"
       end
    +
     end
     
    -

    You can also test this in script/console by using the helper method:

    -
    -
    -
    $ ./script/console
    ->> helper.squawk_info_for(@some_yaffle_instance)
    -
    +

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

    9. Add a Custom Route

    diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt new file mode 100644 index 0000000000..51b4cebb01 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -0,0 +1,51 @@ +== Add a helper == + +This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. + +You can test your plugin's helper as you would test any other helper: + +*vendor/plugins/yaffle/test/woodpeckers_helper_test.rb* + +[source, ruby] +--------------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +include WoodpeckersHelper + +class WoodpeckersHelperTest < Test::Unit::TestCase + def test_tweet + assert_equal "Tweet! Hello", tweet("Hello") + end +end +--------------------------------------------------------------- + +This is just a simple test to make sure the helper is being loaded correctly. After watching it fail with `rake`, you can make it pass like so: + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +ActionView::Base.send :include, WoodpeckersHelper +---------------------------------------------- + + +*vendor/plugins/yaffle/lib/app/helpers/woodpeckers_helper.rb:* + +[source, ruby] +---------------------------------------------- +module WoodpeckersHelper + + def tweet(text) + "Tweet! #{text}" + end + +end +---------------------------------------------- + +Now your test should be passing, and you should be able to use the Woodpeckers helper in your app. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 67e6aec39c..19484e2830 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -43,7 +43,7 @@ include::models.txt[] include::controllers.txt[] -include::view_helper.txt[] +include::helpers.txt[] include::custom_route.txt[] diff --git a/railties/doc/guides/source/creating_plugins/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt deleted file mode 100644 index 4eaec93824..0000000000 --- a/railties/doc/guides/source/creating_plugins/view_helper.txt +++ /dev/null @@ -1,61 +0,0 @@ -== Create a `squawk_info_for` view helper == - -Creating a view helper is a 3-step process: - - * Add an appropriately named file to the 'lib' directory. - * Require the file and hooks in 'init.rb'. - * Write the tests. - -First, create the test to define the functionality you want: - -*vendor/plugins/yaffle/test/view_helpers_test.rb* - -[source, ruby] ---------------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' -include YaffleViewHelper - -class ViewHelpersTest < Test::Unit::TestCase - def test_squawk_info_for_should_return_the_text_and_date - time = Time.now - hickwall = Hickwall.new - hickwall.last_squawk = "Hello World" - hickwall.last_squawked_at = time - assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) - end -end ---------------------------------------------------------------- - -Then add the following statements to init.rb: - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] ---------------------------------------------------------------- -require "view_helpers" -ActionView::Base.send :include, YaffleViewHelper ---------------------------------------------------------------- - -Then add the view helpers file and - -*vendor/plugins/yaffle/lib/view_helpers.rb* - -[source, ruby] ---------------------------------------------------------------- -module YaffleViewHelper - def squawk_info_for(yaffle) - returning "" do |result| - result << yaffle.read_attribute(yaffle.class.yaffle_text_field) - result << ", " - result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s - end - end -end ---------------------------------------------------------------- - -You can also test this in script/console by using the `helper` method: - ---------------------------------------------------------------- -$ ./script/console ->> helper.squawk_info_for(@some_yaffle_instance) ---------------------------------------------------------------- -- cgit v1.2.3 From fa9ea057d1252a578f8e056defef41b93853bc8b Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Fri, 14 Nov 2008 03:14:09 -0500 Subject: Plugin guide: updated to start working with GemPlugin --- railties/doc/guides/html/creating_plugins.html | 10 +++++----- railties/doc/guides/source/creating_plugins/core_ext.txt | 5 ++--- railties/doc/guides/source/creating_plugins/gem.txt | 1 + railties/doc/guides/source/creating_plugins/test_setup.txt | 3 ++- 4 files changed, 10 insertions(+), 9 deletions(-) create mode 100644 railties/doc/guides/source/creating_plugins/gem.txt diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 023a4ddbab..375d216b4a 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -447,6 +447,7 @@ create vendor/plugins/yaffle/generators/yaffle/templates create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE
    +

    To begin just change one thing - move init.rb to rails/init.rb.

    1.3. Setup the plugin for testing

    If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

    To setup your plugin to allow for easy testing you'll need to add 3 files:

    @@ -553,7 +554,7 @@ ENV['RAILS_ROOT ActiveRecord::Base.establish_connection(config[db_adapter]) load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../init.rb' + require File.dirname(__FILE__) + '/../rails/init.rb' end

    Now whenever you write a test that requires the database, you can call load_schema.

    @@ -668,14 +669,13 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String

    A common pattern in rails plugins is to set up the file structure like this:

    -
    |-- init.rb
    -|-- lib
    +
    |-- lib
     |   |-- yaffle
     |   |   `-- core_ext.rb
     |   `-- yaffle.rb
    -

    The first thing we need to to is to require our lib/yaffle.rb file from init.rb:

    -

    vendor/plugins/yaffle/init.rb

    +

    The first thing we need to to is to require our lib/yaffle.rb file from rails/init.rb:

    +

    vendor/plugins/yaffle/rails/init.rb

    end
    -

    7. Changelog

    +

    7. Using the errors collection

    +
    +

    You can do more than just call valid? upon your objects based on the existance of the errors collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state.

    +
      +
    • +

      +add_to_base lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. add_to_base receives a string with the message. +

      +
    • +
    +
    +
    +
    class Person < ActiveRecord::Base
    +  def a_method_used_for_validation_purposes
    +    errors.add_to_base("This person is invalid because ...")
    +  end
    +end
    +
    +
      +
    • +

      +add lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. add receives a symbol with the name of the attribute that you want to add the message to and the message itself. +

      +
    • +
    +
    +
    +
    class Person < ActiveRecord::Base
    +  def a_method_used_for_validation_purposes
    +    errors.add(:name, "can't have the characters !@#$%*()_-+=")
    +  end
    +end
    +
    +
      +
    • +

      +invalid? is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check. +

      +
    • +
    +
    +
    +
    class Person < ActiveRecord::Base
    +  validates_presence_of :name, :email
    +end
    +
    +person = Person.new(:name => "John Doe")
    +person.invalid?(:email) # => true
    +
    +
      +
    • +

      +on is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the errors collection for the given attribute. If there are no errors related to the attribute, on will return nil. If there is just one errors message for this attribute, on will return a string with the message. When errors holds two or more error messages for the attribute, on will return an array of strings, each one with one error message. +

      +
    • +
    +
    +
    +
    class Person < ActiveRecord::Base
    +  validates_presence_of :name
    +  validates_length_of :name, :minimum => 3
    +end
    +
    +person = Person.new(:name => "John Doe")
    +person.valid? # => true
    +person.errors.on(:name) # => nil
    +
    +person = Person.new(:name => "JD")
    +person.valid? # => false
    +person.errors.on(:name) # => "is too short (minimum is 3 characters)"
    +
    +person = Person.new
    +person.valid? # => false
    +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
    +
    +
      +
    • +

      +clear is used when you intentionally wants to clear all the messages in the errors collection. +

      +
    • +
    +
    +
    +
    class Person < ActiveRecord::Base
    +  validates_presence_of :name
    +  validates_length_of :name, :minimum => 3
    +end
    +
    +person = Person.new
    +puts person.valid? # => false
    +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"]
    +person.errors.clear
    +person.errors # => nil
    +
    +
    +

    8. Changelog

    diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index fd6eb86b0b..87f3392551 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -399,6 +399,83 @@ class Invoice < ActiveRecord::Base end ------------------------------------------------------------------ +== Using the +errors+ collection + +You can do more than just call +valid?+ upon your objects based on the existance of the +errors+ collection. Here is a list of the other available methods that you can use to manipulate errors or ask for an object's state. + +* +add_to_base+ lets you add errors messages that are related to the object's state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of it's attributes. +add_to_base+ receives a string with the message. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add_to_base("This person is invalid because ...") + end +end +------------------------------------------------------------------ + +* +add+ lets you manually add messages that are related to particular attributes. When writing those messages, keep in mind that Rails will prepend them with the name of the attribute that holds the error, so write it in a way that makes sense. +add+ receives a symbol with the name of the attribute that you want to add the message to and the message itself. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + def a_method_used_for_validation_purposes + errors.add(:name, "can't have the characters !@#$%*()_-+=") + end +end +------------------------------------------------------------------ + +* +invalid?+ is used when you want to check if a particular attribute is invalid. It receives a symbol with the name of the attribute that you want to check. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name, :email +end + +person = Person.new(:name => "John Doe") +person.invalid?(:email) # => true +------------------------------------------------------------------ + +* +on+ is used when you want to check the error messages for a specific attribute. It will return different kinds of objects depending on the state of the +errors+ collection for the given attribute. If there are no errors related to the attribute, +on+ will return +nil+. If there is just one errors message for this attribute, +on+ will return a string with the message. When +errors+ holds two or more error messages for the attribute, +on+ will return an array of strings, each one with one error message. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new(:name => "John Doe") +person.valid? # => true +person.errors.on(:name) # => nil + +person = Person.new(:name => "JD") +person.valid? # => false +person.errors.on(:name) # => "is too short (minimum is 3 characters)" + +person = Person.new +person.valid? # => false +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +------------------------------------------------------------------ + +* +clear+ is used when you intentionally wants to clear all the messages in the +errors+ collection. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name + validates_length_of :name, :minimum => 3 +end + +person = Person.new +puts person.valid? # => false +person.errors.on(:name) # => ["can't be blank", "is too short (minimum is 3 characters)"] +person.errors.clear +person.errors # => nil +------------------------------------------------------------------ + + == Changelog http://rails.lighthouseapp.com/projects/16213/tickets/26-active-record-validations-and-callbacks -- cgit v1.2.3 From 097b4678f6d52e86a9d46ba6c862e6eb6ef7bbdd Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 20:30:42 -0500 Subject: Plugin Guide: added section on migrations, updated generator section, tightened up spacing of P's inside LI's --- railties/doc/guides/html/configuring.html | 119 ++- railties/doc/guides/html/creating_plugins.html | 952 +++++++++++++-------- railties/doc/guides/html/migrations.html | 3 +- .../source/creating_plugins/acts_as_yaffle.txt | 2 +- .../guides/source/creating_plugins/appendix.txt | 73 +- .../guides/source/creating_plugins/controllers.txt | 2 +- .../source/creating_plugins/custom_route.txt | 69 -- .../doc/guides/source/creating_plugins/gem.txt | 2 + .../source/creating_plugins/generator_commands.txt | 140 +++ .../source/creating_plugins/generator_method.txt | 89 -- .../guides/source/creating_plugins/generators.txt | 103 +++ .../doc/guides/source/creating_plugins/helpers.txt | 2 +- .../doc/guides/source/creating_plugins/index.txt | 16 +- .../creating_plugins/migration_generator.txt | 156 ---- .../guides/source/creating_plugins/migrations.txt | 209 +++++ .../doc/guides/source/creating_plugins/models.txt | 2 +- .../doc/guides/source/creating_plugins/routes.txt | 69 ++ .../doc/guides/source/creating_plugins/setup.txt | 64 ++ .../guides/source/creating_plugins/test_setup.txt | 230 ----- .../doc/guides/source/creating_plugins/tests.txt | 165 ++++ railties/doc/guides/source/stylesheets/base.css | 4 + 21 files changed, 1505 insertions(+), 966 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/custom_route.txt create mode 100644 railties/doc/guides/source/creating_plugins/generator_commands.txt delete mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt create mode 100644 railties/doc/guides/source/creating_plugins/generators.txt delete mode 100644 railties/doc/guides/source/creating_plugins/migration_generator.txt create mode 100644 railties/doc/guides/source/creating_plugins/migrations.txt create mode 100644 railties/doc/guides/source/creating_plugins/routes.txt create mode 100644 railties/doc/guides/source/creating_plugins/setup.txt delete mode 100644 railties/doc/guides/source/creating_plugins/test_setup.txt create mode 100644 railties/doc/guides/source/creating_plugins/tests.txt diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html index 4aa3a0f545..ea5f162cb7 100644 --- a/railties/doc/guides/html/configuring.html +++ b/railties/doc/guides/html/configuring.html @@ -205,6 +205,9 @@ ul#navMain { Using a Preinitializer
  • + Initialization Process Settings +
  • +
  • Configuring Rails Components
      @@ -229,6 +232,9 @@ ul#navMain { Using an After-Initializer
    • + Rails Environment Settings +
    • +
    • Changelog
    • @@ -264,26 +270,81 @@ after-initializer

      2. Using a Preinitializer

      -

      3. Configuring Rails Components

      +

      3. Initialization Process Settings

      +
      +
      +

      4. Configuring Rails Components

      -

      3.1. Configuring Active Record

      -

      3.2. Configuring Action Controller

      -

      3.3. Configuring Action View

      -

      3.4. Configuring Action Mailer

      -

      3.5. Configuring Active Resource

      -

      3.6. Configuring Active Support

      +

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

      +

      4.2. Configuring Action Controller

      +

      ActionController::Base includes a number of configuration settings:

      +

      asset_host provides a string that is prepended to all of the URL-generating helpers in AssetHelper. This is designed to allow moving all javascript, CSS, and image files to a separate asset host.

      +

      consider_all_requests_local is generally set to true during development and false during production; if it is set to true, then any error will cause detailed debugging information to be dumped in the HTTP response. For finer-grained control, set this to false and implement local_request? to specify which requests should provide debugging information on errors.

      +

      allow_concurrency should be set to true to allow concurrent (threadsafe) action processing. Set to false by default.

      +

      param_parsers provides an array of handlers that can extract information from incoming HTTP requests and add it to the params hash. By default, parsers for multipart forms, URL-encoded forms, XML, and JSON are active.

      +

      default_charset specifies the default character set for all renders. The default is "utf-8".

      +

      logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Controller. Set to nil to disable logging.

      +

      resource_action_separator gives the token to be used between resources and actions when building or interpreting RESTful URLs. By default, this is "/".

      +

      resource_path_names is a hash of default names for several RESTful actions. By default, the new action is named new and the edit action is named edit.

      +

      request_forgery_protection_token sets the token parameter name for RequestForgery. Calling protect_from_forgery sets it to :authenticity_token by default.

      +

      optimise_named_routes turns on some optimizations in generating the routing table. It is set to true by default.

      +

      use_accept_header sets the rules for determining the response format. If this is set to true (the default) then respond_to and Request#format will take the Accept header into account. If it is set to false then the request format will be determined solely by examining params[:format]. If there is no format parameter, then the response format will be either HTML or Javascript depending on whether the request is an AJAX request.

      +

      allow_forgery_protection enables or disables CSRF protection. By default this is false in test mode and true in all other modes.

      +

      relative_url_root can be used to tell Rails that you are deploying to a subdirectory. The default is ENV[RAILS_RELATIVE_URL_ROOT].

      +

      The caching code adds two additional settings:

      +

      ActionController::Caching::Pages.page_cache_directory sets the directory where Rails will create cached pages for your web server. The default is Rails.public_path (which is usually set to RAILS_ROOT "/public"+).

      +

      ActionController::Caching::Pages.page_cache_extension sets the extension to be used when generating pages for the cache (this is ignored if the incoming request already has an extension). The default is .html.

      +

      The dispatcher includes one setting:

      +

      ActionController::Dispatcher.error_file_path gives the path where Rails will look for error files such as 404.html. The default is Rails.public_path.

      +

      The Active Record session store can also be configured:

      +

      CGI::Session::ActiveRecordStore::Session.data_column_name sets the name of the column to use to store session data. By default it is data

      +

      4.3. Configuring Action View

      +

      4.4. Configuring Action Mailer

      +

      4.5. Configuring Active Resource

      +

      4.6. Configuring Active Support

      -

      4. Using Initializers

      +

      5. Using Initializers

      organization, controlling load order
      -

      5. Using an After-Initializer

      +

      6. Using an After-Initializer

      +
      +
      +

      7. Rails Environment Settings

      +

      ENV

      -

      6. Changelog

      +

      8. Changelog

      diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 375d216b4a..45c81f2af1 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -199,14 +199,18 @@ ul#navMain {

      Chapters

      1. - Preparation + Setup +
      2. +
      3. + Tests +
      4. - Add an acts_as_yaffle method to Active Record + Add an acts_as method to Active Record
      5. - Create a generator + Models +
      6. +
      7. + Controllers +
      8. +
      9. + Helpers +
      10. +
      11. + Routes +
      12. +
      13. + Generators
      14. - Add a custom generator command -
      15. -
      16. - Add a model + Generator Commands
      17. - Add a controller -
      18. -
      19. - Add a helper + Migrations +
      20. - Add a Custom Route + Generating migrations
      21. Odds and ends @@ -388,7 +401,7 @@ A custom route method that can be used in routes.rb

        For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development.

        -

        1. Preparation

        +

        1. Setup

        1.1. Create the basic app

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

        @@ -448,7 +461,9 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE

        To begin just change one thing - move init.rb to rails/init.rb.

        -

        1.3. Setup the plugin for testing

        + +

        2. Tests

        +

        If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

        To setup your plugin to allow for easy testing you'll need to add 3 files:

          @@ -558,7 +573,7 @@ ENV['RAILS_ROOT end

        Now whenever you write a test that requires the database, you can call load_schema.

        -

        1.4. Run the plugin tests

        +

        2.1. Run the plugin tests

        Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:

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

        @@ -619,7 +634,7 @@ rake DB=postgresql

        Now you are ready to test-drive your plugin!

        -

        2. Extending core classes

        +

        3. Extending core classes

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

          @@ -634,7 +649,7 @@ Creating and requiring the correct files

        -

        2.1. Creating the test

        +

        3.1. Creating the test

        In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:

        vendor/plugins/yaffle/test/core_ext_test.rb

        @@ -665,7 +680,7 @@ 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.

        -

        2.2. Organize your files

        +

        3.2. Organize your files

        A common pattern in rails plugins is to set up the file structure like this:

        @@ -712,7 +727,7 @@ http://www.gnu.org/software/src-highlite --> >> "Hello World".to_squawk => "squawk! Hello World"
        -

        2.3. Working with init.rb

        +

        3.3. Working with init.rb

        When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.

        Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.

        If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:

        @@ -742,7 +757,7 @@ http://www.gnu.org/software/src-highlite --> end -

        3. Add an acts_as_yaffle method to Active Record

        +

        4. Add an acts_as method to Active Record

        A common pattern in plugins is to add a method called acts_as_something to models. In this case, you want to write a method called acts_as_yaffle that adds a squawk method to your models.

        To begin, set up your files so that you have:

        @@ -801,7 +816,7 @@ http://www.gnu.org/software/src-highlite --> end

        With structure you can easily separate the methods that will be used for the class (like Hickwall.some_method) and the instance (like @hickwell.some_method).

        -

        3.1. Add a class method

        +

        4.1. Add a class method

        This plugin will expect that you've added a method to your model named last_squawk. However, the plugin users might have already defined a method on their model named last_squawk that they use for something else. This plugin will allow the name to be changed by adding a class method called yaffle_text_field.

        To start out, write a failing test that shows the behavior you'd like:

        vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

        @@ -854,7 +869,7 @@ http://www.gnu.org/software/src-highlite --> ActiveRecord::Base.send :include, Yaffle -

        3.2. Add an instance method

        +

        4.2. Add an instance method

        This plugin will add a method named squawk to any Active Record objects that call acts_as_yaffle. The squawk method will simply set the value of one of the fields in the database.

        To start out, write a failing test that shows the behavior you'd like:

        vendor/plugins/yaffle/test/acts_as_yaffle_test.rb

        @@ -936,267 +951,7 @@ ActiveRecord::Base4. Create a generator -
        -

        Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.

        -

        Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.

        -

        To create a generator you must:

        -
          -
        • -

          -Add your instructions to the manifest method of the generator -

          -
        • -
        • -

          -Add any necessary template files to the templates directory -

          -
        • -
        • -

          -Test the generator manually by running various combinations of script/generate and script/destroy -

          -
        • -
        • -

          -Update the USAGE file to add helpful documentation for your generator -

          -
        • -
        -

        4.1. Testing generators

        -

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

        -
          -
        • -

          -Creates a new fake rails root directory that will serve as destination -

          -
        • -
        • -

          -Runs the generator forward and backward, making whatever assertions are necessary -

          -
        • -
        • -

          -Removes the fake rails root -

          -
        • -
        -

        For the generator in this section, the test could look something like this:

        -

        vendor/plugins/yaffle/test/yaffle_generator_test.rb

        -
        -
        -
        require File.dirname(__FILE__) + '/test_helper.rb'
        -require 'rails_generator'
        -require 'rails_generator/scripts/generate'
        -require 'rails_generator/scripts/destroy'
        -
        -class GeneratorTest < Test::Unit::TestCase
        -
        -  def fake_rails_root
        -    File.join(File.dirname(__FILE__), 'rails_root')
        -  end
        -
        -  def file_list
        -    Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
        -  end
        -
        -  def setup
        -    FileUtils.mkdir_p(fake_rails_root)
        -    @original_files = file_list
        -  end
        -
        -  def teardown
        -    FileUtils.rm_r(fake_rails_root)
        -  end
        -
        -  def test_generates_correct_file_name
        -    Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
        -    new_file = (file_list - @original_files).first
        -    assert_match /add_yaffle_fields_to_bird/, new_file
        -  end
        -
        -end
        -
        -

        You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.

        -

        4.2. Adding to the manifest

        -

        This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. To start, update your generator file to look like this:

        -

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

        -
        -
        -
        class YaffleGenerator < Rails::Generator::NamedBase
        -  def manifest
        -    record do |m|
        -      m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
        -        :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
        -      }
        -    end
        -  end
        -
        -  private
        -    def custom_file_name
        -      custom_name = class_name.underscore.downcase
        -      custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
        -    end
        -
        -    def yaffle_local_assigns
        -      returning(assigns = {}) do
        -        assigns[:migration_action] = "add"
        -        assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
        -        assigns[:table_name] = custom_file_name
        -        assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
        -      end
        -    end
        -end
        -
        -

        The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.

        -

        It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.

        -

        4.3. Manually test the generator

        -

        To run the generator, type the following at the command line:

        -
        -
        -
        ./script/generate yaffle bird
        -
        -

        and you will see a new file:

        -

        db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

        -
        -
        -
        class AddYaffleFieldsToBirds < ActiveRecord::Migration
        -  def self.up
        -    add_column :birds, :last_squawk, :string
        -  end
        -
        -  def self.down
        -    remove_column :birds, :last_squawk
        -  end
        -end
        -
        -

        4.4. The USAGE file

        -

        Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:

        -
        -
        -
        script/generate
        -
        -

        You should see something like this:

        -
        -
        -
        Installed Generators
        -  Plugins (vendor/plugins): yaffle
        -  Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration
        -
        -

        When you run script/generate yaffle you should see the contents of your vendor/plugins/yaffle/generators/yaffle/USAGE file.

        -

        For this plugin, update the USAGE file looks like this:

        -
        -
        -
        Description:
        -    Creates a migration that adds yaffle squawk fields to the given model
        -
        -Example:
        -    ./script/generate yaffle hickwall
        -
        -    This will create:
        -        db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
        -
        -
        -

        5. Add a custom generator command

        -
        -

        You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.

        -

        This section describes how you you can create your own commands to add and remove a line of text from routes.rb. This example creates a very simple method that adds or removes a text file.

        -

        To start, add the following test method:

        -

        vendor/plugins/yaffle/test/generator_test.rb

        -
        -
        -
        def test_generates_definition
        -  Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root)
        -  definition = File.read(File.join(fake_rails_root, "definition.txt"))
        -  assert_match /Yaffle\:/, definition
        -end
        -
        -

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

        -

        vendor/plugins/yaffle/generators/yaffle/templates/definition.txt

        -
        -
        -
        Yaffle: A bird
        -
        -

        vendor/plugins/yaffle/lib/yaffle.rb

        -
        -
        -
        require "yaffle/commands"
        -
        -

        vendor/plugins/yaffle/lib/commands.rb

        -
        -
        -
        require 'rails_generator'
        -require 'rails_generator/commands'
        -
        -module Yaffle #:nodoc:
        -  module Generator #:nodoc:
        -    module Commands #:nodoc:
        -      module Create
        -        def yaffle_definition
        -          file("definition.txt", "definition.txt")
        -        end
        -      end
        -
        -      module Destroy
        -        def yaffle_definition
        -          file("definition.txt", "definition.txt")
        -        end
        -      end
        -
        -      module List
        -        def yaffle_definition
        -          file("definition.txt", "definition.txt")
        -        end
        -      end
        -
        -      module Update
        -        def yaffle_definition
        -          file("definition.txt", "definition.txt")
        -        end
        -      end
        -    end
        -  end
        -end
        -
        -Rails::Generator::Commands::Create.send   :include,  Yaffle::Generator::Commands::Create
        -Rails::Generator::Commands::Destroy.send  :include,  Yaffle::Generator::Commands::Destroy
        -Rails::Generator::Commands::List.send     :include,  Yaffle::Generator::Commands::List
        -Rails::Generator::Commands::Update.send   :include,  Yaffle::Generator::Commands::Update
        -
        -

        Finally, call your new method in the manifest:

        -

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

        -
        -
        -
        class YaffleGenerator < Rails::Generator::NamedBase
        -  def manifest
        -    m.yaffle_definition
        -  end
        -end
        -
        -
        -

        6. Add a model

        +

        5. Models

        This section describes how to add a model named Woodpecker to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this:

        @@ -1271,7 +1026,7 @@ http://www.gnu.org/software/src-highlite -->

        Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.

        -

        7. Add a controller

        +

        6. Controllers

        This section describes how to add a controller named woodpeckers to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.

        You can test your plugin's controller as you would test any other controller:

        @@ -1330,7 +1085,7 @@ http://www.gnu.org/software/src-highlite -->

        Now your test should be passing, and you should be able to use the Woodpeckers controller in your app. If you add a route for the woodpeckers controller you can start up your server and go to http://localhost:3000/woodpeckers to see your controller in action.

        -

        8. Add a helper

        +

        7. Helpers

        This section describes how to add a helper named WoodpeckersHelper to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller.

        You can test your plugin's helper as you would test any other helper:

        @@ -1381,7 +1136,7 @@ http://www.gnu.org/software/src-highlite -->

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

        -

        9. Add a Custom Route

        +

        8. Routes

        Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.

        vendor/plugins/yaffle/test/routing_test.rb

        @@ -1454,41 +1209,541 @@ http://www.gnu.org/software/src-highlite -->

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

        -

        10. Odds and ends

        +

        9. Generators

        -

        10.1. Generate RDoc Documentation

        -

        Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

        -

        The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

        +

        Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.

        +

        Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.

        +

        To add a generator to a plugin:

        • -Your name. +Write a test

        • -How to install. +Add your instructions to the manifest method of the generator

        • -How to add the functionality to the app (several examples of common use cases). +Add any necessary template files to the templates directory

        • -Warning, gotchas or tips that might help save users time. +Update the USAGE file to add helpful documentation for your generator

        -

        Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.

        -

        Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.

        -

        Once your comments are good to go, navigate to your plugin directory and run:

        -
        +

        9.1. Testing generators

        +

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

        +
          +
        • +

          +Creates a new fake rails root directory that will serve as destination +

          +
        • +
        • +

          +Runs the generator +

          +
        • +
        • +

          +Asserts that the correct files were generated +

          +
        • +
        • +

          +Removes the fake rails root +

          +
        • +
        +

        This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this:

        +

        vendor/plugins/yaffle/test/definition_generator_test.rb

        +
        +
        +
        require File.dirname(__FILE__) + '/test_helper.rb'
        +require 'rails_generator'
        +require 'rails_generator/scripts/generate'
        +
        +class DefinitionGeneratorTest < Test::Unit::TestCase
        +
        +  def fake_rails_root
        +    File.join(File.dirname(__FILE__), 'rails_root')
        +  end
        +
        +  def file_list
        +    Dir.glob(File.join(fake_rails_root, "*"))
        +  end
        +
        +  def setup
        +    FileUtils.mkdir_p(fake_rails_root)
        +    @original_files = file_list
        +  end
        +
        +  def teardown
        +    FileUtils.rm_r(fake_rails_root)
        +  end
        +
        +  def test_generates_correct_file_name
        +    Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root)
        +    new_file = (file_list - @original_files).first
        +    assert_equal "definition.txt", File.basename(new_file)
        +  end
        +
        +end
        +
        +

        You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.

        +

        To make it pass, create the generator:

        +

        vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb

        +
        +
        +
        class YaffleDefinitionGenerator < Rails::Generator::Base
        +  def manifest
        +    record do |m|
        +      m.file "definition.txt", "definition.txt"
        +    end
        +  end
        +end
        +
        +

        9.2. The USAGE file

        +

        If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file.

        +

        Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line:

        +
        +
        +
        ./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
        +
        +
        +

        10. Generator Commands

        +
        +

        You may have noticed above that you can used one of the built-in rails migration commands migration_template. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods.

        +

        This section describes how you you can create your own commands to add and remove a line of text from config/routes.rb.

        +

        To start, add the following test method:

        +

        vendor/plugins/yaffle/test/route_generator_test.rb

        +
        +
        +
        require File.dirname(__FILE__) + '/test_helper.rb'
        +require 'rails_generator'
        +require 'rails_generator/scripts/generate'
        +require 'rails_generator/scripts/destroy'
        +
        +class RouteGeneratorTest < Test::Unit::TestCase
        +
        +  def fake_rails_root
        +    File.join(File.dirname(__FILE__), "rails_root")
        +  end
        +
        +  def routes_path
        +    File.join(fake_rails_root, "config", "routes.rb")
        +  end
        +
        +  def setup
        +    FileUtils.mkdir_p(File.join(fake_rails_root, "config"))
        +  end
        +
        +  def teardown
        +    FileUtils.rm_r(fake_rails_root)
        +  end
        +
        +  def test_generates_route
        +    content = <<-END
        +      ActionController::Routing::Routes.draw do |map|
        +        map.connect ':controller/:action/:id'
        +        map.connect ':controller/:action/:id.:format'
        +      end
        +    END
        +    File.open(routes_path, 'wb') {|f| f.write(content) }
        +
        +    Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root)
        +    assert_match /map\.yaffle/, File.read(routes_path)
        +  end
        +
        +  def test_destroys_route
        +    content = <<-END
        +      ActionController::Routing::Routes.draw do |map|
        +        map.yaffle
        +        map.connect ':controller/:action/:id'
        +        map.connect ':controller/:action/:id.:format'
        +      end
        +    END
        +    File.open(routes_path, 'wb') {|f| f.write(content) }
        +
        +    Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root)
        +    assert_no_match /map\.yaffle/, File.read(routes_path)
        +  end
        +end
        +
        +

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

        +

        vendor/plugins/yaffle/lib/yaffle.rb

        +
        +
        +
        require "yaffle/commands"
        +
        +

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

        +
        +
        +
        require 'rails_generator'
        +require 'rails_generator/commands'
        +
        +module Yaffle #:nodoc:
        +  module Generator #:nodoc:
        +    module Commands #:nodoc:
        +      module Create
        +        def yaffle_route
        +          logger.route "map.yaffle"
        +          look_for = 'ActionController::Routing::Routes.draw do |map|'
        +          unless options[:pretend]
        +            gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n  map.yaffle\n"}
        +          end
        +        end
        +      end
        +
        +      module Destroy
        +        def yaffle_route
        +          logger.route "map.yaffle"
        +          gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, ''
        +        end
        +      end
        +
        +      module List
        +        def yaffle_route
        +        end
        +      end
        +
        +      module Update
        +        def yaffle_route
        +        end
        +      end
        +    end
        +  end
        +end
        +
        +Rails::Generator::Commands::Create.send   :include,  Yaffle::Generator::Commands::Create
        +Rails::Generator::Commands::Destroy.send  :include,  Yaffle::Generator::Commands::Destroy
        +Rails::Generator::Commands::List.send     :include,  Yaffle::Generator::Commands::List
        +Rails::Generator::Commands::Update.send   :include,  Yaffle::Generator::Commands::Update
        +
        +

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

        +
        +
        +
        class YaffleRouteGenerator < Rails::Generator::Base
        +  def manifest
        +    record do |m|
        +      m.yaffle_route
        +    end
        +  end
        +end
        +
        +

        To see this work, type:

        +
        +
        +
        ./script/generate yaffle_route
        +./script/destroy yaffle_route
        +
        +
        +
  • + + +
    +Note +If you haven't set up the custom route from above, script/destroy will fail and you'll have to remove it manually.
    +
    +
    +

    11. Migrations

    +
    +

    If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins.

    +

    If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration.

    +

    Let's say you have the following migration in your plugin:

    +

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

    +
    +
    +
    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:

    +

    11.1. Create a custom rake task

    +

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

    +
    +
    +
    class CreateBirdhouses < ActiveRecord::Migration
    +  def self.up
    +    create_table :birdhouses, :force => true do |t|
    +      t.string :name
    +      t.timestamps
    +    end
    +  end
    +
    +  def self.down
    +    drop_table :birdhouses
    +  end
    +end
    +
    +

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

    +
    +
    +
    namespace :db do
    +  namespace :migrate do
    +    desc "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false."
    +    task :yaffle => :environment do
    +      ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
    +      ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
    +      Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby
    +    end
    +  end
    +end
    +
    +

    11.2. Call plugin migrations from regular migrations

    +

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

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

    db/migrate/20081116181115_create_birdhouses.rb:

    +
    +
    +
    class CreateBirdhouses < ActiveRecord::Migration
    +  def self.up
    +    Yaffle::CreateBirdhouses.up
    +  end
    +
    +  def self.down
    +    Yaffle::CreateBirdhouses.down
    +  end
    +end
    +
    +
    + + + +
    +Note +several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
    +
    +
    +

    12. Generating migrations

    +
    +

    Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:

    +
      +
    • +

      +call your script/generate script and pass in whatever options they need +

      +
    • +
    • +

      +examine the generated migration, adding/removing columns or other options as necessary +

      +
    • +
    +

    This example will demonstrate how to use one of the built-in generator methods named migration_template to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first:

    +

    vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb

    +
    +
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +require 'rails_generator'
    +require 'rails_generator/scripts/generate'
    +require 'rails_generator/scripts/destroy'
    +
    +class MigrationGeneratorTest < Test::Unit::TestCase
    +
    +  def fake_rails_root
    +    File.join(File.dirname(__FILE__), 'rails_root')
    +  end
    +
    +  def file_list
    +    Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
    +  end
    +
    +  def setup
    +    FileUtils.mkdir_p(fake_rails_root)
    +    @original_files = file_list
    +  end
    +
    +  def teardown
    +    FileUtils.rm_r(fake_rails_root)
    +  end
    +
    +  def test_generates_correct_file_name
    +    Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
    +    new_file = (file_list - @original_files).first
    +    assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
    +    assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file)
    +  end
    +
    +  def test_pluralizes_properly
    +    ActiveRecord::Base.pluralize_table_names = false
    +    Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
    +    new_file = (file_list - @original_files).first
    +    assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
    +    assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file)
    +  end
    +
    +end
    +
    +
    + + + +
    +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

    +
    +
    +
    class YaffleGenerator < Rails::Generator::NamedBase
    +  def manifest
    +    record do |m|
    +      m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
    +        :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
    +      }
    +    end
    +  end
    +
    +  private
    +    def custom_file_name
    +      custom_name = class_name.underscore.downcase
    +      custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
    +    end
    +
    +    def yaffle_local_assigns
    +      returning(assigns = {}) do
    +        assigns[:migration_action] = "add"
    +        assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
    +        assigns[:table_name] = custom_file_name
    +        assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
    +      end
    +    end
    +end
    +
    +

    The generator creates a new file in db/migrate with a timestamp and an add_column statement. It reuses the built in rails migration_template method, and reuses the built-in rails migration template.

    +

    It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off.

    +

    To run the generator, type the following at the command line:

    +
    +
    +
    ./script/generate yaffle_migration bird
    +
    +

    and you will see a new file:

    +

    db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

    +
    +
    +
    class AddYaffleFieldsToBirds < ActiveRecord::Migration
    +  def self.up
    +    add_column :birds, :last_squawk, :string
    +  end
    +
    +  def self.down
    +    remove_column :birds, :last_squawk
    +  end
    +end
    +
    +
    +

    13. Odds and ends

    +
    +

    13.1. Generate RDoc Documentation

    +

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    +

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

    +
      +
    • +

      +Your name. +

      +
    • +
    • +

      +How to install. +

      +
    • +
    • +

      +How to add the functionality to the app (several examples of common use cases). +

      +
    • +
    • +

      +Warning, gotchas or tips that might help save users time. +

      +
    • +
    +

    Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.

    +

    Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.

    +

    Once your comments are good to go, navigate to your plugin directory and run:

    +
    rake rdoc
    -

    10.2. Write custom Rake tasks in your plugin

    +

    13.2. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    vendor/plugins/yaffle/tasks/yaffle.rake

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

    -

    10.3. Store plugins in alternate locations

    +

    13.3. Store plugins in alternate locations

    You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.

    Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.

    You can even store plugins inside of other plugins for complete plugin madness!

    @@ -1521,14 +1776,14 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
     
    -

    10.4. Create your own Plugin Loaders and Plugin Locators

    +

    13.4. Create your own Plugin Loaders and Plugin Locators

    If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.

    -

    10.5. Use Custom Plugin Generators

    +

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

    -

    11. Appendix

    +

    14. Appendix

    -

    11.1. References

    +

    14.1. References

    -

    11.2. Final plugin directory structure

    +

    14.2. Final plugin directory structure

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

    -
      |-- MIT-LICENSE
    -  |-- README
    -  |-- Rakefile
    -  |-- generators
    -  |   `-- yaffle
    -  |       |-- USAGE
    -  |       |-- templates
    -  |       |   `-- definition.txt
    -  |       `-- yaffle_generator.rb
    -  |-- init.rb
    -  |-- install.rb
    -  |-- lib
    -  |   |-- acts_as_yaffle.rb
    -  |   |-- commands.rb
    -  |   |-- core_ext.rb
    -  |   |-- routing.rb
    -  |   `-- view_helpers.rb
    -  |-- tasks
    -  |   `-- yaffle_tasks.rake
    -  |-- test
    -  |   |-- acts_as_yaffle_test.rb
    -  |   |-- core_ext_test.rb
    -  |   |-- database.yml
    -  |   |-- debug.log
    -  |   |-- routing_test.rb
    -  |   |-- schema.rb
    -  |   |-- test_helper.rb
    -  |   `-- view_helpers_test.rb
    -  |-- uninstall.rb
    -  `-- yaffle_plugin.sqlite3.db
    +
    vendor/plugins/yaffle/
    +|-- MIT-LICENSE
    +|-- README
    +|-- Rakefile
    +|-- generators
    +|   `-- yaffle
    +|       |-- USAGE
    +|       |-- templates
    +|       |   `-- definition.txt
    +|       `-- yaffle_generator.rb
    +|-- install.rb
    +|-- lib
    +|   |-- app
    +|   |   |-- controllers
    +|   |   |   `-- woodpeckers_controller.rb
    +|   |   |-- helpers
    +|   |   |   `-- woodpeckers_helper.rb
    +|   |   `-- models
    +|   |       `-- woodpecker.rb
    +|   |-- yaffle
    +|   |   |-- acts_as_yaffle.rb
    +|   |   |-- commands.rb
    +|   |   `-- core_ext.rb
    +|   `-- yaffle.rb
    +|-- rails
    +|   `-- init.rb
    +|-- tasks
    +|   `-- yaffle_tasks.rake
    +|-- test
    +|   |-- acts_as_yaffle_test.rb
    +|   |-- core_ext_test.rb
    +|   |-- database.yml
    +|   |-- debug.log
    +|   |-- generator_test.rb
    +|   |-- schema.rb
    +|   |-- test_helper.rb
    +|   |-- woodpecker_test.rb
    +|   |-- woodpeckers_controller_test.rb
    +|   |-- wookpeckers_helper_test.rb
    +|   |-- yaffle_plugin.sqlite3.db
    +|   `-- yaffle_test.rb
    +`-- uninstall.rb
    diff --git a/railties/doc/guides/html/migrations.html b/railties/doc/guides/html/migrations.html index 8b580d8086..9f7fa28daf 100644 --- a/railties/doc/guides/html/migrations.html +++ b/railties/doc/guides/html/migrations.html @@ -279,7 +279,7 @@ ul#navMain {

    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.

    You'll learn all about migrations including:

      @@ -699,6 +699,7 @@ displayed saying that it can't be done.

    4. Running Migrations

    Rails provides a set of rake tasks to work with migrations which boils down to running certain sets of migrations. The very first migration related rake task you use will probably be db:migrate. In its most basic form it just runs the up method for all the migrations that have not yet been run. If there are no such migrations it exits.

    +

    Note that running the db:migrate also invokes the db:schema:dump task, which will update your db/schema.rb file to match the structure of your database.

    If you specify a target version, Active Record will run the required migrations (up or down) until it has reached the specified version. The version is the numerical prefix on the migration's filename. For example to migrate to version 20080906120000 run

    diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index de116af7db..674f086e17 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,4 +1,4 @@ -== Add an `acts_as_yaffle` method to Active Record == +== Add an 'acts_as' method to Active Record == A common pattern in plugins is to add a method called 'acts_as_something' to models. In this case, you want to write a method called 'acts_as_yaffle' that adds a 'squawk' method to your models. diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index a78890ccd5..d890f861b5 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -6,41 +6,54 @@ * http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii * http://github.com/technoweenie/attachment_fu/tree/master * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html + * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins === Final plugin directory structure === The final plugin should have a directory structure that looks something like this: ------------------------------------------------ - |-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db +vendor/plugins/yaffle/ +|-- MIT-LICENSE +|-- README +|-- Rakefile +|-- generators +| `-- yaffle +| |-- USAGE +| |-- templates +| | `-- definition.txt +| `-- yaffle_generator.rb +|-- install.rb +|-- lib +| |-- app +| | |-- controllers +| | | `-- woodpeckers_controller.rb +| | |-- helpers +| | | `-- woodpeckers_helper.rb +| | `-- models +| | `-- woodpecker.rb +| |-- yaffle +| | |-- acts_as_yaffle.rb +| | |-- commands.rb +| | `-- core_ext.rb +| `-- yaffle.rb +|-- rails +| `-- init.rb +|-- tasks +| `-- yaffle_tasks.rake +|-- test +| |-- acts_as_yaffle_test.rb +| |-- core_ext_test.rb +| |-- database.yml +| |-- debug.log +| |-- generator_test.rb +| |-- schema.rb +| |-- test_helper.rb +| |-- woodpecker_test.rb +| |-- woodpeckers_controller_test.rb +| |-- wookpeckers_helper_test.rb +| |-- yaffle_plugin.sqlite3.db +| `-- yaffle_test.rb +`-- uninstall.rb ------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index ee408adb1d..4f4417b416 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -1,4 +1,4 @@ -== Add a controller == +== Controllers == This section describes how to add a controller named 'woodpeckers' to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model. diff --git a/railties/doc/guides/source/creating_plugins/custom_route.txt b/railties/doc/guides/source/creating_plugins/custom_route.txt deleted file mode 100644 index 1fce902a4e..0000000000 --- a/railties/doc/guides/source/creating_plugins/custom_route.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Add a Custom Route == - -Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. - -*vendor/plugins/yaffle/test/routing_test.rb* - -[source, ruby] --------------------------------------------------------- -require "#{File.dirname(__FILE__)}/test_helper" - -class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end - - private - - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. - def assert_recognition(method, path, options) - result = ActionController::Routing::Routes.recognize_path(path, :method => method) - assert_equal options, result - end -end --------------------------------------------------------- - -*vendor/plugins/yaffle/init.rb* - -[source, ruby] --------------------------------------------------------- -require "routing" -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions --------------------------------------------------------- - -*vendor/plugins/yaffle/lib/routing.rb* - -[source, ruby] --------------------------------------------------------- -module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) - end - end - end -end --------------------------------------------------------- - -*config/routes.rb* - -[source, ruby] --------------------------------------------------------- -ActionController::Routing::Routes.draw do |map| - ... - map.yaffles -end --------------------------------------------------------- - -You can also see if your routes work by running `rake routes` from your app directory. diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt index 93f5e0ee89..8a0bbb3bc0 100644 --- a/railties/doc/guides/source/creating_plugins/gem.txt +++ b/railties/doc/guides/source/creating_plugins/gem.txt @@ -1 +1,3 @@ +== Gems == + http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt new file mode 100644 index 0000000000..5cce81c8bd --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -0,0 +1,140 @@ +== Generator Commands == + +You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. + +This section describes how you you can create your own commands to add and remove a line of text from 'config/routes.rb'. + +To start, add the following test method: + +*vendor/plugins/yaffle/test/route_generator_test.rb* + +[source, ruby] +----------------------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class RouteGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + + def setup + FileUtils.mkdir_p(File.join(fake_rails_root, "config")) + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_match /map\.yaffle/, File.read(routes_path) + end + + def test_destroys_route + content = <<-END + ActionController::Routing::Routes.draw do |map| + map.yaffle + map.connect ':controller/:action/:id' + map.connect ':controller/:action/:id.:format' + end + END + File.open(routes_path, 'wb') {|f| f.write(content) } + + Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) + assert_no_match /map\.yaffle/, File.read(routes_path) + end +end +----------------------------------------------------------- + +Run `rake` to watch the test fail, then make the test pass add the following: + +*vendor/plugins/yaffle/lib/yaffle.rb* + +[source, ruby] +----------------------------------------------------------- +require "yaffle/commands" +----------------------------------------------------------- + +*vendor/plugins/yaffle/lib/yaffle/commands.rb* + +[source, ruby] +----------------------------------------------------------- +require 'rails_generator' +require 'rails_generator/commands' + +module Yaffle #:nodoc: + module Generator #:nodoc: + module Commands #:nodoc: + module Create + def yaffle_route + logger.route "map.yaffle" + look_for = 'ActionController::Routing::Routes.draw do |map|' + unless options[:pretend] + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + end + end + end + + module Destroy + def yaffle_route + logger.route "map.yaffle" + gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + end + end + + module List + def yaffle_route + end + end + + module Update + def yaffle_route + end + end + end + end +end + +Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create +Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy +Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List +Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update +----------------------------------------------------------- + +*vendor/plugins/yaffle/generators/yaffle/yaffle_route_generator.rb* + +[source, ruby] +----------------------------------------------------------- +class YaffleRouteGenerator < Rails::Generator::Base + def manifest + record do |m| + m.yaffle_route + end + end +end +----------------------------------------------------------- + +To see this work, type: + +----------------------------------------------------------- +./script/generate yaffle_route +./script/destroy yaffle_route +----------------------------------------------------------- + +NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/generator_method.txt b/railties/doc/guides/source/creating_plugins/generator_method.txt deleted file mode 100644 index 126692f2c4..0000000000 --- a/railties/doc/guides/source/creating_plugins/generator_method.txt +++ /dev/null @@ -1,89 +0,0 @@ -== Add a custom generator command == - -You may have noticed above that you can used one of the built-in rails migration commands `migration_template`. If your plugin needs to add and remove lines of text from existing files you will need to write your own generator methods. - -This section describes how you you can create your own commands to add and remove a line of text from 'routes.rb'. This example creates a very simple method that adds or removes a text file. - -To start, add the following test method: - -*vendor/plugins/yaffle/test/generator_test.rb* - -[source, ruby] ------------------------------------------------------------ -def test_generates_definition - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - definition = File.read(File.join(fake_rails_root, "definition.txt")) - assert_match /Yaffle\:/, definition -end ------------------------------------------------------------ - -Run `rake` to watch the test fail, then make the test pass add the following: - -*vendor/plugins/yaffle/generators/yaffle/templates/definition.txt* - ------------------------------------------------------------ -Yaffle: A bird ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/yaffle.rb* - -[source, ruby] ------------------------------------------------------------ -require "yaffle/commands" ------------------------------------------------------------ - -*vendor/plugins/yaffle/lib/commands.rb* - -[source, ruby] ------------------------------------------------------------ -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Update - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end - -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List -Rails::Generator::Commands::Update.send :include, Yaffle::Generator::Commands::Update ------------------------------------------------------------ - -Finally, call your new method in the manifest: - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end ------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt new file mode 100644 index 0000000000..eb0fbb5ee9 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -0,0 +1,103 @@ +== Generators == + +Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. + +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. + +To add a generator to a plugin: + + * Write a test + * Add your instructions to the 'manifest' method of the generator + * Add any necessary template files to the templates directory + * Update the USAGE file to add helpful documentation for your generator + +=== Testing generators === + +Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: + + * Creates a new fake rails root directory that will serve as destination + * Runs the generator + * Asserts that the correct files were generated + * Removes the fake rails root + +This section will describe how to create a simple generator that adds a file. For the generator in this section, the test could look something like this: + +*vendor/plugins/yaffle/test/definition_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' + +class DefinitionGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle_definition"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_equal "definition.txt", File.basename(new_file) + end + +end +------------------------------------------------------------------ + +You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. + +To make it pass, create the generator: + +*vendor/plugins/yaffle/generators/yaffle_definition/yaffle_definition_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +class YaffleDefinitionGenerator < Rails::Generator::Base + def manifest + record do |m| + m.file "definition.txt", "definition.txt" + end + end +end +------------------------------------------------------------------ + +=== The USAGE file === + +If you plan to distribute your plugin, developers will expect at least a minimum of documentation. You can add simple documentation to the generator by updating the USAGE file. + +Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: + +------------------------------------------------------------------ +./script/generate +------------------------------------------------------------------ + +You should see something like this: + +------------------------------------------------------------------ +Installed Generators + Plugins (vendor/plugins): yaffle_definition + Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration +------------------------------------------------------------------ + +When you run `script/generate yaffle_definition -h` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle_definition/USAGE'. + +For this plugin, update the USAGE file could look like this: + +------------------------------------------------------------------ +Description: + Adds a file with the definition of a Yaffle to the app's main directory +------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt index 51b4cebb01..c2273813dd 100644 --- a/railties/doc/guides/source/creating_plugins/helpers.txt +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -1,4 +1,4 @@ -== Add a helper == +== Helpers == This section describes how to add a helper named 'WoodpeckersHelper' to your plugin that will behave the same as a helper in your main app. This is very similar to adding a model and a controller. diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 19484e2830..5d10fa4f31 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -29,23 +29,27 @@ This guide describes how to build a test-driven plugin that will: For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::test_setup.txt[] +include::setup.txt[] + +include::tests.txt[] include::core_ext.txt[] include::acts_as_yaffle.txt[] -include::migration_generator.txt[] - -include::generator_method.txt[] - include::models.txt[] include::controllers.txt[] include::helpers.txt[] -include::custom_route.txt[] +include::routes.txt[] + +include::generators.txt[] + +include::generator_commands.txt[] + +include::migrations.txt[] include::odds_and_ends.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt deleted file mode 100644 index f4fc32481c..0000000000 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ /dev/null @@ -1,156 +0,0 @@ -== Create a generator == - -Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. - -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. - -To create a generator you must: - - * Add your instructions to the 'manifest' method of the generator - * Add any necessary template files to the templates directory - * Test the generator manually by running various combinations of `script/generate` and `script/destroy` - * Update the USAGE file to add helpful documentation for your generator - -=== Testing generators === - -Many rails plugin authors do not test their generators, however testing generators is quite simple. A typical generator test does the following: - - * Creates a new fake rails root directory that will serve as destination - * Runs the generator forward and backward, making whatever assertions are necessary - * Removes the fake rails root - -For the generator in this section, the test could look something like this: - -*vendor/plugins/yaffle/test/yaffle_generator_test.rb* - -[source, ruby] ------------------------------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' -require 'rails_generator' -require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' - -class GeneratorTest < Test::Unit::TestCase - - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - - def setup - FileUtils.mkdir_p(fake_rails_root) - @original_files = file_list - end - - def teardown - FileUtils.rm_r(fake_rails_root) - end - - def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "bird"], :destination => fake_rails_root) - new_file = (file_list - @original_files).first - assert_match /add_yaffle_fields_to_bird/, new_file - end - -end ------------------------------------------------------------------- - -You can run 'rake' from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you. - -=== Adding to the manifest === - -This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. To start, update your generator file to look like this: - -*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* - -[source, ruby] ------------------------------------------------------------------- -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - end - - def yaffle_local_assigns - returning(assigns = {}) do - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - end - end -end ------------------------------------------------------------------- - -The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. - -It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. - -=== Manually test the generator === - -To run the generator, type the following at the command line: - ------------------------------------------------------------------- -./script/generate yaffle bird ------------------------------------------------------------------- - -and you will see a new file: - -*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* - -[source, ruby] ------------------------------------------------------------------- -class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - end - - def self.down - remove_column :birds, :last_squawk - end -end ------------------------------------------------------------------- - - -=== The USAGE file === - -Rails ships with several built-in generators. You can see all of the generators available to you by typing the following at the command line: - ------------------------------------------------------------------- -script/generate ------------------------------------------------------------------- - -You should see something like this: - ------------------------------------------------------------------- -Installed Generators - Plugins (vendor/plugins): yaffle - Builtin: controller, integration_test, mailer, migration, model, observer, plugin, resource, scaffold, session_migration ------------------------------------------------------------------- - -When you run `script/generate yaffle` you should see the contents of your 'vendor/plugins/yaffle/generators/yaffle/USAGE' file. - -For this plugin, update the USAGE file looks like this: - ------------------------------------------------------------------- -Description: - Creates a migration that adds yaffle squawk fields to the given model - -Example: - ./script/generate yaffle hickwall - - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall ------------------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt new file mode 100644 index 0000000000..7154f0bc06 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -0,0 +1,209 @@ +== Migrations == + +If your plugin requires changes to the app's database you will likely want to somehow add migrations. Rails does not include any built-in support for calling migrations from plugins, but you can still make it easy for developers to call migrations from plugins. + +If you have a very simple needs, like creating a table that will always have the same name and columns, then you can use a more simple solution, like creating a custom rake task or method. If your migration needs user input to supply table names or other options, you probably want to opt for generating a migration. + +Let's say you have the following migration in your plugin: + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + +Here are a few possibilities for how to allow developers to use your plugin migrations: + +=== Create a custom rake task === + +*vendor/plugins/yaffle/lib/db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + create_table :birdhouses, :force => true do |t| + t.string :name + t.timestamps + end + end + + def self.down + drop_table :birdhouses + end +end +---------------------------------------------- + + +*vendor/plugins/yaffle/tasks/yaffle.rake:* + +[source, ruby] +---------------------------------------------- +namespace :db do + namespace :migrate do + desc "Migrate the database through scripts in vendor/plugins/yaffle/lib/db/migrate and update db/schema.rb by invoking db:schema:dump. Target specific version with VERSION=x. Turn off output with VERBOSE=false." + task :yaffle => :environment do + ActiveRecord::Migration.verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true + ActiveRecord::Migrator.migrate("vendor/plugins/yaffle/lib/db/migrate/", ENV["VERSION"] ? ENV["VERSION"].to_i : nil) + Rake::Task["db:schema:dump"].invoke if ActiveRecord::Base.schema_format == :ruby + end + end +end +---------------------------------------------- + +=== Call plugin migrations from regular migrations === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| + require file +end +---------------------------------------------- + +*db/migrate/20081116181115_create_birdhouses.rb:* + +[source, ruby] +---------------------------------------------- +class CreateBirdhouses < ActiveRecord::Migration + def self.up + Yaffle::CreateBirdhouses.up + end + + def self.down + Yaffle::CreateBirdhouses.down + end +end +---------------------------------------------- + +NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. + +== Generating migrations == + +Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: + + * call your script/generate script and pass in whatever options they need + * examine the generated migration, adding/removing columns or other options as necessary + +This example will demonstrate how to use one of the built-in generator methods named 'migration_template' to create a migration file. Extending the rails migration generator requires a somewhat intimate knowledge of the migration generator internals, so it's best to write a test first: + +*vendor/plugins/yaffle/test/yaffle_migration_generator_test.rb* + +[source, ruby] +------------------------------------------------------------------ +require File.dirname(__FILE__) + '/test_helper.rb' +require 'rails_generator' +require 'rails_generator/scripts/generate' +require 'rails_generator/scripts/destroy' + +class MigrationGeneratorTest < Test::Unit::TestCase + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + + def setup + FileUtils.mkdir_p(fake_rails_root) + @original_files = file_list + end + + def teardown + FileUtils.rm_r(fake_rails_root) + end + + def test_generates_correct_file_name + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) + end + + def test_pluralizes_properly + ActiveRecord::Base.pluralize_table_names = false + Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + new_file = (file_list - @original_files).first + assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file + assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) + end + +end +------------------------------------------------------------------ + +NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. + +After running the test with 'rake' you can make it pass with: + +*vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb* + +[source, ruby] +------------------------------------------------------------------ +class YaffleGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, + :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" + } + end + end + + private + def custom_file_name + custom_name = class_name.underscore.downcase + custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + end + + def yaffle_local_assigns + returning(assigns = {}) do + assigns[:migration_action] = "add" + assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" + assigns[:table_name] = custom_file_name + assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] + end + end +end +------------------------------------------------------------------ + +The generator creates a new file in 'db/migrate' with a timestamp and an 'add_column' statement. It reuses the built in rails `migration_template` method, and reuses the built-in rails migration template. + +It's courteous to check to see if table names are being pluralized whenever you create a generator that needs to be aware of table names. This way people using your generator won't have to manually change the generated files if they've turned pluralization off. + +To run the generator, type the following at the command line: + +------------------------------------------------------------------ +./script/generate yaffle_migration bird +------------------------------------------------------------------ + +and you will see a new file: + +*db/migrate/20080529225649_add_yaffle_fields_to_birds.rb* + +[source, ruby] +------------------------------------------------------------------ +class AddYaffleFieldsToBirds < ActiveRecord::Migration + def self.up + add_column :birds, :last_squawk, :string + end + + def self.down + remove_column :birds, :last_squawk + end +end +------------------------------------------------------------------ + diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt index 458edec80a..dfe11f9c4e 100644 --- a/railties/doc/guides/source/creating_plugins/models.txt +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -1,4 +1,4 @@ -== Add a model == +== Models == This section describes how to add a model named 'Woodpecker' to your plugin that will behave the same as a model in your main app. When storing models, controllers, views and helpers in your plugin, it's customary to keep them in directories that match the rails directories. For this example, create a file structure like this: diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt new file mode 100644 index 0000000000..cdc20e998e --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -0,0 +1,69 @@ +== Routes == + +Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. + +*vendor/plugins/yaffle/test/routing_test.rb* + +[source, ruby] +-------------------------------------------------------- +require "#{File.dirname(__FILE__)}/test_helper" + +class RoutingTest < Test::Unit::TestCase + + def setup + ActionController::Routing::Routes.draw do |map| + map.yaffles + end + end + + def test_yaffles_route + assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" + end + + private + + # yes, I know about assert_recognizes, but it has proven problematic to + # use in these tests, since it uses RouteSet#recognize (which actually + # tries to instantiate the controller) and because it uses an awkward + # parameter order. + def assert_recognition(method, path, options) + result = ActionController::Routing::Routes.recognize_path(path, :method => method) + assert_equal options, result + end +end +-------------------------------------------------------- + +*vendor/plugins/yaffle/init.rb* + +[source, ruby] +-------------------------------------------------------- +require "routing" +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +-------------------------------------------------------- + +*vendor/plugins/yaffle/lib/routing.rb* + +[source, ruby] +-------------------------------------------------------- +module Yaffle #:nodoc: + module Routing #:nodoc: + module MapperExtensions + def yaffles + @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) + end + end + end +end +-------------------------------------------------------- + +*config/routes.rb* + +[source, ruby] +-------------------------------------------------------- +ActionController::Routing::Routes.draw do |map| + ... + map.yaffles +end +-------------------------------------------------------- + +You can also see if your routes work by running `rake routes` from your app directory. diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt new file mode 100644 index 0000000000..fcf5b459e6 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/setup.txt @@ -0,0 +1,64 @@ +== Setup == + +=== Create the basic app === + +The examples in this guide require that you have a working rails application. To create a simple rails app execute: + +------------------------------------------------ +gem install rails +rails yaffle_guide +cd yaffle_guide +script/generate scaffold bird name:string +rake db:migrate +script/server +------------------------------------------------ + +Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. + +.Editor's note: +NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. + + +=== Generate the plugin skeleton === + +Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. + +This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. + +Examples: +---------------------------------------------- +./script/generate plugin yaffle +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +To get more detailed help on the plugin generator, type `./script/generate plugin`. + +Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: + +---------------------------------------------- +./script/generate plugin yaffle --with-generator +---------------------------------------------- + +You should see the following output: + +---------------------------------------------- +create vendor/plugins/yaffle/lib +create vendor/plugins/yaffle/tasks +create vendor/plugins/yaffle/test +create vendor/plugins/yaffle/README +create vendor/plugins/yaffle/MIT-LICENSE +create vendor/plugins/yaffle/Rakefile +create vendor/plugins/yaffle/init.rb +create vendor/plugins/yaffle/install.rb +create vendor/plugins/yaffle/uninstall.rb +create vendor/plugins/yaffle/lib/yaffle.rb +create vendor/plugins/yaffle/tasks/yaffle_tasks.rake +create vendor/plugins/yaffle/test/core_ext_test.rb +create vendor/plugins/yaffle/generators +create vendor/plugins/yaffle/generators/yaffle +create vendor/plugins/yaffle/generators/yaffle/templates +create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb +create vendor/plugins/yaffle/generators/yaffle/USAGE +---------------------------------------------- + +To begin just change one thing - move 'init.rb' to 'rails/init.rb'. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt deleted file mode 100644 index 64236ff110..0000000000 --- a/railties/doc/guides/source/creating_plugins/test_setup.txt +++ /dev/null @@ -1,230 +0,0 @@ -== Preparation == - -=== Create the basic app === - -The examples in this guide require that you have a working rails application. To create a simple rails app execute: - ------------------------------------------------- -gem install rails -rails yaffle_guide -cd yaffle_guide -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -.Editor's note: -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Generate the plugin skeleton === - -Rails ships with a plugin generator which creates a basic plugin skeleton. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin yaffle -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -To get more detailed help on the plugin generator, type `./script/generate plugin`. - -Later on this guide will describe how to work with generators, so go ahead and generate your plugin with the `\--with-generator` option now: - ----------------------------------------------- -./script/generate plugin yaffle --with-generator ----------------------------------------------- - -You should see the following output: - ----------------------------------------------- -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/tasks -create vendor/plugins/yaffle/test -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib/yaffle.rb -create vendor/plugins/yaffle/tasks/yaffle_tasks.rake -create vendor/plugins/yaffle/test/core_ext_test.rb -create vendor/plugins/yaffle/generators -create vendor/plugins/yaffle/generators/yaffle -create vendor/plugins/yaffle/generators/yaffle/templates -create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb -create vendor/plugins/yaffle/generators/yaffle/USAGE ----------------------------------------------- - -To begin just change one thing - move 'init.rb' to 'rails/init.rb'. - -=== Setup the plugin for testing === - -If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A 'database.yml' file with all of your connection strings - * A 'schema.rb' file with your table definitions - * A test helper method that sets up the database - -*vendor/plugins/yaffle/test/database.yml:* - ----------------------------------------------- -sqlite: - :adapter: sqlite - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: root - :password: password - :database: yaffle_plugin_test ----------------------------------------------- - -For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: - -*vendor/plugins/yaffle/test/schema.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - create_table :woodpeckers, :force => true do |t| - t.string :name - end -end ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -def load_schema - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - load(File.dirname(__FILE__) + "/schema.rb") - require File.dirname(__FILE__) + '/../rails/init.rb' -end ----------------------------------------------- - -Now whenever you write a test that requires the database, you can call 'load_schema'. - -=== Run the plugin tests === - -Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: - -*vendor/plugins/yaffle/test/yaffle_test.rb:* - -[source, ruby] ----------------------------------------------- -require File.dirname(__FILE__) + '/test_helper.rb' - -class YaffleTest < Test::Unit::TestCase - load_schema - - class Hickwall < ActiveRecord::Base - end - - class Wickwall < ActiveRecord::Base - end - - def test_schema_has_loaded_correctly - assert_equal [], Hickwall.all - assert_equal [], Wickwall.all - end - -end ----------------------------------------------- - -To run this, go to the plugin directory and run `rake`: - ----------------------------------------------- -cd vendor/plugins/yaffle -rake ----------------------------------------------- - -You should see output like: - ----------------------------------------------- -/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" --- create_table(:hickwalls, {:force=>true}) - -> 0.0220s --- create_table(:wickwalls, {:force=>true}) - -> 0.0077s --- initialize_schema_migrations_table() - -> 0.0007s --- assume_migrated_upto_version(0) - -> 0.0007s -Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader -Started -. -Finished in 0.002236 seconds. - -1 test, 1 assertion, 0 failures, 0 errors ----------------------------------------------- - -By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: - ----------------------------------------------- -rake DB=sqlite -rake DB=sqlite3 -rake DB=mysql -rake DB=postgresql ----------------------------------------------- - -Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt new file mode 100644 index 0000000000..ef6dab2f9f --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tests.txt @@ -0,0 +1,165 @@ +== Tests == + +If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. + +To setup your plugin to allow for easy testing you'll need to add 3 files: + + * A 'database.yml' file with all of your connection strings + * A 'schema.rb' file with your table definitions + * A test helper method that sets up the database + +*vendor/plugins/yaffle/test/database.yml:* + +---------------------------------------------- +sqlite: + :adapter: sqlite + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite.db + +sqlite3: + :adapter: sqlite3 + :dbfile: vendor/plugins/yaffle/test/yaffle_plugin.sqlite3.db + +postgresql: + :adapter: postgresql + :username: postgres + :password: postgres + :database: yaffle_plugin_test + :min_messages: ERROR + +mysql: + :adapter: mysql + :host: localhost + :username: root + :password: password + :database: yaffle_plugin_test +---------------------------------------------- + +For this guide you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following: + +*vendor/plugins/yaffle/test/schema.rb:* + +[source, ruby] +---------------------------------------------- +ActiveRecord::Schema.define(:version => 0) do + create_table :hickwalls, :force => true do |t| + t.string :name + t.string :last_squawk + t.datetime :last_squawked_at + end + create_table :wickwalls, :force => true do |t| + t.string :name + t.string :last_tweet + t.datetime :last_tweeted_at + end + create_table :woodpeckers, :force => true do |t| + t.string :name + end +end +---------------------------------------------- + +*vendor/plugins/yaffle/test/test_helper.rb:* + +[source, ruby] +---------------------------------------------- +ENV['RAILS_ENV'] = 'test' +ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' + +require 'test/unit' +require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) + +def load_schema + config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) + ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") + + db_adapter = ENV['DB'] + + # no db passed, try one of these fine config-free DBs before bombing. + db_adapter ||= + begin + require 'rubygems' + require 'sqlite' + 'sqlite' + rescue MissingSourceFile + begin + require 'sqlite3' + 'sqlite3' + rescue MissingSourceFile + end + end + + if db_adapter.nil? + raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." + end + + ActiveRecord::Base.establish_connection(config[db_adapter]) + load(File.dirname(__FILE__) + "/schema.rb") + require File.dirname(__FILE__) + '/../rails/init.rb' +end +---------------------------------------------- + +Now whenever you write a test that requires the database, you can call 'load_schema'. + +=== Run the plugin tests === + +Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in 'vendor/plugins/yaffle/test/yaffle_test.rb' with a sample test. Replace the contents of that file with: + +*vendor/plugins/yaffle/test/yaffle_test.rb:* + +[source, ruby] +---------------------------------------------- +require File.dirname(__FILE__) + '/test_helper.rb' + +class YaffleTest < Test::Unit::TestCase + load_schema + + class Hickwall < ActiveRecord::Base + end + + class Wickwall < ActiveRecord::Base + end + + def test_schema_has_loaded_correctly + assert_equal [], Hickwall.all + assert_equal [], Wickwall.all + end + +end +---------------------------------------------- + +To run this, go to the plugin directory and run `rake`: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake +---------------------------------------------- + +You should see output like: + +---------------------------------------------- +/opt/local/bin/ruby -Ilib:lib "/opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader.rb" "test/yaffle_test.rb" +-- create_table(:hickwalls, {:force=>true}) + -> 0.0220s +-- create_table(:wickwalls, {:force=>true}) + -> 0.0077s +-- initialize_schema_migrations_table() + -> 0.0007s +-- assume_migrated_upto_version(0) + -> 0.0007s +Loaded suite /opt/local/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake/rake_test_loader +Started +. +Finished in 0.002236 seconds. + +1 test, 1 assertion, 0 failures, 0 errors +---------------------------------------------- + +By default the setup above runs your tests with sqlite or sqlite3. To run tests with one of the other connection strings specified in database.yml, pass the DB environment variable to rake: + +---------------------------------------------- +rake DB=sqlite +rake DB=sqlite3 +rake DB=mysql +rake DB=postgresql +---------------------------------------------- + +Now you are ready to test-drive your plugin! diff --git a/railties/doc/guides/source/stylesheets/base.css b/railties/doc/guides/source/stylesheets/base.css index 76ee6e2ca9..1cf0a3de98 100644 --- a/railties/doc/guides/source/stylesheets/base.css +++ b/railties/doc/guides/source/stylesheets/base.css @@ -97,6 +97,10 @@ ul li { background-position: 0 0.55em; } +ul li p { + margin-bottom: 0.5em; +} + /* ---------------------------------------------------------------------------- Structure ---------------------------------------------------------------------------- */ -- cgit v1.2.3 From 1d8c4cf6e0b115bac598f7d817ee98dc298580ff Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 16 Nov 2008 20:44:30 -0600 Subject: Fix markup for cattr_accessors in Action View and Action Mailer to work better with RDoc 2+. --- actionmailer/lib/action_mailer/base.rb | 111 +++++++++++++-------- actionpack/lib/action_view/base.rb | 8 +- .../lib/action_view/template_handlers/erb.rb | 2 + 3 files changed, 76 insertions(+), 45 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 19ce77ea5a..c4470810dc 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -201,49 +201,7 @@ module ActionMailer #:nodoc: # end # # - # = Configuration options - # - # These options are specified on the class level, like ActionMailer::Base.template_root = "/my/templates" - # - # * template_root - Determines the base from which template references will be made. - # - # * logger - the logger is used for generating information on the mailing run if available. - # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers. - # - # * smtp_settings - Allows detailed configuration for :smtp delivery method: - # * :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. - # * :port - On the off chance that your mail server doesn't run on port 25, you can change it. - # * :domain - If you need to specify a HELO domain, you can do it here. - # * :user_name - If your mail server requires authentication, set the username in this setting. - # * :password - If your mail server requires authentication, set the password in this setting. - # * :authentication - If your mail server requires authentication, you need to specify the authentication type here. - # This is a symbol and one of :plain, :login, :cram_md5. - # - # * sendmail_settings - Allows you to override options for the :sendmail delivery method. - # * :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. - # * :arguments - The command line arguments. Defaults to -i -t. - # - # * raise_delivery_errors - Whether or not errors should be raised if the email fails to be delivered. - # - # * delivery_method - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test. - # - # * perform_deliveries - Determines whether deliver_* methods are actually carried out. By default they are, - # but this can be turned off to help functional testing. - # - # * deliveries - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful - # for unit and functional testing. - # - # * default_charset - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also - # pick a different charset from inside a method with +charset+. - # * default_content_type - The default content type used for the main part of the message. Defaults to "text/plain". You - # can also pick a different content type from inside a method with +content_type+. - # * default_mime_version - The default mime version used for the message. Defaults to 1.0. You - # can also pick a different value from inside a method with +mime_version+. - # * default_implicit_parts_order - When a message is built implicitly (i.e. multiple parts are assembled from templates - # which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to - # ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client - # and appear last in the mime encoded message. You can also pick a different order from inside a method with - # +implicit_parts_order+. + # Configuration options are specified on the class level, like ActionMailer::Base.template_root = "/my/templates" class Base include AdvAttrAccessor, PartContainer if Object.const_defined?(:ActionController) @@ -254,6 +212,10 @@ module ActionMailer #:nodoc: private_class_method :new #:nodoc: class_inheritable_accessor :view_paths + ## + # :singleton-method: + # The logger is used for generating information on the mailing run if available. + # Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers. cattr_accessor :logger @@smtp_settings = { @@ -264,88 +226,150 @@ module ActionMailer #:nodoc: :password => nil, :authentication => nil } + ## + # :singleton-method: + # Allows detailed configuration for :smtp delivery method: + # * :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. + # * :port - On the off chance that your mail server doesn't run on port 25, you can change it. + # * :domain - If you need to specify a HELO domain, you can do it here. + # * :user_name - If your mail server requires authentication, set the username in this setting. + # * :password - If your mail server requires authentication, set the password in this setting. + # * :authentication - If your mail server requires authentication, you need to specify the authentication type here. + # This is a symbol and one of :plain, :login, :cram_md5. cattr_accessor :smtp_settings @@sendmail_settings = { :location => '/usr/sbin/sendmail', :arguments => '-i -t' } + ## + # :singleton-method: + # Allows you to override options for the :sendmail delivery method. + # * :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. + # * :arguments - The command line arguments. Defaults to -i -t. cattr_accessor :sendmail_settings @@raise_delivery_errors = true + ## + # :singleton-method: + # Whether or not errors should be raised if the email fails to be delivered. cattr_accessor :raise_delivery_errors + ## + # :singleton-method: + # Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test. superclass_delegating_accessor :delivery_method self.delivery_method = :smtp @@perform_deliveries = true + ## + # :singleton-method: + # Determines whether deliver_* methods are actually carried out. By default they are, + # but this can be turned off to help functional testing. cattr_accessor :perform_deliveries @@deliveries = [] + ## + # :singleton-method: + # Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful + # for unit and functional testing. cattr_accessor :deliveries @@default_charset = "utf-8" + ## + # :singleton-method: + # The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also + # pick a different charset from inside a method with +charset+. cattr_accessor :default_charset @@default_content_type = "text/plain" + ## + # :singleton-method: + # The default content type used for the main part of the message. Defaults to "text/plain". You + # can also pick a different content type from inside a method with +content_type+. cattr_accessor :default_content_type @@default_mime_version = "1.0" + ## + # :singleton-method: + # The default mime version used for the message. Defaults to 1.0. You + # can also pick a different value from inside a method with +mime_version+. cattr_accessor :default_mime_version @@default_implicit_parts_order = [ "text/html", "text/enriched", "text/plain" ] + ## + # :singleton-method: + # When a message is built implicitly (i.e. multiple parts are assembled from templates + # which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to + # ["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client + # and appear last in the mime encoded message. You can also pick a different order from inside a method with + # +implicit_parts_order+. cattr_accessor :default_implicit_parts_order cattr_reader :protected_instance_variables @@protected_instance_variables = %w(@body) + ## # Specify the BCC addresses for the message adv_attr_accessor :bcc + ## # Define the body of the message. This is either a Hash (in which case it # specifies the variables to pass to the template when it is rendered), # or a string, in which case it specifies the actual text of the message. adv_attr_accessor :body + ## # Specify the CC addresses for the message. adv_attr_accessor :cc + ## # Specify the charset to use for the message. This defaults to the # +default_charset+ specified for ActionMailer::Base. adv_attr_accessor :charset + ## # Specify the content type for the message. This defaults to text/plain # in most cases, but can be automatically set in some situations. adv_attr_accessor :content_type + ## # Specify the from address for the message. adv_attr_accessor :from + ## # Specify the address (if different than the "from" address) to direct # replies to this message. adv_attr_accessor :reply_to + ## # Specify additional headers to be added to the message. adv_attr_accessor :headers + ## # Specify the order in which parts should be sorted, based on content-type. # This defaults to the value for the +default_implicit_parts_order+. adv_attr_accessor :implicit_parts_order + ## # Defaults to "1.0", but may be explicitly given if needed. adv_attr_accessor :mime_version + ## # The recipient addresses for the message, either as a string (for a single # address) or an array (for multiple addresses). adv_attr_accessor :recipients + ## # The date on which the message was sent. If not set (the default), the # header will be set by the delivery agent. adv_attr_accessor :sent_on + ## # Specify the subject of the message. adv_attr_accessor :subject + ## # Specify the template name to use for current message. This is the "base" # template name, without the extension or directory, and may be used to # have multiple mailer methods share the same template. @@ -432,6 +456,7 @@ module ActionMailer #:nodoc: "Use ActionView::Base.register_template_extension instead", caller) end + # Determines the base from which template references will be made. def template_root self.view_paths && self.view_paths.first end diff --git a/actionpack/lib/action_view/base.rb b/actionpack/lib/action_view/base.rb index 945246a39a..a8ca0f685f 100644 --- a/actionpack/lib/action_view/base.rb +++ b/actionpack/lib/action_view/base.rb @@ -183,13 +183,17 @@ module ActionView #:nodoc: @@exempt_from_layout.merge(regexps) end + @@debug_rjs = false + ## + # :singleton-method: # Specify whether RJS responses should be wrapped in a try/catch block # that alert()s the caught exception (and then re-raises it). - @@debug_rjs = false cattr_accessor :debug_rjs - # A warning will be displayed whenever an action results in a cache miss on your view paths. @@warn_cache_misses = false + ## + # :singleton-method: + # A warning will be displayed whenever an action results in a cache miss on your view paths. cattr_accessor :warn_cache_misses attr_internal :request diff --git a/actionpack/lib/action_view/template_handlers/erb.rb b/actionpack/lib/action_view/template_handlers/erb.rb index 3def949f1e..0fec1e0b18 100644 --- a/actionpack/lib/action_view/template_handlers/erb.rb +++ b/actionpack/lib/action_view/template_handlers/erb.rb @@ -42,6 +42,8 @@ module ActionView class ERB < TemplateHandler include Compilable + ## + # :singleton-method: # Specify trim mode for the ERB compiler. Defaults to '-'. # See ERb documentation for suitable values. cattr_accessor :erb_trim_mode -- cgit v1.2.3 From 80f5f265471e8d53b66f432c203206c1a4197121 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Sun, 16 Nov 2008 20:46:03 -0600 Subject: Added Action View and Action Mailer documentation to the Config guide. --- railties/doc/guides/source/configuring.txt | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt index dde04ffb05..1fb73abbb8 100644 --- a/railties/doc/guides/source/configuring.txt +++ b/railties/doc/guides/source/configuring.txt @@ -101,8 +101,26 @@ The Active Record session store can also be configured: === Configuring Action View +There are only a few configuration options for Action View, starting with four on +ActionView::Base+: + ++debug_rjs+ specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is +false+. + ++warn_cache_misses+ tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is +false+. + ++field_error_proc+ provides an HTML generator for displaying errors that come from Active Record. The default is +Proc.new{ |html_tag, instance| "
    #{html_tag}
    " }+ + ++default_form_builder+ tells Rails which form builder to use by default. The default is +ActionView::Helpers::FormBuilder+. + +The ERB template handler supplies one additional option: + ++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. + === Configuring Action Mailer +There are a number of settings available on +ActionMailer::Base+: + + + === Configuring Active Resource === Configuring Active Support -- cgit v1.2.3 From 6b8500ce48f45f18696f6215b8a01f5cf0e328b5 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 22:27:08 -0500 Subject: Rails guide: Added PluginGem section, reorganized the odds and ends. --- railties/doc/guides/html/authors.html | 5 + railties/doc/guides/html/creating_plugins.html | 190 +++++++++++++-------- railties/doc/guides/html/routing_outside_in.html | 2 +- railties/doc/guides/source/authors.txt | 6 + .../guides/source/creating_plugins/appendix.txt | 26 ++- .../guides/source/creating_plugins/controllers.txt | 2 +- .../doc/guides/source/creating_plugins/gem.txt | 3 - .../doc/guides/source/creating_plugins/gems.txt | 50 ++++++ .../doc/guides/source/creating_plugins/index.txt | 6 +- .../guides/source/creating_plugins/migrations.txt | 4 +- .../source/creating_plugins/odds_and_ends.txt | 69 -------- .../doc/guides/source/creating_plugins/rdoc.txt | 18 ++ .../doc/guides/source/creating_plugins/tasks.txt | 29 ++++ 13 files changed, 254 insertions(+), 156 deletions(-) delete mode 100644 railties/doc/guides/source/creating_plugins/gem.txt create mode 100644 railties/doc/guides/source/creating_plugins/gems.txt delete mode 100644 railties/doc/guides/source/creating_plugins/odds_and_ends.txt create mode 100644 railties/doc/guides/source/creating_plugins/rdoc.txt create mode 100644 railties/doc/guides/source/creating_plugins/tasks.txt diff --git a/railties/doc/guides/html/authors.html b/railties/doc/guides/html/authors.html index a54135b14d..6fd556d2cd 100644 --- a/railties/doc/guides/html/authors.html +++ b/railties/doc/guides/html/authors.html @@ -231,6 +231,11 @@ Heiko has rarely looked back.

    Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog Sneaky Abstractions.

    +
    +
    diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 45c81f2af1..1762bd95d2 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -269,28 +269,20 @@ ul#navMain {
  • Create a custom rake task
  • -
  • Call plugin migrations from regular migrations
  • +
  • Call migrations directly
  • + +
  • Generate migrations
  • - Generating migrations + Rake tasks
  • - Odds and ends - + PluginGems +
  • +
  • + RDoc Documentation
  • Appendix @@ -1030,7 +1022,7 @@ http://www.gnu.org/software/src-highlite -->

    This section describes how to add a controller named woodpeckers to your plugin that will behave the same as a controller in your main app. This is very similar to adding a model.

    You can test your plugin's controller as you would test any other controller:

    -

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

    +

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

    end end
    -

    11.2. Call plugin migrations from regular migrations

    +

    11.2. Call migrations directly

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

    several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.
    -
    -

    12. Generating migrations

    -
    +

    11.3. Generate migrations

    Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this:

    • @@ -1709,41 +1699,8 @@ http://www.gnu.org/software/src-highlite --> end
    -

    13. Odds and ends

    +

    12. Rake tasks

    -

    13.1. Generate RDoc Documentation

    -

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    -

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

    -
      -
    • -

      -Your name. -

      -
    • -
    • -

      -How to install. -

      -
    • -
    • -

      -How to add the functionality to the app (several examples of common use cases). -

      -
    • -
    • -

      -Warning, gotchas or tips that might help save users time. -

      -
    • -
    -

    Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.

    -

    Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.

    -

    Once your comments are good to go, navigate to your plugin directory and run:

    -
    -
    -
    rake rdoc
    -
    -

    13.2. Write custom Rake tasks in your plugin

    When you created the plugin with the built-in rails generator, it generated a rake file for you in vendor/plugins/yaffle/tasks/yaffle.rake. Any rake task you add here will be available to the app.

    Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:

    vendor/plugins/yaffle/tasks/yaffle.rake

    @@ -1762,28 +1719,99 @@ http://www.gnu.org/software/src-highlite -->

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

    -
    yaffle:squawk             # Prints out the word 'Yaffle'
    +
    ...
    +yaffle:squawk             # Prints out the word 'Yaffle'
    +...

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

    -

    13.3. Store plugins in alternate locations

    -

    You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb.

    -

    Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.

    -

    You can even store plugins inside of other plugins for complete plugin madness!

    +

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

    +
    +

    13. PluginGems

    +
    +

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

    +

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

    +

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

    +

    vendor/plugins/yaffle/Rakefile:

    -
    config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
    +
    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
     
    -

    13.4. Create your own Plugin Loaders and Plugin Locators

    -

    If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.

    -

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

    +

    To build and install the gem locally, run the following commands:

    +
    +
    +
    cd vendor/plugins/yaffle
    +rake gem
    +sudo gem install pkg/yaffle-0.0.1.gem
    +
    +

    To test this, create a new rails app, add config.gem "yaffle" to environment.rb and all of your plugin's functionality will be available to you.

    -

    14. Appendix

    +

    14. RDoc Documentation

    -

    14.1. References

    +

    Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    +

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

    +
      +
    • +

      +Your name +

      +
    • +
    • +

      +How to install +

      +
    • +
    • +

      +How to add the functionality to the app (several examples of common use cases) +

      +
    • +
    • +

      +Warning, gotchas or tips that might help save users time +

      +
    • +
    +

    Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.

    +

    Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.

    +

    Once your comments are good to go, navigate to your plugin directory and run:

    +
    +
    +
    rake rdoc
    +
    +
    +

    15. Appendix

    +
    +

    If you prefer to use RSpec instead of tets, you may be interested in the RSpec Plugin Generator.

    +

    15.1. References

    • @@ -1811,20 +1839,27 @@ http://www.gnu.org/software/src-highlite -->

    -

    14.2. Final plugin directory structure

    +

    15.2. Final plugin directory structure

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

    -
    vendor/plugins/yaffle/
    -|-- MIT-LICENSE
    +
    |-- MIT-LICENSE
     |-- README
     |-- Rakefile
     |-- generators
    -|   `-- yaffle
    +|   |-- yaffle_definition
    +|   |   |-- USAGE
    +|   |   |-- templates
    +|   |   |   `-- definition.txt
    +|   |   `-- yaffle_definition_generator.rb
    +|   |-- yaffle_migration
    +|   |   |-- USAGE
    +|   |   |-- templates
    +|   |   `-- yaffle_migration_generator.rb
    +|   `-- yaffle_route
     |       |-- USAGE
     |       |-- templates
    -|       |   `-- definition.txt
    -|       `-- yaffle_generator.rb
    +|       `-- yaffle_route_generator.rb
     |-- install.rb
     |-- lib
     |   |-- app
    @@ -1834,11 +1869,16 @@ http://www.gnu.org/software/src-highlite -->
     |   |   |   `-- woodpeckers_helper.rb
     |   |   `-- models
     |   |       `-- woodpecker.rb
    +|   |-- db
    +|   |   `-- migrate
    +|   |       `-- 20081116181115_create_birdhouses.rb
     |   |-- yaffle
     |   |   |-- acts_as_yaffle.rb
     |   |   |-- commands.rb
     |   |   `-- core_ext.rb
     |   `-- yaffle.rb
    +|-- pkg
    +|   `-- yaffle-0.0.1.gem
     |-- rails
     |   `-- init.rb
     |-- tasks
    @@ -1848,7 +1888,9 @@ http://www.gnu.org/software/src-highlite -->
     |   |-- core_ext_test.rb
     |   |-- database.yml
     |   |-- debug.log
    -|   |-- generator_test.rb
    +|   |-- definition_generator_test.rb
    +|   |-- migration_generator_test.rb
    +|   |-- route_generator_test.rb
     |   |-- schema.rb
     |   |-- test_helper.rb
     |   |-- woodpecker_test.rb
    diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html
    index 947d0836ce..1d313b619f 100644
    --- a/railties/doc/guides/html/routing_outside_in.html
    +++ b/railties/doc/guides/html/routing_outside_in.html
    @@ -1454,7 +1454,7 @@ http://www.gnu.org/software/src-highlite -->
     
     Tip
     
    -If your application has many RESTful routes, using :only and :accept to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
    +If your application has many RESTful routes, using :only and :except to generate only the routes that you actually need can cut down on memory use and speed up the routing process.
     
     

    3.8. Nested Resources

    diff --git a/railties/doc/guides/source/authors.txt b/railties/doc/guides/source/authors.txt index 94dfc4db08..987238eb4c 100644 --- a/railties/doc/guides/source/authors.txt +++ b/railties/doc/guides/source/authors.txt @@ -37,3 +37,9 @@ Heiko has rarely looked back. Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the internet is his blog http://tore.darell.no/[Sneaky Abstractions]. *********************************************************** + +.Jeff Dean +[[zilkey]] +*********************************************************** +Jeff Dean is a software engineer with http://pivotallabs.com/[Pivotal Labs]. +*********************************************************** diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index d890f861b5..19f677c5fd 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -1,5 +1,7 @@ == Appendix == +If you prefer to use RSpec instead of tets, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. + === References === * http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i @@ -13,16 +15,23 @@ The final plugin should have a directory structure that looks something like this: ------------------------------------------------ -vendor/plugins/yaffle/ |-- MIT-LICENSE |-- README |-- Rakefile |-- generators -| `-- yaffle +| |-- yaffle_definition +| | |-- USAGE +| | |-- templates +| | | `-- definition.txt +| | `-- yaffle_definition_generator.rb +| |-- yaffle_migration +| | |-- USAGE +| | |-- templates +| | `-- yaffle_migration_generator.rb +| `-- yaffle_route | |-- USAGE | |-- templates -| | `-- definition.txt -| `-- yaffle_generator.rb +| `-- yaffle_route_generator.rb |-- install.rb |-- lib | |-- app @@ -32,11 +41,16 @@ vendor/plugins/yaffle/ | | | `-- woodpeckers_helper.rb | | `-- models | | `-- woodpecker.rb +| |-- db +| | `-- migrate +| | `-- 20081116181115_create_birdhouses.rb | |-- yaffle | | |-- acts_as_yaffle.rb | | |-- commands.rb | | `-- core_ext.rb | `-- yaffle.rb +|-- pkg +| `-- yaffle-0.0.1.gem |-- rails | `-- init.rb |-- tasks @@ -46,7 +60,9 @@ vendor/plugins/yaffle/ | |-- core_ext_test.rb | |-- database.yml | |-- debug.log -| |-- generator_test.rb +| |-- definition_generator_test.rb +| |-- migration_generator_test.rb +| |-- route_generator_test.rb | |-- schema.rb | |-- test_helper.rb | |-- woodpecker_test.rb diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index 4f4417b416..e38cf8251e 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -4,7 +4,7 @@ This section describes how to add a controller named 'woodpeckers' to your plugi You can test your plugin's controller as you would test any other controller: -*vendor/plugins/yaffle/yaffle/woodpeckers_controller_test.rb:* +*vendor/plugins/yaffle/test/woodpeckers_controller_test.rb:* [source, ruby] ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt deleted file mode 100644 index 8a0bbb3bc0..0000000000 --- a/railties/doc/guides/source/creating_plugins/gem.txt +++ /dev/null @@ -1,3 +0,0 @@ -== Gems == - -http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/gems.txt b/railties/doc/guides/source/creating_plugins/gems.txt new file mode 100644 index 0000000000..67d55adb3a --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/gems.txt @@ -0,0 +1,50 @@ +== PluginGems == + +Turning your rails plugin into a gem is a simple and straightforward task. This section will cover how to turn your plugin into a gem. It will not cover how to distribute that gem. + +Historically rails plugins loaded the plugin's 'init.rb' file. In fact some plugins contain all of their code in that one file. To be compatible with plugins, 'init.rb' was moved to 'rails/init.rb'. + +It's common practice to put any developer-centric rake tasks (such as tests, rdoc and gem package tasks) in 'Rakefile'. A rake task that packages the gem might look like this: + +*vendor/plugins/yaffle/Rakefile:* + +[source, ruby] +---------------------------------------------- +PKG_FILES = FileList[ + '[a-zA-Z]*', + 'generators/**/*', + 'lib/**/*', + 'rails/**/*', + 'tasks/**/*', + 'test/**/*' +] + +spec = Gem::Specification.new do |s| + s.name = "yaffle" + s.version = "0.0.1" + s.author = "Gleeful Yaffler" + s.email = "yaffle@example.com" + s.homepage = "http://yafflers.example.com/" + s.platform = Gem::Platform::RUBY + s.summary = "Sharing Yaffle Goodness" + s.files = PKG_FILES.to_a + s.require_path = "lib" + s.has_rdoc = false + s.extra_rdoc_files = ["README"] +end + +desc 'Turn this plugin into a gem.' +Rake::GemPackageTask.new(spec) do |pkg| + pkg.gem_spec = spec +end +---------------------------------------------- + +To build and install the gem locally, run the following commands: + +---------------------------------------------- +cd vendor/plugins/yaffle +rake gem +sudo gem install pkg/yaffle-0.0.1.gem +---------------------------------------------- + +To test this, create a new rails app, add 'config.gem "yaffle"' to environment.rb and all of your plugin's functionality will be available to you. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/index.txt b/railties/doc/guides/source/creating_plugins/index.txt index 5d10fa4f31..0607bc7487 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -51,6 +51,10 @@ include::generator_commands.txt[] include::migrations.txt[] -include::odds_and_ends.txt[] +include::tasks.txt[] + +include::gems.txt[] + +include::rdoc.txt[] include::appendix.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index 7154f0bc06..4dd932734d 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -63,7 +63,7 @@ namespace :db do end ---------------------------------------------- -=== Call plugin migrations from regular migrations === +=== Call migrations directly === *vendor/plugins/yaffle/lib/yaffle.rb:* @@ -91,7 +91,7 @@ end NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. -== Generating migrations == +=== Generate migrations === Generating migrations has several advantages over other methods. Namely, you can allow other developers to more easily customize the migration. The flow looks like this: diff --git a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt deleted file mode 100644 index e328c04a79..0000000000 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Odds and ends == - -=== Generate RDoc Documentation === - -Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. - -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - - * Your name. - * How to install. - * How to add the functionality to the app (several examples of common use cases). - * Warning, gotchas or tips that might help save users time. - -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. - -Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. - -Once your comments are good to go, navigate to your plugin directory and run: - - rake rdoc - -=== Write custom Rake tasks in your plugin === - -When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. - -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: - -*vendor/plugins/yaffle/tasks/yaffle.rake* - -[source, ruby] ---------------------------------------------------------- -namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end -end ---------------------------------------------------------- - -When you run `rake -T` from your plugin you will see: - ---------------------------------------------------------- -yaffle:squawk # Prints out the word 'Yaffle' ---------------------------------------------------------- - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -=== Store plugins in alternate locations === - -You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'. - -Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. - -You can even store plugins inside of other plugins for complete plugin madness! - -[source, ruby] ---------------------------------------------------------- -config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") ---------------------------------------------------------- - -=== Create your own Plugin Loaders and Plugin Locators === - -If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. - - -=== Use Custom Plugin Generators === - -If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master. - diff --git a/railties/doc/guides/source/creating_plugins/rdoc.txt b/railties/doc/guides/source/creating_plugins/rdoc.txt new file mode 100644 index 0000000000..0f6f843c42 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/rdoc.txt @@ -0,0 +1,18 @@ +== RDoc Documentation == + +Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. + +The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: + + * Your name + * How to install + * How to add the functionality to the app (several examples of common use cases) + * Warning, gotchas or tips that might help save users time + +Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add '#:nodoc:' comments to those parts of the code that are not part of the public api. + +Once your comments are good to go, navigate to your plugin directory and run: + +--------------------------------------------------------- +rake rdoc +--------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt new file mode 100644 index 0000000000..c71ba42bb0 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/tasks.txt @@ -0,0 +1,29 @@ +== Rake tasks == + +When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. + +Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: + +*vendor/plugins/yaffle/tasks/yaffle.rake* + +[source, ruby] +--------------------------------------------------------- +namespace :yaffle do + desc "Prints out the word 'Yaffle'" + task :squawk => :environment do + puts "squawk!" + end +end +--------------------------------------------------------- + +When you run `rake -T` from your plugin you will see: + +--------------------------------------------------------- +... +yaffle:squawk # Prints out the word 'Yaffle' +... +--------------------------------------------------------- + +You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. + +Note that tasks from 'vendor/plugins/yaffle/Rakefile' are not available to the main app. \ No newline at end of file -- cgit v1.2.3 From e08af7219795d28fe9e9eb5f0dc2e7488541382e Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 23:09:12 -0500 Subject: Rails guide: Misc reorganization --- railties/doc/guides/html/creating_plugins.html | 84 ++++++++++------------ .../guides/source/creating_plugins/core_ext.txt | 27 +------ .../source/creating_plugins/generator_commands.txt | 1 + .../guides/source/creating_plugins/migrations.txt | 2 + .../doc/guides/source/creating_plugins/setup.txt | 22 +++++- .../doc/guides/source/creating_plugins/tests.txt | 6 +- 6 files changed, 65 insertions(+), 77 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 1762bd95d2..8f32f72458 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -206,12 +206,16 @@ ul#navMain {
  • Generate the plugin skeleton
  • +
  • Organize your files
  • +
  • Tests @@ -220,10 +224,6 @@ ul#navMain { Extending core classes @@ -452,12 +452,30 @@ create vendor/plugins/yaffle/generators/yaffle/templates create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE -

    To begin just change one thing - move init.rb to rails/init.rb.

    +

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

    +
    +
    +
    require 'yaffle'
    +
    +

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

    2. Tests

    -

    If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests.

    -

    To setup your plugin to allow for easy testing you'll need to add 3 files:

    +

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

    • @@ -475,6 +493,7 @@ A test helper method that sets up the database

    +

    2.1. Test Setup

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

    @@ -565,7 +584,7 @@ ENV['RAILS_ROOT end

    Now whenever you write a test that requires the database, you can call load_schema.

    -

    2.1. Run the plugin tests

    +

    2.2. Run the plugin tests

    Once you have these files in place, you can write your first test to ensure that your plugin-testing setup is correct. By default rails generates a file in vendor/plugins/yaffle/test/yaffle_test.rb with a sample test. Replace the contents of that file with:

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

    @@ -628,20 +647,7 @@ rake DB=postgresql

    3. Extending core classes

    -

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

    -
      -
    • -

      -Writing tests for the desired behavior -

      -
    • -
    • -

      -Creating and requiring the correct files -

      -
    • -
    -

    3.1. Creating the test

    +

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

    In this example you will add a method to String named to_squawk. To begin, create a new test file with a few assertions:

    vendor/plugins/yaffle/test/core_ext_test.rb

    @@ -672,24 +678,6 @@ 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.

    -

    3.2. Organize your files

    -

    A common pattern in rails plugins is to set up the file structure like this:

    -
    -
    -
    |-- lib
    -|   |-- yaffle
    -|   |   `-- core_ext.rb
    -|   `-- yaffle.rb
    -
    -

    The first thing we need to to is to require our lib/yaffle.rb file from rails/init.rb:

    -

    vendor/plugins/yaffle/rails/init.rb

    -
    -
    -
    require 'yaffle'
    -

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

    vendor/plugins/yaffle/lib/yaffle.rb

    @@ -719,7 +707,7 @@ http://www.gnu.org/software/src-highlite --> >> "Hello World".to_squawk => "squawk! Hello World"
    -

    3.3. Working with init.rb

    +

    3.1. Working with init.rb

    When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.

    Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.

    If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:

    @@ -1471,7 +1459,8 @@ http://www.gnu.org/software/src-highlite --> Note -If you haven't set up the custom route from above, script/destroy will fail and you'll have to remove it manually. + +
    Editor's note:
    If you haven't set up the custom route from above, script/destroy will fail and you'll have to remove it manually. @@ -1569,7 +1558,8 @@ http://www.gnu.org/software/src-highlite --> Note -several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. + +
    Editor's note:
    several plugin frameworks such as Desert and Engines provide more advanced plugin functionality.

    11.3. Generate migrations

    @@ -1639,7 +1629,8 @@ http://www.gnu.org/software/src-highlite --> 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. + +
    Editor's note:
    the migration generator checks to see if a migation already exists, and it's hard-coded to check the db/migrate directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app.

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

    @@ -1776,7 +1767,7 @@ sudo gem install pkg/yaffle-0.0.1.gem

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

    +

    Once your plugin is stable and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.

    The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:

    • @@ -1800,8 +1791,7 @@ Warning, gotchas or tips that might help save users time

    -

    Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.

    -

    Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.

    +

    Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. It's also customary to add #:nodoc: comments to those parts of the code that are not part of the public api.

    Once your comments are good to go, navigate to your plugin directory and run:

    diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index ca8efc3df1..efef0e1f70 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -1,11 +1,6 @@ == Extending core classes == -This section will explain how to add a method to String that will be available anywhere in your rails app by: - - * Writing tests for the desired behavior - * Creating and requiring the correct files - -=== Creating the test === +This section will explain how to add a method to String that will be available anywhere in your rails app. In this example you will add a method to String named `to_squawk`. To begin, create a new test file with a few assertions: @@ -40,26 +35,6 @@ NoMethodError: undefined method `to_squawk' for "Hello World":String Great - now you are ready to start development. -=== Organize your files === - -A common pattern in rails plugins is to set up the file structure like this: - --------------------------------------------------------- -|-- lib -| |-- yaffle -| | `-- core_ext.rb -| `-- yaffle.rb --------------------------------------------------------- - -The first thing we need to to is to require our 'lib/yaffle.rb' file from 'rails/init.rb': - -*vendor/plugins/yaffle/rails/init.rb* - -[source, ruby] --------------------------------------------------------- -require 'yaffle' --------------------------------------------------------- - Then in 'lib/yaffle.rb' require 'lib/core_ext.rb': *vendor/plugins/yaffle/lib/yaffle.rb* diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt index 5cce81c8bd..3ace3c7318 100644 --- a/railties/doc/guides/source/creating_plugins/generator_commands.txt +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -137,4 +137,5 @@ To see this work, type: ./script/destroy yaffle_route ----------------------------------------------------------- +.Editor's note: NOTE: If you haven't set up the custom route from above, 'script/destroy' will fail and you'll have to remove it manually. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index 4dd932734d..d158004ea3 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -89,6 +89,7 @@ class CreateBirdhouses < ActiveRecord::Migration end ---------------------------------------------- +.Editor's note: NOTE: several plugin frameworks such as Desert and Engines provide more advanced plugin functionality. === Generate migrations === @@ -146,6 +147,7 @@ class MigrationGeneratorTest < Test::Unit::TestCase end ------------------------------------------------------------------ +.Editor's note: NOTE: the migration generator checks to see if a migation already exists, and it's hard-coded to check the 'db/migrate' directory. As a result, if your test tries to generate a migration that already exists in the app, it will fail. The easy workaround is to make sure that the name you generate in your test is very unlikely to actually appear in the app. After running the test with 'rake' you can make it pass with: diff --git a/railties/doc/guides/source/creating_plugins/setup.txt b/railties/doc/guides/source/creating_plugins/setup.txt index fcf5b459e6..cd4b6ecb04 100644 --- a/railties/doc/guides/source/creating_plugins/setup.txt +++ b/railties/doc/guides/source/creating_plugins/setup.txt @@ -61,4 +61,24 @@ create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb create vendor/plugins/yaffle/generators/yaffle/USAGE ---------------------------------------------- -To begin just change one thing - move 'init.rb' to 'rails/init.rb'. +=== Organize your files === + +To make it easy to organize your files and to make the plugin more compatible with GemPlugins, start out by altering your file system to look like this: + +-------------------------------------------------------- +|-- lib +| |-- yaffle +| `-- yaffle.rb +`-- rails + | + `-- init.rb +-------------------------------------------------------- + +*vendor/plugins/yaffle/rails/init.rb* + +[source, ruby] +-------------------------------------------------------- +require 'yaffle' +-------------------------------------------------------- + +Now you can add any 'require' statements to 'lib/yaffle.rb' and keep 'init.rb' clean. \ No newline at end of file diff --git a/railties/doc/guides/source/creating_plugins/tests.txt b/railties/doc/guides/source/creating_plugins/tests.txt index ef6dab2f9f..47611542cb 100644 --- a/railties/doc/guides/source/creating_plugins/tests.txt +++ b/railties/doc/guides/source/creating_plugins/tests.txt @@ -1,13 +1,13 @@ == Tests == -If your plugin interacts with a database, you'll need to setup a database connection. In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. This guide will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: +In this guide you will learn how to test your plugin against multiple different database adapters using Active Record. To setup your plugin to allow for easy testing you'll need to add 3 files: * A 'database.yml' file with all of your connection strings * A 'schema.rb' file with your table definitions * A test helper method that sets up the database +=== Test Setup === + *vendor/plugins/yaffle/test/database.yml:* ---------------------------------------------- -- cgit v1.2.3 From eda282f85743961e2910e4e493a2690fa633b94f Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Sun, 16 Nov 2008 23:11:40 -0500 Subject: Re-ran rake guides --- railties/doc/guides/html/configuring.html | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html index ea5f162cb7..55f5d48554 100644 --- a/railties/doc/guides/html/configuring.html +++ b/railties/doc/guides/html/configuring.html @@ -326,7 +326,15 @@ after-initializer

    The Active Record session store can also be configured:

    CGI::Session::ActiveRecordStore::Session.data_column_name sets the name of the column to use to store session data. By default it is data

    4.3. Configuring Action View

    +

    There are only a few configuration options for Action View, starting with four on ActionView::Base:

    +

    debug_rjs specifies whether RJS responses should be wrapped in a try/catch block that alert()s the caught exception (and then re-raises it). The default is false.

    +

    warn_cache_misses tells Rails to display a warning whenever an action results in a cache miss on your view paths. The default is false.

    +

    +

    default_form_builder tells Rails which form builder to use by default. The default is ActionView::Helpers::FormBuilder.

    +

    The ERB template handler supplies one additional option:

    +

    ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -.

    4.4. Configuring Action Mailer

    +

    There are a number of settings available on ActionMailer::Base:

    4.5. Configuring Active Resource

    4.6. Configuring Active Support

    -- cgit v1.2.3 From 236142d23eb083d0a755d29d6365925ae5cc9f03 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Mon, 17 Nov 2008 00:15:20 -0500 Subject: Rails plugin: misc error fixes. --- railties/doc/guides/html/creating_plugins.html | 141 +++++++++++++-------- .../guides/source/creating_plugins/appendix.txt | 30 ++++- .../guides/source/creating_plugins/controllers.txt | 4 + .../guides/source/creating_plugins/core_ext.txt | 6 +- .../source/creating_plugins/generator_commands.txt | 29 +++-- .../guides/source/creating_plugins/generators.txt | 18 +-- .../doc/guides/source/creating_plugins/helpers.txt | 2 - .../guides/source/creating_plugins/migrations.txt | 26 ++-- .../doc/guides/source/creating_plugins/models.txt | 6 +- .../doc/guides/source/creating_plugins/routes.txt | 16 +-- .../doc/guides/source/creating_plugins/tasks.txt | 2 - 11 files changed, 170 insertions(+), 110 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 8f32f72458..ba7962d9ca 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -290,6 +290,8 @@ ul#navMain {
  • References
  • +
  • Contents of lib/yaffle.rb
  • +
  • Final plugin directory structure
  • @@ -708,10 +710,10 @@ http://www.gnu.org/software/src-highlite --> => "squawk! Hello World"

    3.1. Working with init.rb

    -

    When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.

    +

    When rails loads plugins it looks for the file named init.rb or rails/init.rb. However, when the plugin is initialized, init.rb is invoked via eval (not require) so it has slightly different behavior.

    Under certain circumstances if you reopen classes or modules in init.rb you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from init.rb, as shown above.

    If you must reopen a class in init.rb you can use module_eval or class_eval to avoid any issues:

    -

    vendor/plugins/yaffle/init.rb

    +

    vendor/plugins/yaffle/rails/init.rb

    end

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

    -

    vendor/plugins/yaffle/init.rb

    +

    vendor/plugins/yaffle/rails/init.rb

    by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    ActiveRecord::Schema.define(:version => 0) do
    -  create_table :woodpeckers, :force => true do |t|
    -    t.string :name
    -  end
    +
    create_table :woodpeckers, :force => true do |t|
    +  t.string :name
     end
     

    Now your test should be passing, and you should be able to use the Woodpecker model from within your rails app, and any changes made to it are reflected immediately when running in development mode.

    @@ -1027,6 +1027,10 @@ http://www.gnu.org/software/src-highlite --> @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 @@ -1097,8 +1101,6 @@ http://www.gnu.org/software/src-highlite --> ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) end - -ActionView::Base.send :include, WoodpeckersHelper

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

    @@ -1141,26 +1143,21 @@ http://www.gnu.org/software/src-highlite --> private - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. def assert_recognition(method, path, options) result = ActionController::Routing::Routes.recognize_path(path, :method => method) assert_equal options, result end end
    -

    vendor/plugins/yaffle/init.rb

    +

    vendor/plugins/yaffle/lib/yaffle.rb

    -
    require "routing"
    -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
    +
    require "yaffle/routing"
     
    -

    vendor/plugins/yaffle/lib/routing.rb

    +

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

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

    config/routes.rb

    @@ -1183,7 +1181,6 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    ActionController::Routing::Routes.draw do |map|
    -  ...
       map.yaffles
     end
     
    @@ -1253,14 +1250,6 @@ http://www.gnu.org/software/src-highlite --> class DefinitionGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "*")) - end - def setup FileUtils.mkdir_p(fake_rails_root) @original_files = file_list @@ -1276,6 +1265,16 @@ http://www.gnu.org/software/src-highlite --> assert_equal "definition.txt", File.basename(new_file) end + private + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end + end

    You can run rake from the plugin directory to see this fail. Unless you are doing more advanced generator commands it typically suffices to just test the Generate script, and trust that rails will handle the Destroy and Update commands for you.

    @@ -1334,14 +1333,6 @@ http://www.gnu.org/software/src-highlite --> class RouteGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), "rails_root") - end - - def routes_path - File.join(fake_rails_root, "config", "routes.rb") - end - def setup FileUtils.mkdir_p(File.join(fake_rails_root, "config")) end @@ -1360,13 +1351,13 @@ http://www.gnu.org/software/src-highlite --> File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_match /map\.yaffle/, File.read(routes_path) + assert_match /map\.yaffles/, File.read(routes_path) end def test_destroys_route content = <<-END ActionController::Routing::Routes.draw do |map| - map.yaffle + map.yaffles map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end @@ -1374,8 +1365,19 @@ http://www.gnu.org/software/src-highlite --> File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_no_match /map\.yaffle/, File.read(routes_path) + assert_no_match /map\.yaffles/, File.read(routes_path) end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + end

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

    @@ -1404,7 +1406,7 @@ http://www.gnu.org/software/src-highlite --> logger.route "map.yaffle" look_for = 'ActionController::Routing::Routes.draw do |map|' unless options[:pretend] - gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} end end end @@ -1412,7 +1414,7 @@ http://www.gnu.org/software/src-highlite --> module Destroy def yaffle_route logger.route "map.yaffle" - gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' end end @@ -1586,29 +1588,21 @@ http://www.gnu.org/software/src-highlite -->
    require File.dirname(__FILE__) + '/test_helper.rb'
     require 'rails_generator'
     require 'rails_generator/scripts/generate'
    -require 'rails_generator/scripts/destroy'
     
     class MigrationGeneratorTest < Test::Unit::TestCase
     
    -  def fake_rails_root
    -    File.join(File.dirname(__FILE__), 'rails_root')
    -  end
    -
    -  def file_list
    -    Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
    -  end
    -
       def setup
         FileUtils.mkdir_p(fake_rails_root)
         @original_files = file_list
       end
     
       def teardown
    +    ActiveRecord::Base.pluralize_table_names = true
         FileUtils.rm_r(fake_rails_root)
       end
     
       def test_generates_correct_file_name
    -    Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
    +    Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
         new_file = (file_list - @original_files).first
         assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file
         assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file)
    @@ -1616,12 +1610,21 @@ http://www.gnu.org/software/src-highlite -->
     
       def test_pluralizes_properly
         ActiveRecord::Base.pluralize_table_names = false
    -    Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
    +    Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root)
         new_file = (file_list - @original_files).first
         assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file
         assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file)
       end
     
    +  private
    +    def fake_rails_root
    +      File.join(File.dirname(__FILE__), 'rails_root')
    +    end
    +
    +    def file_list
    +      Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
    +    end
    +
     end
     
    @@ -1640,7 +1643,7 @@ http://www.gnu.org/software/src-highlite --> by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
    class YaffleGenerator < Rails::Generator::NamedBase
    +
    class YaffleMigrationGenerator < Rails::Generator::NamedBase
       def manifest
         record do |m|
           m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
    @@ -1653,6 +1656,7 @@ http://www.gnu.org/software/src-highlite -->
         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
    @@ -1710,9 +1714,7 @@ http://www.gnu.org/software/src-highlite -->
     

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

    -
    ...
    -yaffle:squawk             # Prints out the word 'Yaffle'
    -...
    +
    yaffle:squawk             # Prints out the word 'Yaffle'

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

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

    @@ -1829,7 +1831,32 @@ Warning, gotchas or tips that might help save users time

    -

    15.2. Final plugin directory structure

    +

    15.2. Contents of lib/yaffle.rb

    +

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

    +
    +
    +
    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
    +
    +
    +

    15.3. Final plugin directory structure

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

    @@ -1865,7 +1892,8 @@ Warning, gotchas or tips that might help save users time | |-- yaffle | | |-- acts_as_yaffle.rb | | |-- commands.rb -| | `-- core_ext.rb +| | |-- core_ext.rb +| | `-- routing.rb | `-- yaffle.rb |-- pkg | `-- yaffle-0.0.1.gem @@ -1881,6 +1909,7 @@ Warning, gotchas or tips that might help save users time | |-- definition_generator_test.rb | |-- migration_generator_test.rb | |-- route_generator_test.rb +| |-- routes_test.rb | |-- schema.rb | |-- test_helper.rb | |-- woodpecker_test.rb diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index 19f677c5fd..5c3bd20a1b 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -10,6 +10,32 @@ If you prefer to use RSpec instead of tets, you may be interested in the http:// * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins +=== Contents of 'lib/yaffle.rb' === + +*vendor/plugins/yaffle/lib/yaffle.rb:* + +[source, ruby] +---------------------------------------------- +require "yaffle/core_ext" +require "yaffle/acts_as_yaffle" +require "yaffle/commands" +require "yaffle/routing" + +%w{ models controllers helpers }.each do |dir| + path = File.join(File.dirname(__FILE__), 'app', dir) + $LOAD_PATH << path + ActiveSupport::Dependencies.load_paths << path + ActiveSupport::Dependencies.load_once_paths.delete(path) +end + +# optionally: +# Dir.glob(File.join(File.dirname(__FILE__), "db", "migrate", "*")).each do |file| +# require file +# end + +---------------------------------------------- + + === Final plugin directory structure === The final plugin should have a directory structure that looks something like this: @@ -47,7 +73,8 @@ The final plugin should have a directory structure that looks something like thi | |-- yaffle | | |-- acts_as_yaffle.rb | | |-- commands.rb -| | `-- core_ext.rb +| | |-- core_ext.rb +| | `-- routing.rb | `-- yaffle.rb |-- pkg | `-- yaffle-0.0.1.gem @@ -63,6 +90,7 @@ The final plugin should have a directory structure that looks something like thi | |-- definition_generator_test.rb | |-- migration_generator_test.rb | |-- route_generator_test.rb +| |-- routes_test.rb | |-- schema.rb | |-- test_helper.rb | |-- woodpecker_test.rb diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt index e38cf8251e..7afdef032d 100644 --- a/railties/doc/guides/source/creating_plugins/controllers.txt +++ b/railties/doc/guides/source/creating_plugins/controllers.txt @@ -19,6 +19,10 @@ class WoodpeckersControllerTest < Test::Unit::TestCase @controller = WoodpeckersController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new + + ActionController::Routing::Routes.draw do |map| + map.resources :woodpeckers + end end def test_index diff --git a/railties/doc/guides/source/creating_plugins/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt index efef0e1f70..cbedb9eaf2 100644 --- a/railties/doc/guides/source/creating_plugins/core_ext.txt +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -67,13 +67,13 @@ $ ./script/console === Working with init.rb === -When rails loads plugins it looks for the file named init.rb. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. +When rails loads plugins it looks for the file named 'init.rb' or 'rails/init.rb'. However, when the plugin is initialized, 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior. Under certain circumstances if you reopen classes or modules in 'init.rb' you may inadvertently create a new class, rather than reopening an existing class. A better alternative is to reopen the class in a different file, and require that file from `init.rb`, as shown above. If you must reopen a class in `init.rb` you can use `module_eval` or `class_eval` to avoid any issues: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- @@ -86,7 +86,7 @@ end Another way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: -*vendor/plugins/yaffle/init.rb* +*vendor/plugins/yaffle/rails/init.rb* [source, ruby] --------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/generator_commands.txt b/railties/doc/guides/source/creating_plugins/generator_commands.txt index 3ace3c7318..f60ea3d8f1 100644 --- a/railties/doc/guides/source/creating_plugins/generator_commands.txt +++ b/railties/doc/guides/source/creating_plugins/generator_commands.txt @@ -17,14 +17,6 @@ require 'rails_generator/scripts/destroy' class RouteGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), "rails_root") - end - - def routes_path - File.join(fake_rails_root, "config", "routes.rb") - end - def setup FileUtils.mkdir_p(File.join(fake_rails_root, "config")) end @@ -43,13 +35,13 @@ class RouteGeneratorTest < Test::Unit::TestCase File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Generate.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_match /map\.yaffle/, File.read(routes_path) + assert_match /map\.yaffles/, File.read(routes_path) end def test_destroys_route content = <<-END ActionController::Routing::Routes.draw do |map| - map.yaffle + map.yaffles map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format' end @@ -57,8 +49,19 @@ class RouteGeneratorTest < Test::Unit::TestCase File.open(routes_path, 'wb') {|f| f.write(content) } Rails::Generator::Scripts::Destroy.new.run(["yaffle_route"], :destination => fake_rails_root) - assert_no_match /map\.yaffle/, File.read(routes_path) + assert_no_match /map\.yaffles/, File.read(routes_path) end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), "rails_root") + end + + def routes_path + File.join(fake_rails_root, "config", "routes.rb") + end + end ----------------------------------------------------------- @@ -86,7 +89,7 @@ module Yaffle #:nodoc: logger.route "map.yaffle" look_for = 'ActionController::Routing::Routes.draw do |map|' unless options[:pretend] - gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffle\n"} + gsub_file('config/routes.rb', /(#{Regexp.escape(look_for)})/mi){|match| "#{match}\n map.yaffles\n"} end end end @@ -94,7 +97,7 @@ module Yaffle #:nodoc: module Destroy def yaffle_route logger.route "map.yaffle" - gsub_file 'config/routes.rb', /\n.+?map\.yaffle/mi, '' + gsub_file 'config/routes.rb', /\n.+?map\.yaffles/mi, '' end end diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt index eb0fbb5ee9..8ef46561d1 100644 --- a/railties/doc/guides/source/creating_plugins/generators.txt +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -32,14 +32,6 @@ require 'rails_generator/scripts/generate' class DefinitionGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "*")) - end - def setup FileUtils.mkdir_p(fake_rails_root) @original_files = file_list @@ -54,6 +46,16 @@ class DefinitionGeneratorTest < Test::Unit::TestCase new_file = (file_list - @original_files).first assert_equal "definition.txt", File.basename(new_file) end + + private + + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + + def file_list + Dir.glob(File.join(fake_rails_root, "*")) + end end ------------------------------------------------------------------ diff --git a/railties/doc/guides/source/creating_plugins/helpers.txt b/railties/doc/guides/source/creating_plugins/helpers.txt index c2273813dd..fa4227be41 100644 --- a/railties/doc/guides/source/creating_plugins/helpers.txt +++ b/railties/doc/guides/source/creating_plugins/helpers.txt @@ -30,8 +30,6 @@ This is just a simple test to make sure the helper is being loaded correctly. A ActiveSupport::Dependencies.load_paths << path ActiveSupport::Dependencies.load_once_paths.delete(path) end - -ActionView::Base.send :include, WoodpeckersHelper ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/migrations.txt b/railties/doc/guides/source/creating_plugins/migrations.txt index d158004ea3..e7d2e09069 100644 --- a/railties/doc/guides/source/creating_plugins/migrations.txt +++ b/railties/doc/guides/source/creating_plugins/migrations.txt @@ -108,29 +108,21 @@ This example will demonstrate how to use one of the built-in generator methods n require File.dirname(__FILE__) + '/test_helper.rb' require 'rails_generator' require 'rails_generator/scripts/generate' -require 'rails_generator/scripts/destroy' class MigrationGeneratorTest < Test::Unit::TestCase - def fake_rails_root - File.join(File.dirname(__FILE__), 'rails_root') - end - - def file_list - Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) - end - def setup FileUtils.mkdir_p(fake_rails_root) @original_files = file_list end def teardown + ActiveRecord::Base.pluralize_table_names = true FileUtils.rm_r(fake_rails_root) end def test_generates_correct_file_name - Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) new_file = (file_list - @original_files).first assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migrations/, new_file assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migrations do |t|/, File.read(new_file) @@ -138,12 +130,21 @@ class MigrationGeneratorTest < Test::Unit::TestCase def test_pluralizes_properly ActiveRecord::Base.pluralize_table_names = false - Rails::Generator::Scripts::Generate.new.run(["yaffle", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) + Rails::Generator::Scripts::Generate.new.run(["yaffle_migration", "some_name_nobody_is_likely_to_ever_use_in_a_real_migration"], :destination => fake_rails_root) new_file = (file_list - @original_files).first assert_match /add_yaffle_fields_to_some_name_nobody_is_likely_to_ever_use_in_a_real_migration/, new_file assert_match /add_column :some_name_nobody_is_likely_to_ever_use_in_a_real_migration do |t|/, File.read(new_file) end + + private + def fake_rails_root + File.join(File.dirname(__FILE__), 'rails_root') + end + def file_list + Dir.glob(File.join(fake_rails_root, "db", "migrate", "*")) + end + end ------------------------------------------------------------------ @@ -156,7 +157,7 @@ After running the test with 'rake' you can make it pass with: [source, ruby] ------------------------------------------------------------------ -class YaffleGenerator < Rails::Generator::NamedBase +class YaffleMigrationGenerator < Rails::Generator::NamedBase def manifest record do |m| m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, @@ -169,6 +170,7 @@ class YaffleGenerator < Rails::Generator::NamedBase def custom_file_name custom_name = class_name.underscore.downcase custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names + custom_name end def yaffle_local_assigns diff --git a/railties/doc/guides/source/creating_plugins/models.txt b/railties/doc/guides/source/creating_plugins/models.txt index dfe11f9c4e..8b66de0f99 100644 --- a/railties/doc/guides/source/creating_plugins/models.txt +++ b/railties/doc/guides/source/creating_plugins/models.txt @@ -66,10 +66,8 @@ Finally, add the following to your plugin's 'schema.rb': [source, ruby] ---------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :woodpeckers, :force => true do |t| - t.string :name - end +create_table :woodpeckers, :force => true do |t| + t.string :name end ---------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt index cdc20e998e..249176729c 100644 --- a/railties/doc/guides/source/creating_plugins/routes.txt +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -22,10 +22,6 @@ class RoutingTest < Test::Unit::TestCase private - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. def assert_recognition(method, path, options) result = ActionController::Routing::Routes.recognize_path(path, :method => method) assert_equal options, result @@ -33,15 +29,16 @@ class RoutingTest < Test::Unit::TestCase end -------------------------------------------------------- -*vendor/plugins/yaffle/init.rb* +Once you see the tests fail by running 'rake', you can make them pass with: + +*vendor/plugins/yaffle/lib/yaffle.rb* [source, ruby] -------------------------------------------------------- -require "routing" -ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions +require "yaffle/routing" -------------------------------------------------------- -*vendor/plugins/yaffle/lib/routing.rb* +*vendor/plugins/yaffle/lib/yaffle/routing.rb* [source, ruby] -------------------------------------------------------- @@ -54,6 +51,8 @@ module Yaffle #:nodoc: end end end + +ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions -------------------------------------------------------- *config/routes.rb* @@ -61,7 +60,6 @@ end [source, ruby] -------------------------------------------------------- ActionController::Routing::Routes.draw do |map| - ... map.yaffles end -------------------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/tasks.txt b/railties/doc/guides/source/creating_plugins/tasks.txt index c71ba42bb0..d848c2cfa1 100644 --- a/railties/doc/guides/source/creating_plugins/tasks.txt +++ b/railties/doc/guides/source/creating_plugins/tasks.txt @@ -19,9 +19,7 @@ end When you run `rake -T` from your plugin you will see: --------------------------------------------------------- -... yaffle:squawk # Prints out the word 'Yaffle' -... --------------------------------------------------------- You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. -- cgit v1.2.3 From f22b686ebb8b8606e752188aa072b40700f01f54 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Mon, 17 Nov 2008 00:17:15 -0500 Subject: Plugin guide: re-ran rake guides --- railties/doc/guides/html/creating_plugins.html | 2 ++ 1 file changed, 2 insertions(+) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index ba7962d9ca..0fa9822c0c 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -1149,6 +1149,7 @@ http://www.gnu.org/software/src-highlite --> end end
    +

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

    vendor/plugins/yaffle/lib/yaffle.rb

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

    config/routes.rb

    -- cgit v1.2.3 From 3fbd9acc5c6418cffe8b2676f9e9e69ee1a84847 Mon Sep 17 00:00:00 2001 From: Jeff Dean Date: Mon, 17 Nov 2008 00:45:20 -0500 Subject: Plugin guide: Edits --- railties/doc/guides/html/creating_plugins.html | 35 ++++++---------------- .../guides/source/creating_plugins/appendix.txt | 3 +- .../guides/source/creating_plugins/generators.txt | 9 +----- .../doc/guides/source/creating_plugins/routes.txt | 4 ++- 4 files changed, 15 insertions(+), 36 deletions(-) diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 0fa9822c0c..850822c8ed 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -1120,7 +1120,8 @@ http://www.gnu.org/software/src-highlite -->

    8. Routes

    -

    Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2.

    +

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

    +

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

    vendor/plugins/yaffle/test/routing_test.rb

    9. Generators

    Many plugins ship with generators. When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in vendor/plugins/yaffle/generators/yaffle.

    -

    Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration.

    -

    To add a generator to a plugin:

    -
      -
    • -

      -Write a test -

      -
    • -
    • -

      -Add your instructions to the manifest method of the generator -

      -
    • -
    • -

      -Add any necessary template files to the templates directory -

      -
    • -
    • -

      -Update the USAGE file to add helpful documentation for your generator -

      -
    • -
    +

    Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file.

    9.1. Testing generators

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

      @@ -1804,7 +1782,7 @@ Warning, gotchas or tips that might help save users time

    15. Appendix

    -

    If you prefer to use RSpec instead of tets, you may be interested in the RSpec Plugin Generator.

    +

    If you prefer to use RSpec instead of Test::Unit, you may be interested in the RSpec Plugin Generator.

    15.1. References

    15.2. Contents of lib/yaffle.rb

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

    diff --git a/railties/doc/guides/source/creating_plugins/appendix.txt b/railties/doc/guides/source/creating_plugins/appendix.txt index 5c3bd20a1b..340c03dd4e 100644 --- a/railties/doc/guides/source/creating_plugins/appendix.txt +++ b/railties/doc/guides/source/creating_plugins/appendix.txt @@ -1,6 +1,6 @@ == Appendix == -If you prefer to use RSpec instead of tets, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. +If you prefer to use RSpec instead of Test::Unit, you may be interested in the http://github.com/pat-maddox/rspec-plugin-generator/tree/master[RSpec Plugin Generator]. === References === @@ -9,6 +9,7 @@ If you prefer to use RSpec instead of tets, you may be interested in the http:// * http://github.com/technoweenie/attachment_fu/tree/master * http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html * http://www.mbleigh.com/2008/6/11/gemplugins-a-brief-introduction-to-the-future-of-rails-plugins + * http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. === Contents of 'lib/yaffle.rb' === diff --git a/railties/doc/guides/source/creating_plugins/generators.txt b/railties/doc/guides/source/creating_plugins/generators.txt index 8ef46561d1..f856bec7a2 100644 --- a/railties/doc/guides/source/creating_plugins/generators.txt +++ b/railties/doc/guides/source/creating_plugins/generators.txt @@ -2,14 +2,7 @@ Many plugins ship with generators. When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in 'vendor/plugins/yaffle/generators/yaffle'. -Building generators is a complex topic unto itself and this section will cover one small aspect of generators: creating a generator that adds a time-stamped migration. - -To add a generator to a plugin: - - * Write a test - * Add your instructions to the 'manifest' method of the generator - * Add any necessary template files to the templates directory - * Update the USAGE file to add helpful documentation for your generator +Building generators is a complex topic unto itself and this section will cover one small aspect of generators: generating a simple text file. === Testing generators === diff --git a/railties/doc/guides/source/creating_plugins/routes.txt b/railties/doc/guides/source/creating_plugins/routes.txt index 249176729c..dc1bf09fd1 100644 --- a/railties/doc/guides/source/creating_plugins/routes.txt +++ b/railties/doc/guides/source/creating_plugins/routes.txt @@ -1,6 +1,8 @@ == Routes == -Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2. +In a standard 'routes.rb' file you use routes like 'map.connect' or 'map.resources'. You can add your own custom routes from a plugin. This section will describe how to add a custom method called that can be called with 'map.yaffles'. + +Testing routes from plugins is slightly different from testing routes in a standard rails app. To begin, add a test like this: *vendor/plugins/yaffle/test/routing_test.rb* -- cgit v1.2.3 From 896cff4ffb2bb72c0c7d8bbf90fb27817f8c0e5c Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Mon, 17 Nov 2008 06:41:32 -0600 Subject: Fix bad link in Getting Started guide --- railties/doc/guides/html/getting_started_with_rails.html | 2 +- railties/doc/guides/source/getting_started_with_rails.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 5111d0c645..2912bae98d 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -1990,7 +1990,7 @@ http://www.gnu.org/software/src-highlite -->
    • -The Ruby On Rails guides +The Ruby On Rails guides

    • diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index bae8f9a4fd..00c6d52eef 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -1219,7 +1219,7 @@ Note that each post has its own individual comments collection, accessible as +@ Now that you've seen your first Rails application, you should feel free to update it and experiment on your own. But you don't have to do everything without help. As you need assistance getting up and running with Rails, feel free to consult these support resources: -* The link:http://manuals.rubyonrails.org/[Ruby On Rails guides] +* The link:http://guides.rubyonrails.org/[Ruby On Rails guides] * The link:http://groups.google.com/group/rubyonrails-talk[Ruby on Rails mailing list] * The #rubyonrails channel on irc.freenode.net * The link:http://wiki.rubyonrails.org/rails[Rails wiki] -- cgit v1.2.3 From 74569f3e204b92e7c96a920b9bfde785323c61f4 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Mon, 17 Nov 2008 08:37:59 -0600 Subject: Structure change to AR Associations Guide --- railties/doc/guides/html/association_basics.html | 7 +++++-- railties/doc/guides/source/association_basics.txt | 10 ++++++++-- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html index 9159eaab2a..e8cad6c220 100644 --- a/railties/doc/guides/html/association_basics.html +++ b/railties/doc/guides/html/association_basics.html @@ -742,7 +742,9 @@ customer.orders

      3.2. Avoiding Name Collisions

      You are not free to use just any name for your associations. Because creating an association adds a method with that name to the model, it is a bad idea to give an association a name that is already used for an instance method of ActiveRecord::Base. The association method would override the base method and break things. For instance, attributes or connection are bad names for associations.

      3.3. Updating the Schema

      -

      Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate:

      +

      Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For belongs_to associations you need to create foreign keys, and for has_and_belongs_to_many associations you need to create the appropriate join table.

      +

      3.3.1. Creating Foreign Keys for belongs_to Associations

      +

      When you declare a belongs_to association, you need to create foreign keys as appropriate. For example, consider this model:

      end

      If you create an association some time after you build the underlying model, you need to remember to create an add_column migration to provide the necessary foreign key.

      -

      Second, if you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.

      +

      3.3.2. Creating Join Tables for has_and_belongs_to_many Associations

      +

      If you create a has_and_belongs_to_many association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the :join_table option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering.

      - +
      diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt index 5ba616642b..e0c9ee35d3 100644 --- a/railties/doc/guides/source/association_basics.txt +++ b/railties/doc/guides/source/association_basics.txt @@ -396,7 +396,11 @@ You are not free to use just any name for your associations. Because creating an === Updating the Schema -Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things. First, you need to create foreign keys as appropriate: +Associations are extremely useful, but they are not magic. You are responsible for maintaining your database schema to match your associations. In practice, this means two things, depending on what sort of associations you are creating. For +belongs_to+ associations you need to create foreign keys, and for +has_and_belongs_to_many+ associations you need to create the appropriate join table. + +==== Creating Foreign Keys for +belongs_to+ Associations + +When you declare a +belongs_to+ association, you need to create foreign keys as appropriate. For example, consider this model: [source, ruby] ------------------------------------------------------- @@ -426,7 +430,9 @@ end If you create an association some time after you build the underlying model, you need to remember to create an +add_column+ migration to provide the necessary foreign key. -Second, if you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. +==== Creating Join Tables for +has_and_belongs_to_many+ Associations + +If you create a +has_and_belongs_to_many+ association, you need to explicitly create the joining table. Unless the name of the join table is explicitly specified by using the +:join_table+ option, Active Record create the name by using the lexical order of the class names. So a join between customer and order models will give the default join table name of "customers_orders" because "c" outranks "o" in lexical ordering. WARNING: The precedence between model names is calculated using the +<+ operator for +String+. This means that if the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered of higher lexical precedence than the shorter one. For example, one would expect the tables "paper_boxes" and "papers" to generate a join table name of "papers_paper_boxes" because of the length of the name "paper_boxes", but it in fact generates a join table name of "paper_boxes_papers". -- cgit v1.2.3 From e1e0c126176cd7d3537c42df10e1ea6622a9ea14 Mon Sep 17 00:00:00 2001 From: Tore Darell Date: Mon, 17 Nov 2008 22:16:42 +0100 Subject: Fix various typos, add note about X-Sendfile to AC guide --- railties/doc/guides/source/actioncontroller_basics/cookies.txt | 2 +- railties/doc/guides/source/actioncontroller_basics/filters.txt | 4 ++-- .../guides/source/actioncontroller_basics/parameter_filtering.txt | 4 ++-- .../source/actioncontroller_basics/request_response_objects.txt | 6 +++--- railties/doc/guides/source/actioncontroller_basics/streaming.txt | 2 +- railties/doc/guides/source/actioncontroller_basics/verification.txt | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/railties/doc/guides/source/actioncontroller_basics/cookies.txt b/railties/doc/guides/source/actioncontroller_basics/cookies.txt index 88b99de3ee..9c30d29db4 100644 --- a/railties/doc/guides/source/actioncontroller_basics/cookies.txt +++ b/railties/doc/guides/source/actioncontroller_basics/cookies.txt @@ -31,4 +31,4 @@ class CommentsController < ApplicationController end ----------------------------------------- -Note that while for session values, you set the key to `nil`, to delete a cookie value, you should use `cookies.delete(:key)`. +Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`. diff --git a/railties/doc/guides/source/actioncontroller_basics/filters.txt b/railties/doc/guides/source/actioncontroller_basics/filters.txt index df67977efd..09a4bdf4f6 100644 --- a/railties/doc/guides/source/actioncontroller_basics/filters.txt +++ b/railties/doc/guides/source/actioncontroller_basics/filters.txt @@ -38,7 +38,7 @@ class ApplicationController < ActionController::Base end --------------------------------- -In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter` : +In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with `skip_before_filter`: [source, ruby] --------------------------------- @@ -49,7 +49,7 @@ class LoginsController < Application end --------------------------------- -Now, the +LoginsController+'s "new" and "create" actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place. +Now, the LoginsController's `new` and `create` actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place. === After Filters and Around Filters === diff --git a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt index e29f631038..0013492b73 100644 --- a/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt +++ b/railties/doc/guides/source/actioncontroller_basics/parameter_filtering.txt @@ -1,6 +1,6 @@ == Parameter Filtering == -Rails keeps a log file for each environment (development, test and production) in the "log" folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": +Rails keeps a log file for each environment (development, test and production) in the `log` folder. These are extremely useful when debugging what's actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The `filter_parameter_logging` method can be used to filter out sensitive information from the log. It works by replacing certain values in the `params` hash with "[FILTERED]" as they are written to the log. As an example, let's see how to filter all parameters with keys that include "password": [source, ruby] ------------------------- @@ -11,4 +11,4 @@ class ApplicationController < ActionController::Base end ------------------------- -The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true. +The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true. diff --git a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt index 07a8ec2574..846c24052d 100644 --- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt +++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt @@ -7,13 +7,13 @@ In every controller there are two accessor methods pointing to the request and t The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the link:http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html[API documentation]. Among the properties that you can access on this object are: * host - The hostname used for this request. - * domain - The hostname without the first segment (usually "www"). + * domain(n=2) - The hostname's first `n` segments, starting from the right (the TLD) * format - The content type requested by the client. * method - The HTTP method used for the request. - * get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head. + * get?, post?, put?, delete?, head? - Returns true if the HTTP method is GET/POST/PUT/DELETE/HEAD. * headers - Returns a hash containing the headers associated with the request. * port - The port number (integer) used for the request. - * protocol - The protocol used for the request. + * protocol - Returns a string containing the prototol used plus "://", for example "http://" * query_string - The query string part of the URL - everything after "?". * remote_ip - The IP address of the client. * url - The entire URL used for the request. diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt index dc8ebe6d55..2a930835ee 100644 --- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt +++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt @@ -52,7 +52,7 @@ This will read and stream the file 4Kb at the time, avoiding loading the entire WARNING: Be careful when using (or just don't use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see. -TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. +TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the `:x_sendfile` option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the `X-Sendfile` header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files. === RESTful Downloads === diff --git a/railties/doc/guides/source/actioncontroller_basics/verification.txt b/railties/doc/guides/source/actioncontroller_basics/verification.txt index 5d8ee6117e..a4522a0102 100644 --- a/railties/doc/guides/source/actioncontroller_basics/verification.txt +++ b/railties/doc/guides/source/actioncontroller_basics/verification.txt @@ -25,7 +25,7 @@ class LoginsController < ApplicationController end --------------------------------------- -Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter: +Now the `create` action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the `new` action will be rendered. But there's something rather important missing from the verification above: It will be used for *every* action in LoginsController, which is not what we want. You can limit which actions it will be used for with the `:only` and `:except` options just like a filter: [source, ruby] --------------------------------------- -- cgit v1.2.3 From 047657cdfb7ad63ede151d84fbb922d63f641437 Mon Sep 17 00:00:00 2001 From: Sven Fuchs Date: Tue, 18 Nov 2008 00:41:06 +0100 Subject: initial draft for i18n guide --- railties/doc/guides/source/i18n.txt | 541 +++++++++++++++++++++++++++++++++++ railties/doc/guides/source/index.txt | 10 + 2 files changed, 551 insertions(+) create mode 100644 railties/doc/guides/source/i18n.txt diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt new file mode 100644 index 0000000000..c9867ba0ac --- /dev/null +++ b/railties/doc/guides/source/i18n.txt @@ -0,0 +1,541 @@ +The Rails Internationalization API +================================== + +The Ruby I18n gem which is shipped with Ruby on Rails (starting from Rails 2.2) provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or providing multi-language support in your application. + +== How I18n in Ruby on Rails works + +Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on: + +* providing support for English and similar languages out of the box +* making it easy to customize and extend everything for other languages + +=== The overall architecture of the library + +To solve this the Ruby I18n gem is split into two parts: + +* The public API which is just a Ruby module with a bunch of public methods and definitions how the library works. +* A shipped backend (which is intentionally named the Simple backend) that implements these methods. + +As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one. + +=== The public I18n API + +We will go into more detail about the public methods later but here's a quick overview. The most important methods are: + +[source, ruby] +------------------------------------------------------- +translate # lookup translations +localize # localize Date and Time objects to local formats +------------------------------------------------------- + +There are also attribute readers and writers for the following attributes: + +[source, ruby] +------------------------------------------------------- +load_path # announce your custom translation files +locale # get and set the current locale +default_locale # get and set the default locale +exception_handler # use a different exception_handler +backend # use a different backend +------------------------------------------------------- + +== Walkthrough: setup a simple I18n'ed Rails application + +There are just a few, simple steps to get up and running with a I18n support for your application. + +=== Configure the I18n module + +First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English. + +You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer: + +[source, ruby] +------------------------------------------------------- +# in config/initializer/locale.rb + +# tell the I18n library where to find your translations +I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ] + +# you can omit this if you're happy with English as a default locale +I18n.default_locale = :"pt-BR" +------------------------------------------------------- + +I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced. + +=== Set the locale in each request + +By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English). + +If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this: + +[source, ruby] +------------------------------------------------------- +before_filter :set_locale +def set_locale + # if this is nil then I18n.default_locale will be used + I18n.locale = params[:locale] +end +------------------------------------------------------- + +This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section). + +Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff. + +=== Internationalize your application + +The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits. + +So, let's internationalize something. You most probably have something like this in one of your applications: + +[source, ruby] +------------------------------------------------------- +# config/routes.rb +ActionController::Routing::Routes.draw do |map| + map.root :controller => 'home', :action => 'index' +end + +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = "Hello flash!" + end +end + +# app/views/home/index.html.erb +

      Hello world!

      +

      <%= flash[:notice] %>

      +------------------------------------------------------- + +TODO screenshot + +Obviously there are two strings that are localized to English. In order to internationalize this code replace these strings with calls to Rails' #t helper with a key that makes sense for the translation: + +[source, ruby] +------------------------------------------------------- +# app/controllers/home_controller.rb +class HomeController < ApplicationController + def index + flash[:notice] = t(:hello_flash) + end +end + +# app/views/home/index.html.erb +

      <%=t :hello_world %>

      +

      <%= flash[:notice] %>

      +------------------------------------------------------- + +TODO insert note about #t helper compared to I18n.t + +TODO insert note/reference about structuring translation keys + +When you now render this view it will show an error message that tells you that the translations for the keys :hello_world and :hello_flash are missing. + +TODO screenshot + +So let's add the missing translations (i.e. do the "localization" part): + +[source, ruby] +------------------------------------------------------- +# lib/locale/en-US.yml +en-US: + hello_world: Hello World + hello_flash: Hello Flash + +# lib/locale/pirate.yml +pirate: + hello_world: Ahoy World + hello_flash: Ahoy Flash +------------------------------------------------------- + +There you go. Your application now shows: + +TODO screenshot + +[source, ruby] +------------------------------------------------------- +I18n.t 'store.title' +I18n.l Time.now +------------------------------------------------------- + + +== Overview of the I18n API features + +The following purposes are covered: + +* lookup translations +* interpolate data into translations +* pluralize translations +* localize dates, numbers, currency etc. + +=== Looking up translations + +==== Basic lookup, scopes and nested keys + +Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent: + +[source, ruby] +------------------------------------------------------- +I18n.t :message +I18n.t 'message' +------------------------------------------------------- + +translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key: + +[source, ruby] +------------------------------------------------------- +I18n.t :invalid, :scope => [:active_record, :error_messages] +------------------------------------------------------- + +This looks up the :invalid message in the ActiveRecord error messages. + +Additionally, both the key and scopes can be specified as dot separated keys as in: + +[source, ruby] +------------------------------------------------------- +I18n.translate :"active_record.error_messages.invalid" +------------------------------------------------------- + +Thus the following calls are equivalent: + +[source, ruby] +------------------------------------------------------- +I18n.t 'active_record.error_messages.invalid' +I18n.t 'error_messages.invalid', :scope => :active_record +I18n.t :invalid, :scope => 'active_record.error_messages' +I18n.t :invalid, :scope => [:active_record, :error_messages] +------------------------------------------------------- + +==== Defaults + +When a default option is given its value will be returned if the translation is missing: + +[source, ruby] +------------------------------------------------------- +I18n.t :missing, :default => 'Not here' +# => 'Not here' +------------------------------------------------------- + +If the default value is a Symbol it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned. + +E.g. the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result the string ‘Not here’ will be returned: + +[source, ruby] +------------------------------------------------------- +I18n.t :missing, :default => [:also_missing, 'Not here'] +# => 'Not here' +------------------------------------------------------- + +==== Bulk and namespace lookup + +To lookup multiple translations at once an array of keys can be passed: + +[source, ruby] +------------------------------------------------------- +I18n.t [:odd, :even], :scope => 'active_record.error_messages' +# => ["must be odd", "must be even"] +------------------------------------------------------- + +Also, a key can translate to a (potentially nested) hash as grouped translations. E.g. one can receive all ActiveRecord error messages as a Hash with: + +[source, ruby] +------------------------------------------------------- +I18n.t 'active_record.error_messages' +# => { :inclusion => "is not included in the list", :exclusion => ... } +------------------------------------------------------- + +=== Interpolation + +TODO explain what this is good for + +All options besides :default and :scope that are passed to #translate will be interpolated to the translation: + +[source, ruby] +------------------------------------------------------- +I18n.backend.store_translations 'en-US', :thanks => 'Thanks {{name}}!' +I18n.translate :thanks, :name => 'Jeremy' +# => 'Thanks Jeremy!' +------------------------------------------------------- + +If a translation uses :default or :scope as a interpolation variable an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable but it has not been passed to #translate an I18n::MissingInterpolationArgument exception is raised. + +=== Pluralization + +TODO explain what this is good for + +The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR: + +[source, ruby] +------------------------------------------------------- +I18n.backend.store_translations 'en-US', :inbox => { # TODO change this + :one => '1 message', + :other => '{{count}} messages' +} +I18n.translate :inbox, :count => 2 +# => '2 messages' +------------------------------------------------------- + +The algorithm for pluralizations in en-US is as simple as: + +[source, ruby] +------------------------------------------------------- +entry[count == 1 ? 0 : 1] +------------------------------------------------------- + +I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero). + +If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised. + +=== Setting and passing a locale + +The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize. + +If no locale is passed I18n.locale is used: + +[source, ruby] +------------------------------------------------------- +I18n.locale = :'de-DE' +I18n.t :foo +I18n.l Time.now +------------------------------------------------------- + +Explicitely passing a locale: + +[source, ruby] +------------------------------------------------------- +I18n.t :foo, :locale => :'de-DE' +I18n.l Time.now, :locale => :'de-DE' +------------------------------------------------------- + +I18n.locale defaults to I18n.default_locale which defaults to :'en-US'. The default locale can be set like this: + +[source, ruby] +------------------------------------------------------- +I18n.default_locale = :'de-DE' +------------------------------------------------------- + +== How to store your custom translations + +The shipped Simple backend allows you to store translations in both plain Ruby and YAML format. (2) + +For example a Ruby Hash providing translations can look like this: + +[source, ruby] +------------------------------------------------------- +{ + :'pt-BR' => { + :foo => { + :bar => "baz" + } + } +} +------------------------------------------------------- + +The equivalent YAML file would look like this: + +[source, ruby] +------------------------------------------------------- +"pt-BR": + foo: + bar: baz +------------------------------------------------------- + +As you see in both cases the toplevel key is the locale. :foo is a namespace key and :bar is the key for the translation "baz". + +Here is a "real" example from the ActiveSupport en-US translations YAML file: + +[source, ruby] +------------------------------------------------------- +"en-US": + date: + formats: + default: "%Y-%m-%d" + short: "%b %d" + long: "%B %d, %Y" +------------------------------------------------------- + +So, all of the following equivalent lookups will return the :short date format "%B %d": + +[source, ruby] +------------------------------------------------------- +I18n.t 'date.formats.short' +I18n.t 'formats.short', :scope => :date +I18n.t :short, :scope => 'date.formats' +I18n.t :short, :scope => [:date, :formats] +------------------------------------------------------- + +=== Translations for ActiveRecord models + +You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently lookup translations for your model and attribute names. + +For example when you add the following translations: + +en-US: + activerecord: + models: + user: Dude + attributes: + user: + login: "Handle" + # will translate User attribute "login" as "Handle" + +Then User.human_name will return "Dude" and User.human_attribute_name(:login) will return "Handle". + +==== Error message scopes + +ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account. + +This gives you quite powerful means to flexibly adjust your messages to your application's needs. + +Consider a User model with a validates_presence_of validation for the name attribute like this: + +[source, ruby] +------------------------------------------------------- +class User < ActiveRecord::Base + validates_presence_of :name +end +------------------------------------------------------- + +The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.models.user.attributes.name.blank +------------------------------------------------------- + +If it's not there it will try: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.models.user.blank +------------------------------------------------------- + +If this is also not there it will use the default message from: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.messages.blank +------------------------------------------------------- + +When your models are additionally using inheritance then the messages are looked up for the inherited model class names are looked up. + +For example, you might have an Admin model inheriting from User: + +[source, ruby] +------------------------------------------------------- +class Admin < User + validates_presence_of :name +end +------------------------------------------------------- + +Then ActiveRecord will look for messages in this order: + +[source, ruby] +------------------------------------------------------- +activerecord.errors.models.admin.attributes.title.blank +activerecord.errors.models.admin.blank +activerecord.errors.models.user.attributes.title.blank +activerecord.errors.models.user.blank +activerecord.errors.messages.blank +------------------------------------------------------- + +This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models or default scopes. + +==== Error message interpolation + +The translated model name and translated attribute name are always available for interpolation. + +So, for example, instead of the default error message "can not be blank" you could use the attribute name like this: "Please fill in your {{attribute}}". + +Count and/or value are available where applicable. Count can be used for pluralization if present: + +[grid="all"] +`---------------------------`----------------`---------------`---------------- +validation with option message interpolation +validates_confirmation_of - :confirmation - +validates_acceptance_of - :accepted - +validates_presence_of - :blank - +validates_length_of :within, :in :too_short count +validates_length_of :within, :in :too_long count +validates_length_of :is :wrong_length count +validates_length_of :minimum :too_short count +validates_length_of :maximum :too_long count +validates_uniqueness_of - :taken value +validates_format_of - :invalid value +validates_inclusion_of - :inclusion value +validates_exclusion_of - :exclusion value +validates_associated - :invalid value +validates_numericality_of - :not_a_number value +validates_numericality_of :odd :odd value +validates_numericality_of :even :even value +------------------------------------------------------------------------------ + + +==== Translations for the ActiveRecord error_messages_for helper + +If you are using the ActiveRecord error_messages_for helper you will want to add translations for it. + +Rails ships with the following translations: + +[source, ruby] +------------------------------------------------------- +"en-US": + activerecord: + errors: + template: + header: + one: "1 error prohibited this {{model}} from being saved" + other: "{{count}} errors prohibited this {{model}} from being saved" + body: "There were problems with the following fields:" +------------------------------------------------------- + + +=== Other translations and localizations + +Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. + +TODO list helpers and available keys + +== Customize your I18n setup + +=== Using different backends + +For several reasons the shipped Simple backend only does the "simplest thing that ever could work" _for Ruby on Rails_ (1) ... which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format. + +That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend: + +[source, ruby] +------------------------------------------------------- +I18n.backend = Globalize::Backend::Static.new +------------------------------------------------------- + +TODO expand this ...? list some backends and their features? + +=== Using different exception handlers + +TODO + +* Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend. +* Explain the default behaviour. +* Explain the :raise option + +* Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing" +* Example 2: for tests you might want a handler that just raises all exceptions all the time +* Example 3: a handler + + +== Resources + + +== Footnotes + +(1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions. + +(2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files. + +== Credits + +== NOTES + +How to contribute? + diff --git a/railties/doc/guides/source/index.txt b/railties/doc/guides/source/index.txt index 8828e1d313..a5648fb757 100644 --- a/railties/doc/guides/source/index.txt +++ b/railties/doc/guides/source/index.txt @@ -113,6 +113,16 @@ This guide covers ways to analyze and optimize your running Rails code. This guide covers how to build a plugin to extend the functionality of Rails. *********************************************************** +.link:i18n.html[The Rails Internationalization API] +*********************************************************** +CAUTION: still a basic draft + +This guide introduces you to the basic concepts and features of the Rails I18n API and shows you how to localize your application. +*********************************************************** + + + + Authors who have contributed to complete guides are listed link:authors.html[here]. This work is licensed under a link:http://creativecommons.org/licenses/by-nc-sa/3.0/[Creative Commons Attribution-Noncommercial-Share Alike 3.0 License] -- cgit v1.2.3 From 90a1a9a2253381ba0799848beadf29232affb8d5 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 18 Nov 2008 00:41:20 +0100 Subject: adding a config file for asciidoc, needs latest mizuho to take effect --- railties/Rakefile | 3 ++- railties/doc/guides/asciidoc.conf | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 railties/doc/guides/asciidoc.conf diff --git a/railties/Rakefile b/railties/Rakefile index 52357a09c5..98aac97022 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -282,6 +282,7 @@ task :guides do FileUtils.mkdir(html) template = File.expand_path("doc/guides/source/templates/guides.html.erb") + asciidoc_conf = 'doc/guides/asciidoc.conf' ignore = ['..', 'icons', 'images', 'templates', 'stylesheets'] ignore << 'active_record_basics.txt' @@ -311,7 +312,7 @@ task :guides do begin puts "GENERATING => #{output}" ENV['MANUALSONRAILS_TOC'] = 'no' if indexless.include?(entry) - Mizuho::Generator.new(input, :output => output, :template => template).start + Mizuho::Generator.new(input, :output => output, :template => template, :conf_file => asciidoc_conf).start rescue Mizuho::GenerationError STDERR.puts "*** ERROR" exit 2 diff --git a/railties/doc/guides/asciidoc.conf b/railties/doc/guides/asciidoc.conf new file mode 100644 index 0000000000..f8e0c0a32c --- /dev/null +++ b/railties/doc/guides/asciidoc.conf @@ -0,0 +1,26 @@ +# Asciidoc substitutes some characters by default, those are called +# "replacements" in the docs. For example => becomes a unicode arrow. +# +# We override replacements to allow copy & paste of source code. + +[replacements] + +# Ellipsis +(? right arrow +(? right double arrow +(? Date: Tue, 18 Nov 2008 10:50:21 -0600 Subject: FIx minor errors in Getting Started & Associations guides --- railties/doc/guides/source/association_basics.txt | 8 ++++---- railties/doc/guides/source/getting_started_with_rails.txt | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/railties/doc/guides/source/association_basics.txt b/railties/doc/guides/source/association_basics.txt index e0c9ee35d3..39d92be2d2 100644 --- a/railties/doc/guides/source/association_basics.txt +++ b/railties/doc/guides/source/association_basics.txt @@ -354,8 +354,8 @@ In designing a data model, you will sometimes find a model that should have a re [source, ruby] ------------------------------------------------------- class Employee < ActiveRecord::Base - has_many :subordinates, :class_name => "User", :foreign_key => "manager_id" - belongs_to :manager, :class_name => "User" + has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id" + belongs_to :manager, :class_name => "Employee" end ------------------------------------------------------- @@ -1336,7 +1336,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ @@ -1704,7 +1704,7 @@ end ===== +:offset+ -The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 10 records. +The +:offset+ option lets you specify the starting offset for fetching objects via an association. For example, if you set +:offset => 11+, it will skip the first 11 records. ===== +:order+ diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index 00c6d52eef..9adcc729a3 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -1021,7 +1021,7 @@ class CommentsController < ApplicationController def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1033,7 +1033,7 @@ class CommentsController < ApplicationController @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1041,14 +1041,14 @@ class CommentsController < ApplicationController def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end -- cgit v1.2.3 From 24bc0b267d1c313d78424eeffda6d8eaa5be0c24 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 10:50:42 -0600 Subject: Regenerate Guide HTML --- .../doc/guides/html/actioncontroller_basics.html | 20 +- railties/doc/guides/html/association_basics.html | 8 +- .../guides/html/getting_started_with_rails.html | 8 +- railties/doc/guides/html/i18n.html | 1079 ++++++++++++++++++++ railties/doc/guides/html/index.html | 13 + 5 files changed, 1110 insertions(+), 18 deletions(-) create mode 100644 railties/doc/guides/html/i18n.html diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index 66563bf1a3..4af157d4f7 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -723,7 +723,7 @@ http://www.gnu.org/software/src-highlite --> end -

      Note that while for session values, you set the key to nil, to delete a cookie value, you should use cookies.delete(:key).

      +

      Note that while for session values you set the key to nil, to delete a cookie value you should use cookies.delete(:key).

      6. Filters

      @@ -767,7 +767,7 @@ http://www.gnu.org/software/src-highlite --> end
      -

      In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter :

      +

      In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with skip_before_filter:

      end
      -

      Now, the LoginsController's "new" and "create" actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

      +

      Now, the LoginsController's new and create actions will work as before without requiring the user to be logged in. The :only option is used to only skip this filter for these actions, and there is also an :except option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.

      6.1. After Filters and Around Filters

      In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that's about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter's way of stopping it.

      @@ -872,7 +872,7 @@ http://www.gnu.org/software/src-highlite --> end
      -

      Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the "new" action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:

      +

      Now the create action won't run unless the "username" and "password" parameters are present, and if they're not, an error message will be added to the flash and the new action will be rendered. But there's something rather important missing from the verification above: It will be used for every action in LoginsController, which is not what we want. You can limit which actions it will be used for with the :only and :except options just like a filter:

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

      11.2. RESTful Downloads

      @@ -1166,7 +1166,7 @@ http://www.gnu.org/software/src-highlite -->

    12. 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":

    end
    -

    The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in return and replaces those for which the block returns true.

    +

    The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.

    13. Rescue

    diff --git a/railties/doc/guides/html/association_basics.html b/railties/doc/guides/html/association_basics.html index e8cad6c220..3eea8b421f 100644 --- a/railties/doc/guides/html/association_basics.html +++ b/railties/doc/guides/html/association_basics.html @@ -687,8 +687,8 @@ by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    class Employee < ActiveRecord::Base
    -  has_many :subordinates, :class_name => "User", :foreign_key => "manager_id"
    -  belongs_to :manager, :class_name => "User"
    +  has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
    +  belongs_to :manager, :class_name => "Employee"
     end
     

    With this setup, you can retrieve @employee.subordinates and @employee.manager.

    @@ -1941,7 +1941,7 @@ http://www.gnu.org/software/src-highlite --> end
    :offset
    -

    The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.

    +

    The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.

    :order

    The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).

    @@ -2412,7 +2412,7 @@ http://www.gnu.org/software/src-highlite --> end
    :offset
    -

    The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 10 records.

    +

    The :offset option lets you specify the starting offset for fetching objects via an association. For example, if you set :offset ⇒ 11, it will skip the first 11 records.

    :order

    The :order option dictates the order in which associated objects will be received (in the syntax used by a SQL ORDER BY clause).

    diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 2912bae98d..304c26a54f 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -1791,7 +1791,7 @@ http://www.gnu.org/software/src-highlite --> def show @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def new @@ -1803,7 +1803,7 @@ http://www.gnu.org/software/src-highlite --> @post = Post.find(params[:post_id]) @comment = @post.comments.build(params[:comment]) if @comment.save - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "new" end @@ -1811,14 +1811,14 @@ http://www.gnu.org/software/src-highlite --> def edit @post = Post.find(params[:post_id]) - @comment = Comment.find(params[:id]) + @comment = @post.comments.find(params[:id]) end def update @post = Post.find(params[:post_id]) @comment = Comment.find(params[:id]) if @comment.update_attributes(params[:comment]) - redirect_to post_comment_path(@post, @comment) + redirect_to post_comment_url(@post, @comment) else render :action => "edit" end diff --git a/railties/doc/guides/html/i18n.html b/railties/doc/guides/html/i18n.html new file mode 100644 index 0000000000..3504a9e366 --- /dev/null +++ b/railties/doc/guides/html/i18n.html @@ -0,0 +1,1079 @@ + + + + + The Rails Internationalization API + + + + + + + + + +
    + + + +
    +

    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.

    +
    +
    +

    1. How I18n in Ruby on Rails works

    +
    +

    Internationalization is a complex problem. Natural languages differ in so many ways that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focusses on:

    +
      +
    • +

      +providing support for English and similar languages out of the box +

      +
    • +
    • +

      +making it easy to customize and extend everything for other languages +

      +
    • +
    +

    1.1. The overall architecture of the library

    +

    To solve this the Ruby I18n gem is split into two parts:

    +
      +
    • +

      +The public API which is just a Ruby module with a bunch of public methods and definitions how the library works. +

      +
    • +
    • +

      +A shipped backend (which is intentionally named the Simple backend) that implements these methods. +

      +
    • +
    +

    As a user you should always only access the public methods on the I18n module but it is useful to know about the capabilities of the backend you use and maybe exchange the shipped Simple backend with a more powerful one.

    +

    1.2. The public I18n API

    +

    We will go into more detail about the public methods later but here's a quick overview. The most important methods are:

    +
    +
    +
    translate         # lookup translations
    +localize          # localize Date and Time objects to local formats
    +
    +

    There are also attribute readers and writers for the following attributes:

    +
    +
    +
    load_path         # announce your custom translation files
    +locale            # get and set the current locale
    +default_locale    # get and set the default locale
    +exception_handler # use a different exception_handler
    +backend           # use a different backend
    +
    +
    +

    2. Walkthrough: setup a simple I18n'ed Rails application

    +
    +

    There are just a few, simple steps to get up and running with a I18n support for your application.

    +

    2.1. Configure the I18n module

    +

    First of all you want to tell the I18n library where it can find your custom translation files. You might also want to set your default locale to something else than English.

    +

    You can pick whatever directory and translation file naming scheme makes sense for you. The simplest thing possible is probably to put the following into an initializer:

    +
    +
    +
    # in config/initializer/locale.rb
    +
    +# tell the I18n library where to find your translations
    +I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ]
    +
    +# you can omit this if you're happy with English as a default locale
    +I18n.default_locale = :"pt-BR"
    +
    +

    I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced.

    +

    2.2. Set the locale in each request

    +

    By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English).

    +

    If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this:

    +
    +
    +
    before_filter :set_locale
    +def set_locale
    +  # if this is nil then I18n.default_locale will be used
    +  I18n.locale = params[:locale]
    +end
    +
    +

    This will already work for URLs where you pass the locale as a query parameter as in example.com?locale=pt-BR (which is what Google also does). (TODO hints about other approaches in the resources section).

    +

    Now you've initialized I18n support for your application and told it which locale should be used. With that in place you're now ready for the really interesting stuff.

    +

    2.3. Internationalize your application

    +

    The process of "internationalization" usually means to abstract all strings and other locale specific bits out of your application (TODO reference to wikipedia). The process of "localization" means to then provide translations and localized formats for these bits.

    +

    So, let's internationalize something. You most probably have something like this in one of your applications:

    +
    +
    +
    # 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:

    +
    +
    +
    # 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):

    +
    +
    +
    # 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

    +
    +
    +
    I18n.t 'store.title'
    +I18n.l Time.now
    +
    +
    +

    3. Overview of the I18n API features

    +
    +

    The following purposes are covered:

    +
      +
    • +

      +lookup translations +

      +
    • +
    • +

      +interpolate data into translations +

      +
    • +
    • +

      +pluralize translations +

      +
    • +
    • +

      +localize dates, numbers, currency etc. +

      +
    • +
    +

    3.1. Looking up translations

    +

    3.1.1. Basic lookup, scopes and nested keys

    +

    Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:

    +
    +
    +
    I18n.t :message
    +I18n.t 'message'
    +
    +

    translate also takes a :scope option which can contain one or many additional keys that will be used to specify a “namespace” or scope for a translation key:

    +
    +
    +
    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:

    +
    +
    +
    I18n.translate :"active_record.error_messages.invalid"
    +
    +

    Thus the following calls are equivalent:

    +
    +
    +
    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]
    +
    +

    3.1.2. Defaults

    +

    When a default option is given its value will be returned if the translation is missing:

    +
    +
    +
    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:

    +
    +
    +
    I18n.t :missing, :default => [:also_missing, 'Not here']
    +# => 'Not here'
    +
    +

    3.1.3. Bulk and namespace lookup

    +

    To lookup multiple translations at once an array of keys can be passed:

    +
    +
    +
    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:

    +
    +
    +
    I18n.t 'active_record.error_messages'
    +# => { :inclusion => "is not included in the list", :exclusion => ... }
    +
    +

    3.2. 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:

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

    +

    3.3. Pluralization

    +

    TODO explain what this is good for

    +

    The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by CLDR:

    +
    +
    +
    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:

    +
    +
    +
    entry[count == 1 ? 0 : 1]
    +
    +

    I.e. the translation denoted as :one is regarded as singular, the other is used as plural (including the count being zero).

    +

    If the lookup for the key does not return an Hash suitable for pluralization an I18n::InvalidPluralizationData exception is raised.

    +

    3.4. Setting and passing a locale

    +

    The locale can be either set pseudo-globally to I18n.locale (which uses Thread.current like, e.g., Time.zone) or can be passed as an option to #translate and #localize.

    +

    If no locale is passed I18n.locale is used:

    +
    +
    +
    I18n.locale = :'de-DE'
    +I18n.t :foo
    +I18n.l Time.now
    +
    +

    Explicitely passing a locale:

    +
    +
    +
    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:

    +
    +
    +
    I18n.default_locale = :'de-DE'
    +
    +
    +

    4. 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:

    +
    +
    +
    {
    +  :'pt-BR' => {
    +    :foo => {
    +      :bar => "baz"
    +    }
    +  }
    +}
    +
    +

    The equivalent YAML file would look like this:

    +
    +
    +
    "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:

    +
    +
    +
    "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":

    +
    +
    +
    I18n.t 'date.formats.short'
    +I18n.t 'formats.short', :scope => :date
    +I18n.t :short, :scope => 'date.formats'
    +I18n.t :short, :scope => [:date, :formats]
    +
    +

    4.1. 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".

    +

    4.1.1. Error message scopes

    +

    ActiveRecord validation error messages can also be translated easily. ActiveRecord gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes and/or validations. It also transparently takes single table inheritance into account.

    +

    This gives you quite powerful means to flexibly adjust your messages to your application's needs.

    +

    Consider a User model with a validates_presence_of validation for the name attribute like this:

    +
    +
    +
    class User < ActiveRecord::Base
    +  validates_presence_of :name
    +end
    +
    +

    The key for the error message in this case is :blank. So ActiveRecord will first try to look up an error message with:

    +
    +
    +
    activerecord.errors.messages.models.user.attributes.name.blank
    +
    +

    If it's not there it will try:

    +
    +
    +
    activerecord.errors.messages.models.user.blank
    +
    +

    If this is also not there it will use the default message from:

    +
    +
    +
    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:

    +
    +
    +
    class Admin < User
    +  validates_presence_of :name
    +end
    +
    +

    Then ActiveRecord will look for messages in this order:

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

    +

    4.1.2. Error message interpolation

    +

    The translated model name and translated attribute name are always available for interpolation.

    +

    +

    Count and/or value are available where applicable. Count can be used for pluralization if present:

    +
    + +++++ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + validation + + with option + + message + + interpolation +
    + validates_confirmation_of + + - + + :confirmation + + - +
    + validates_acceptance_of + + - + + :accepted + + - +
    + validates_presence_of + + - + + :blank + + - +
    + validates_length_of + + :within, :in + + :too_short + + count +
    + validates_length_of + + :within, :in + + :too_long + + count +
    + validates_length_of + + :is + + :wrong_length + + count +
    + validates_length_of + + :minimum + + :too_short + + count +
    + validates_length_of + + :maximum + + :too_long + + count +
    + validates_uniqueness_of + + - + + :taken + + value +
    + validates_format_of + + - + + :invalid + + value +
    + validates_inclusion_of + + - + + :inclusion + + value +
    + validates_exclusion_of + + - + + :exclusion + + value +
    + validates_associated + + - + + :invalid + + value +
    + validates_numericality_of + + - + + :not_a_number + + value +
    + validates_numericality_of + + :odd + + :odd + + value +
    + validates_numericality_of + + :even + + :even + + value +
    +
    +

    4.1.3. Translations for the ActiveRecord error_messages_for helper

    +

    If you are using the ActiveRecord error_messages_for helper you will want to add translations for it.

    +

    Rails ships with the following translations:

    +
    +
    +
    "en-US":
    +  activerecord:
    +    errors:
    +      template:
    +        header:
    +          one:   "1 error prohibited this {{model}} from being saved"
    +          other: "{{count}} errors prohibited this {{model}} from being saved"
    +        body: "There were problems with the following fields:"
    +
    +

    4.2. Other translations and localizations

    +

    Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers.

    +

    TODO list helpers and available keys

    +
    +

    5. Customize your I18n setup

    +
    +

    5.1. Using different backends

    +

    For several reasons the shipped Simple backend only does the "simplest thing that ever could work" for Ruby on Rails (1) … which means that it is only guaranteed to work for English and, as a side effect, languages that are very similar to English. Also, the simple backend is only capable of reading translations but can not dynamically store them to any format.

    +

    That does not mean you're stuck with these limitations though. The Ruby I18n gem makes it very easy to exchange the Simple backend implementation with something else that fits better for your needs. E.g. you could exchange it with Globalize's Static backend:

    +
    +
    +
    I18n.backend = Globalize::Backend::Static.new
    +
    +

    TODO expand this …? list some backends and their features?

    +

    5.2. Using different exception handlers

    +

    TODO

    +
      +
    • +

      +Explain what exceptions are raised and why we are using exceptions for communication from backend to frontend. +

      +
    • +
    • +

      +Explain the default behaviour. +

      +
    • +
    • +

      +Explain the :raise option +

      +
    • +
    • +

      +Example 1: the Rails #t helper uses a custom exception handler that catches I18n::MissingTranslationData and wraps the message into a span with the CSS class "translation_missing" +

      +
    • +
    • +

      +Example 2: for tests you might want a handler that just raises all exceptions all the time +

      +
    • +
    • +

      +Example 3: a handler +

      +
    • +
    +
    +

    6. Resources

    +
    +
    +

    7. Footnotes

    +
    +

    (1) One of these reasons is that we don't want to any unnecessary load for applications that do not need any I18n capabilities, so we need to keep the I18n library as simple as possible for English. Another reason is that it is virtually impossible to implement a one-fits-all solution for all problems related to I18n for all existing languages. So a solution that allows us to exchange the entire implementation easily is appropriate anyway. This also makes it much easier to experiment with custom features and extensions.

    +

    (2) Other backends might allow or require to use other formats, e.g. a GetText backend might allow to read GetText files.

    +
    +

    8. Credits

    +
    +
    +

    9. NOTES

    +
    +

    How to contribute?

    +
    + +
    +
    + + diff --git a/railties/doc/guides/html/index.html b/railties/doc/guides/html/index.html index 991b10c7e8..45e131012e 100644 --- a/railties/doc/guides/html/index.html +++ b/railties/doc/guides/html/index.html @@ -338,6 +338,19 @@ of your code.

    This guide covers how to build a plugin to extend the functionality of Rails.

    +
    +

    Authors who have contributed to complete guides are listed here.

    -- cgit v1.2.3 From b930d2f259f7ebf3c7134db82dde02c55e00070c Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 11:03:31 -0600 Subject: Finishing up RDoc 2.x markup for cattr_accessors --- activemodel/lib/active_model/errors.rb | 2 ++ activeresource/lib/active_resource/base.rb | 2 ++ activesupport/lib/active_support/buffered_logger.rb | 2 ++ activesupport/lib/active_support/core_ext/logger.rb | 2 ++ 4 files changed, 8 insertions(+) diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index a99bb001e4..bcf0810290 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -24,6 +24,8 @@ module ActiveModel :even => "must be even" } + ## + # :singleton-method: # Holds a hash with all the default error messages that can be replaced by your own copy or localizations. cattr_accessor :default_error_messages diff --git a/activeresource/lib/active_resource/base.rb b/activeresource/lib/active_resource/base.rb index bb284803d8..303b09ba76 100644 --- a/activeresource/lib/active_resource/base.rb +++ b/activeresource/lib/active_resource/base.rb @@ -202,6 +202,8 @@ module ActiveResource # sets the read_timeout of the internal Net::HTTP instance to the same value. The default # read_timeout is 60 seconds on most Ruby implementations. class Base + ## + # :singleton-method: # The logger for diagnosing and tracing Active Resource calls. cattr_accessor :logger diff --git a/activesupport/lib/active_support/buffered_logger.rb b/activesupport/lib/active_support/buffered_logger.rb index 77e0b1d33f..b2c863c893 100644 --- a/activesupport/lib/active_support/buffered_logger.rb +++ b/activesupport/lib/active_support/buffered_logger.rb @@ -13,6 +13,8 @@ module ActiveSupport MAX_BUFFER_SIZE = 1000 + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true diff --git a/activesupport/lib/active_support/core_ext/logger.rb b/activesupport/lib/active_support/core_ext/logger.rb index c622554860..24fe7294c9 100644 --- a/activesupport/lib/active_support/core_ext/logger.rb +++ b/activesupport/lib/active_support/core_ext/logger.rb @@ -30,6 +30,8 @@ require 'logger' # # Note: This logger is deprecated in favor of ActiveSupport::BufferedLogger class Logger + ## + # :singleton-method: # Set to false to disable the silencer cattr_accessor :silencer self.silencer = true -- cgit v1.2.3 From 64e8f14058949b0b1967a4d1282c6fc154e890e9 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Tue, 18 Nov 2008 11:05:04 -0600 Subject: Configuration options for Active Model, Active Resource, Active Support --- railties/doc/guides/html/configuring.html | 181 ++++++++++++----------------- railties/doc/guides/source/configuring.txt | 174 +++++++-------------------- 2 files changed, 114 insertions(+), 241 deletions(-) diff --git a/railties/doc/guides/html/configuring.html b/railties/doc/guides/html/configuring.html index 55f5d48554..adc827c89a 100644 --- a/railties/doc/guides/html/configuring.html +++ b/railties/doc/guides/html/configuring.html @@ -223,6 +223,8 @@ ul#navMain {
  • Configuring Active Support
  • +
  • Configuring Active Model
  • +
  • @@ -332,11 +334,78 @@ after-initializer

    default_form_builder tells Rails which form builder to use by default. The default is ActionView::Helpers::FormBuilder.

    The ERB template handler supplies one additional option:

    -

    ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -.

    +

    ActionView::TemplateHandlers::ERB.erb_trim_mode gives the trim mode to be used by ERB. It defaults to -. See the ERB documentation for more information.

    4.4. Configuring Action Mailer

    There are a number of settings available on ActionMailer::Base:

    +

    template_root gives the root folder for Action Mailer templates.

    +

    logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging.

    +

    smtp_settings allows detailed configuration for the :smtp delivery method. It accepts a hash of options, which can include any of these options:

    +
      +
    • +

      +<tt>:address</tt> - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +

      +
    • +
    • +

      +<tt>:port</tt> - On the off chance that your mail server doesn't run on port 25, you can change it. +

      +
    • +
    • +

      +<tt>:domain</tt> - If you need to specify a HELO domain, you can do it here. +

      +
    • +
    • +

      +<tt>:user_name</tt> - If your mail server requires authentication, set the username in this setting. +

      +
    • +
    • +

      +<tt>:password</tt> - If your mail server requires authentication, set the password in this setting. +

      +
    • +
    • +

      +<tt>:authentication</tt> - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>. +

      +
    • +
    +

    sendmail_settings allows detailed configuration for the sendmail delivery method. It accepts a hash of options, which can include any of these options:

    +
      +
    • +

      +<tt>:location</tt> - The location of the sendmail executable. Defaults to <tt>/usr/sbin/sendmail</tt>. +

      +
    • +
    • +

      +<tt>:arguments</tt> - The command line arguments. Defaults to <tt>-i -t</tt>. +

      +
    • +
    +

    raise_delivery_errors specifies whether to raise an error if email delivery cannot be completed. It defaults to true.

    +

    delivery_method defines the delivery method. The allowed values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.

    +

    perform_deliveries specifies whether mail will actually be delivered. By default this is true; it can be convenient to set it to false for testing.

    +

    default_charset tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to utf-8.

    +

    default_content_type specifies the default content type used for the main part of the message. It defaults to "text/plain"

    +

    default_mime_version is the default MIME version for the message. It defaults to 1.0.

    +

    default_implicit_parts_order - When a message is built implicitly (i.e. multiple parts are assembled from templates +which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +<tt>["text/html", "text/enriched", "text/plain"]</tt>. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message.

    4.5. Configuring Active Resource

    +

    There is a single configuration setting available on ActiveResource::Base:

    +

    logger accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging.

    4.6. Configuring Active Support

    +

    There are a few configuration options available in Active Support:

    +

    ActiveSupport::BufferedLogger.silencer is set to false to disable the ability to silence logging in a block. The default is true.

    +

    ActiveSupport::Cache::Store.logger specifies the logger to use within cache store operations.

    +

    ActiveSupport::Logger.silencer is set to false to disable the ability to silence logging in a block. The default is true.

    +

    4.7. Configuring Active Model

    +

    Active Model currently has a single configuration setting:

    +

    +ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages.

    5. Using Initializers

    @@ -360,114 +429,6 @@ after-initializer

    November 5, 2008: Rough outline by Mike Gunderloy

    -
  • - -

    actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables

    -

    actionmailer/Rakefile -36: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root

    -

    actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension

    -

    actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching

    -

    actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path

    -

    actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types

    -

    actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates

    -

    actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class

    -

    actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer ⇒ false

    -

    actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses

    -

    actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc

    -

    actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder

    -

    actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode

    -

    actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected

    -

    actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log

    -

    actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones

    -

    activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages

    -

    activemodel/Rakefile -19: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    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

    -

    activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger

    -

    activeresource/Rakefile -43: rdoc.options << —line-numbers << —inline-source << -A cattr_accessor=object

    -

    activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer

    -

    activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger

    -

    activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms)

    -

    activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer

    -

    activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer ⇒ false

    -

    activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer ⇒ false

    -

    railties/doc/guides/html/creating_plugins.html -786: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field -860: cattr_accessor <span style="color: #990000">:</span>yaffle_text_field<span style="color: #990000">,</span> <span style="color: #990000">:</span>yaffle_date_field

    -

    railties/lib/rails_generator/base.rb -93: cattr_accessor :logger

    -

    railties/Rakefile -265: rdoc.options << —line-numbers << —inline-source << —accessor << cattr_accessor=object

    -

    railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request

    -

    Rakefile -32: rdoc.options << -A cattr_accessor=object

    1. @@ -475,6 +436,8 @@ need to look for def self. ?

    + + diff --git a/railties/doc/guides/source/configuring.txt b/railties/doc/guides/source/configuring.txt index 1fb73abbb8..945e48cd45 100644 --- a/railties/doc/guides/source/configuring.txt +++ b/railties/doc/guides/source/configuring.txt @@ -113,172 +113,82 @@ There are only a few configuration options for Action View, starting with four o The ERB template handler supplies one additional option: -+ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. ++ActionView::TemplateHandlers::ERB.erb_trim_mode+ gives the trim mode to be used by ERB. It defaults to +'-'+. See the link:http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/[ERB documentation] for more information. === Configuring Action Mailer There are a number of settings available on +ActionMailer::Base+: ++template_root+ gives the root folder for Action Mailer templates. ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Action Mailer. Set to nil to disable logging. -=== Configuring Active Resource - -=== Configuring Active Support - -== Using Initializers - organization, controlling load order - -== Using an After-Initializer ++smtp_settings+ allows detailed configuration for the +:smtp+ delivery method. It accepts a hash of options, which can include any of these options: -== Rails Environment Settings - -ENV - -== Changelog == - -http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] +* :address - Allows you to use a remote mail server. Just change it from its default "localhost" setting. +* :port - On the off chance that your mail server doesn't run on port 25, you can change it. +* :domain - If you need to specify a HELO domain, you can do it here. +* :user_name - If your mail server requires authentication, set the username in this setting. +* :password - If your mail server requires authentication, set the password in this setting. +* :authentication - If your mail server requires authentication, you need to specify the authentication type here. This is a symbol and one of :plain, :login, :cram_md5. -* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] ++sendmail_settings+ allows detailed configuration for the +sendmail+ delivery method. It accepts a hash of options, which can include any of these options: +* :location - The location of the sendmail executable. Defaults to /usr/sbin/sendmail. +* :arguments - The command line arguments. Defaults to -i -t. -actionmailer/lib/action_mailer/base.rb -257: cattr_accessor :logger -267: cattr_accessor :smtp_settings -273: cattr_accessor :sendmail_settings -276: cattr_accessor :raise_delivery_errors -282: cattr_accessor :perform_deliveries -285: cattr_accessor :deliveries -288: cattr_accessor :default_charset -291: cattr_accessor :default_content_type -294: cattr_accessor :default_mime_version -297: cattr_accessor :default_implicit_parts_order -299: cattr_reader :protected_instance_variables - -actionmailer/Rakefile -36: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -actionpack/lib/action_controller/base.rb -263: cattr_reader :protected_instance_variables -273: cattr_accessor :asset_host -279: cattr_accessor :consider_all_requests_local -285: cattr_accessor :allow_concurrency -317: cattr_accessor :param_parsers -321: cattr_accessor :default_charset -325: cattr_accessor :logger -329: cattr_accessor :resource_action_separator -333: cattr_accessor :resources_path_names -337: cattr_accessor :request_forgery_protection_token -341: cattr_accessor :optimise_named_routes -351: cattr_accessor :use_accept_header -361: cattr_accessor :relative_url_root ++raise_delivery_errors+ specifies whether to raise an error if email delivery cannot be completed. It defaults to +true+. -actionpack/lib/action_controller/caching/pages.rb -55: cattr_accessor :page_cache_directory -58: cattr_accessor :page_cache_extension ++delivery_method+ defines the delivery method. The allowed values are :smtp (default), :sendmail, and :test. -actionpack/lib/action_controller/caching.rb -37: cattr_reader :cache_store -48: cattr_accessor :perform_caching ++perform_deliveries+ specifies whether mail will actually be delivered. By default this is +true+; it can be convenient to set it to +false+ for testing. -actionpack/lib/action_controller/dispatcher.rb -98: cattr_accessor :error_file_path ++default_charset+ tells Action Mailer which character set to use for the body and for encoding the subject. It defaults to +utf-8+. -actionpack/lib/action_controller/mime_type.rb -24: cattr_reader :html_types, :unverifiable_types ++default_content_type+ specifies the default content type used for the main part of the message. It defaults to "text/plain" -actionpack/lib/action_controller/rescue.rb -36: base.cattr_accessor :rescue_responses -40: base.cattr_accessor :rescue_templates ++default_mime_version+ is the default MIME version for the message. It defaults to +1.0+. -actionpack/lib/action_controller/session/active_record_store.rb -60: cattr_accessor :data_column_name -170: cattr_accessor :connection -173: cattr_accessor :table_name -177: cattr_accessor :session_id_column -181: cattr_accessor :data_column -282: cattr_accessor :session_class ++default_implicit_parts_order+ - When a message is built implicitly (i.e. multiple parts are assembled from templates +which specify the content type in their filenames) this variable controls how the parts are ordered. Defaults to +["text/html", "text/enriched", "text/plain"]. Items that appear first in the array have higher priority in the mail client +and appear last in the mime encoded message. -actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb -44: cattr_accessor :included_tags, :instance_writer => false - -actionpack/lib/action_view/base.rb -189: cattr_accessor :debug_rjs -193: cattr_accessor :warn_cache_misses - -actionpack/lib/action_view/helpers/active_record_helper.rb -7: cattr_accessor :field_error_proc - -actionpack/lib/action_view/helpers/form_helper.rb -805: cattr_accessor :default_form_builder - -actionpack/lib/action_view/template_handlers/erb.rb -47: cattr_accessor :erb_trim_mode - -actionpack/test/active_record_unit.rb -5: cattr_accessor :able_to_connect -6: cattr_accessor :connected +=== Configuring Active Resource -actionpack/test/controller/filters_test.rb -286: cattr_accessor :execution_log +There is a single configuration setting available on +ActiveResource::Base+: -actionpack/test/template/form_options_helper_test.rb -3:TZInfo::Timezone.cattr_reader :loaded_zones ++logger+ accepts a logger conforming to the interface of Log4r or the default Ruby 1.8+ Logger class, which is then used to log information from Active Resource. Set to nil to disable logging. -activemodel/lib/active_model/errors.rb -28: cattr_accessor :default_error_messages +=== Configuring Active Support -activemodel/Rakefile -19: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' +There are a few configuration options available in Active Support: -activerecord/lib/active_record/attribute_methods.rb -9: base.cattr_accessor :attribute_types_cached_by_default, :instance_writer => false -11: base.cattr_accessor :time_zone_aware_attributes, :instance_writer => false ++ActiveSupport::BufferedLogger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. ++ActiveSupport::Cache::Store.logger+ specifies the logger to use within cache store operations. -activeresource/lib/active_resource/base.rb -206: cattr_accessor :logger ++ActiveSupport::Logger.silencer+ is set to +false+ to disable the ability to silence logging in a block. The default is +true+. -activeresource/Rakefile -43: rdoc.options << '--line-numbers' << '--inline-source' << '-A cattr_accessor=object' - -activesupport/lib/active_support/buffered_logger.rb -17: cattr_accessor :silencer - -activesupport/lib/active_support/cache.rb -81: cattr_accessor :logger +=== Configuring Active Model -activesupport/lib/active_support/core_ext/class/attribute_accessors.rb -5:# cattr_accessor :hair_colors -10: def cattr_reader(*syms) -29: def cattr_writer(*syms) -50: def cattr_accessor(*syms) -51: cattr_reader(*syms) -52: cattr_writer(*syms) +Active Model currently has a single configuration setting: -activesupport/lib/active_support/core_ext/logger.rb -34: cattr_accessor :silencer ++ActiveModel::Errors.default_error_messages is an array containing all of the validation error messages. -activesupport/test/core_ext/class/attribute_accessor_test.rb -6: cattr_accessor :foo -7: cattr_accessor :bar, :instance_writer => false +== Using Initializers + organization, controlling load order -activesupport/test/core_ext/module/synchronization_test.rb -6: @target.cattr_accessor :mutex, :instance_writer => false +== Using an After-Initializer -railties/doc/guides/html/creating_plugins.html -786: cattr_accessor :yaffle_text_field, :yaffle_date_field -860: cattr_accessor :yaffle_text_field, :yaffle_date_field +== Rails Environment Settings -railties/lib/rails_generator/base.rb -93: cattr_accessor :logger +ENV -railties/Rakefile -265: rdoc.options << '--line-numbers' << '--inline-source' << '--accessor' << 'cattr_accessor=object' +== Changelog == -railties/test/rails_info_controller_test.rb -12: cattr_accessor :local_request +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/28[Lighthouse ticket] -Rakefile -32: rdoc.options << '-A cattr_accessor=object' +* November 5, 2008: Rough outline by link:../authors.html#mgunderloy[Mike Gunderloy] need to look for def self. ??? -- cgit v1.2.3 From b60971ad6b19a3cd72a972b459e94059d24c0848 Mon Sep 17 00:00:00 2001 From: CassioMarques Date: Tue, 18 Nov 2008 19:14:51 -0200 Subject: Added note about update_attribute not triggering validation --- .../doc/guides/html/activerecord_validations_callbacks.html | 10 +++++++++- .../doc/guides/source/activerecord_validations_callbacks.txt | 5 ++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index b6cb481eab..097ef706ca 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -362,6 +362,14 @@ http://www.gnu.org/software/src-highlite --> => false

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    +
    + + + +
    +Caution +There are four methods that when called will trigger validation: save, save!, update_attributes and update_attributes!. There is one method left, which is update_attribute. This method will update the value of an attribute without triggering any validation, so be careful when using update_attribute, since it can let you save your objects in an invalid state.
    +

    2.2. The meaning of valid

    For verifying if an object is valid, Active Record uses the valid? method, which basically looks inside the object to see if it has any validation errors. These errors live in a collection that can be accessed through the errors instance method. The proccess is really simple: If the errors method returns an empty collection, the object is valid and can be saved. Each time a validation fails, an error message is added to the errors collection.

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

    +

    If your validation rules are too complicated and you want to break them in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.

    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  protected
    +  def before_validation
    +    if self.login.nil?
    +      self.login = email unless email.blank?
    +    end
    +  end
    +end
    +
    +

    8.3. Registering callbacks by using macro-style class methods

    +

    The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that:

    +
    +
    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  before_validation :ensure_login_has_a_value
    +
    +  protected
    +  def ensure_login_has_a_value
    +    if self.login.nil?
    +      self.login = email unless email.blank?
    +    end
    +  end
    +end
    +
    +

    The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line.

    +
    +
    +
    class User < ActiveRecord::Base
    +  validates_presence_of :login, :email
    +
    +  before_create {|user| user.name = user.login.capitalize if user.name.blank?}
    +end
    +
    +

    In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are:

    +
      +
    • +

      +You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +

      +
    • +
    • +

      +Readability, since your callback declarations will live at the beggining of your models' files. +

      +
    • +
    +
    + + + +
    +Caution +Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details.
    +
    + +

    9. Callbacks that get triggered when an objects is saved

    +
    +
      +
    • +

      +before_validation will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. +

      +
    • +
    +
    +

    10. Changelog

    diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index cbd914405e..a369a66bd3 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -477,6 +477,79 @@ person.errors.clear person.errors # => nil ------------------------------------------------------------------ +== Callbacks + +Callbacks are methods that get called at certain moments of an object's lifecycle. With callbacks it's possible to write code that will run whenever an Active Record object is created, saved, updated, deleted or loaded from the database. + +=== Callbacks registration + +In order to use the available callbacks, you need to registrate them. There are two ways of doing that. + +=== Registering callbacks by overriding the callback methods + +You can specify the callback method direcly, by overriding it. Let's see how it works using the +before_validation+ callback, which will surprisingly run right before any validation is done. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + protected + def before_validation + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +=== Registering callbacks by using macro-style class methods + +The other way you can register a callback method is by implementing it as an ordinary method, and then using a macro-style class method to register it as a callback. The last example could be written like that: + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_validation :ensure_login_has_a_value + + protected + def ensure_login_has_a_value + if self.login.nil? + self.login = email unless email.blank? + end + end +end +------------------------------------------------------------------ + +The macro-style class methods can also receive a block. Rails best practices say that you should only use this style of registration if the code inside your block is so short that it fits in just one line. + +[source, ruby] +------------------------------------------------------------------ +class User < ActiveRecord::Base + validates_presence_of :login, :email + + before_create {|user| user.name = user.login.capitalize if user.name.blank?} +end +------------------------------------------------------------------ + +In Rails, the preferred way of registering callbacks is by using macro-style class methods. The main advantages of using macro-style class methods are: + +* You can add more than one method for each type of callback. Those methods will be queued for execution at the same order they were registered. +* Readability, since your callback declarations will live at the beggining of your models' files. + +CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details. + +== Callbacks that get triggered when an objects is saved + +* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. + + + + + + == Changelog -- cgit v1.2.3 From 2b94b3437e819fbaffb7d5b7cd158efdcf903566 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 19 Nov 2008 22:46:37 +1030 Subject: Fixed all points in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11 --- railties/doc/guides/source/finders.txt | 48 ++++++++++++++++++---------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index ad41ef3bd5..6f1329d474 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -13,6 +13,8 @@ This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as If you're used to using raw SQL to find database records, you'll find that there are generally better ways to carry out the same operations in Rails. Active Record insulates you from the need to use SQL in most cases. +The SQL in your log may have some quoting, and that quoting depends on the backend (MySQL, for example, puts backticks around field and table names). Attempting to copy the raw SQL contained within this guide may not work in your database system. Please consult the database systems manual before attempting to execute any SQL. + == The Sample Models This guide demonstrates finding using the following models: @@ -52,16 +54,16 @@ Active Record will perform queries on the database for you and is compatible wit [source, sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+id+ = 1) +SELECT * FROM clients WHERE (clients.id = 1) ------------------------------------------------------- -NOTE: Because this is a standard table created from a migration in Rail, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column. +NOTE: Because this is a standard table created from a migration in Rails, the primary key is defaulted to 'id'. If you have specified a different primary key in your migrations, this is what Rails will find on when you call the find method, not the id column. If you wanted to find clients with id 1 or 2, you call +Client.find([1,2])+ or +Client.find(1,2)+ and then this will be executed as: [source, sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2)) +SELECT * FROM clients WHERE (clients.id IN (1,2)) ------------------------------------------------------- ------------------------------------------------------- @@ -76,7 +78,7 @@ Note that if you pass in a list of numbers that the result will be returned as a NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception. -If you wanted to find the first client you would simply type +Client.first+ and that would find the first client created in your clients table: +If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client created in your clients table: ------------------------------------------------------- >> Client.first @@ -84,7 +86,7 @@ If you wanted to find the first client you would simply type +Client.first+ and created_at: "2008-09-28 15:38:50", updated_at: "2008-09-28 15:38:50"> ------------------------------------------------------- -If you were running script/server you might see the following output: +If you were reading your log file (the default is log/development.log) you may see something like this: [source,sql] ------------------------------------------------------- @@ -93,10 +95,10 @@ SELECT * FROM clients LIMIT 1 Indicating the query that Rails has performed on your database. -To find the last client you would simply type +Client.find(:last)+ and that would find the last client created in your clients table: +To find the last Client object you would simply type +Client.find(:last)+ and that would find the last client created in your clients table: ------------------------------------------------------- ->> Client.find(:last) +>> Client.last => # "Michael", locked: false, orders_count: 3, created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"> ------------------------------------------------------- @@ -106,7 +108,7 @@ To find the last client you would simply type +Client.find(:last)+ and that woul SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 ------------------------------------------------------- -To find all the clients you would simply type +Client.all+ and that would find all the clients in your clients table: +To find all the Client objects you would simply type +Client.all+ and that would find all the clients in your clients table: ------------------------------------------------------- >> Client.all @@ -116,9 +118,9 @@ To find all the clients you would simply type +Client.all+ and that would find a created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40">] ------------------------------------------------------- -As alternatives to calling +Client.first+, +Client.last+, and +Client.all+, you can use the class methods +Client.first+, +Client.last+, and +Client.all+ instead. +Client.first+, +Client.last+ and +Client.all+ just call their longer counterparts: +Client.find(:first)+, +Client.find(:last)+ and +Client.find(:all)+ respectively. +You may see in Rails code that there are calls to methods such as +Client.find(:all)+, +Client.find(:first)+ and +Client.find(:last)+. These methods are just alternatives to +Client.all+, +Client.first+ and +Client.last+ respectively. -Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to find will do also. +Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.find(:last)+ will both return a single object, where as +Client.all+/+Client.find(:all)+ will return an array of Client objects, just as passing in an array of ids to +find+ will do also. == Conditions @@ -132,19 +134,20 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t === Array Conditions === -Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in params orders and the second will be replaced with true and this will find the first record in the table that has '2' as its value for the orders_count field and 'false' for its locked field. +Now what if that number could vary, say as a parameter from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like +Client.first(:conditions => ["orders_count = ?", params[:orders]])+. Active Record will go through the first element in the conditions value and any additional elements will replace the question marks (?) in the first element. If you want to specify two conditions, you can do it like +Client.first(:conditions => ["orders_count = ? AND locked = ?", params[:orders], false])+. In this example, the first question mark will be replaced with the value in +params[:orders]+ and the second will be replaced with +false+ and this will find the first record in the table that has '2' as its value for the +orders_count+ field and +false+ for its locked field. The reason for doing code like: [source, ruby] ------------------------------------------------------- -+Client.first(:conditions => ["orders_count = ?", params[:orders]])+ +Client.first(:conditions => ["orders_count = ?", params[:orders]]) ------------------------------------------------------- instead of: +[source, ruby] ------------------------------------------------------- -+Client.first(:conditions => "orders_count = #{params[:orders]}")+ +Client.first(:conditions => "orders_count = #{params[:orders]}") ------------------------------------------------------- is because of parameter safety. Putting the variable directly into the conditions string will pass the variable to the database *as-is*. This means that it will be an unescaped variable directly from a user who may have malicious intent. If you do this, you put your entire database at risk because once a user finds out he or she can exploit your database they can do just about anything to it. Never ever put your parameters directly inside the conditions string. @@ -163,7 +166,7 @@ This would generate the proper query which is great for small ranges but not so [source, sql] ------------------------------------------------------- -SELECT * FROM +users+ WHERE (created_at IN +SELECT * FROM users WHERE (created_at IN ('2007-12-31','2008-01-01','2008-01-02','2008-01-03','2008-01-04','2008-01-05', '2008-01-06','2008-01-07','2008-01-08','2008-01-09','2008-01-10','2008-01-11', '2008-01-12','2008-01-13','2008-01-14','2008-01-15','2008-01-16','2008-01-17', @@ -183,7 +186,7 @@ Client.all(:conditions => ["created_at IN (?)", [source, sql] ------------------------------------------------------- -SELECT * FROM +users+ WHERE (created_at IN +SELECT * FROM users WHERE (created_at IN ('2007-12-01 00:00:00', '2007-12-01 00:00:01' ... '2007-12-01 23:59:59', '2007-12-02 00:00:00')) ------------------------------------------------------- @@ -214,7 +217,7 @@ Client.all(:conditions => Just like in Ruby. -=== Hash Conditions === +=== Placeholder Conditions === Similar to the array style of params you can also specify keys in your conditions: @@ -277,7 +280,7 @@ The SQL that would be executed would be something like this: [source, sql] ------------------------------------------------------- -SELECT * FROM +orders+ GROUP BY date(created_at) +SELECT * FROM orders GROUP BY date(created_at) ------------------------------------------------------- == Read Only @@ -363,9 +366,9 @@ There's another set of dynamic finders that let you find or create/initialize ob [source,sql] ------------------------------------------------------- -SELECT * FROM +clients+ WHERE (+clients+.+name+ = 'Ryan') LIMIT 1 +SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1 BEGIN -INSERT INTO +clients+ (+name+, +updated_at+, +created_at+, +orders_count+, +locked+) +INSERT INTO clients (name, updated_at, created_at, orders_count, locked) VALUES('Ryan', '2008-09-28 15:39:12', '2008-09-28 15:39:12', '0', '0') COMMIT ------------------------------------------------------- @@ -571,7 +574,7 @@ Which will execute: [source, sql] ------------------------------------------------------- -SELECT count(*) AS count_all FROM +clients+ WHERE (first_name = 1) +SELECT count(*) AS count_all FROM clients WHERE (first_name = 1) ------------------------------------------------------- You can also use +include+ or +joins+ for this to do something a little more complex: @@ -585,8 +588,8 @@ Which will execute: [source, sql] ------------------------------------------------------- -SELECT count(DISTINCT +clients+.id) AS count_all FROM +clients+ - LEFT OUTER JOIN +orders+ ON orders.client_id = client.id WHERE +SELECT count(DISTINCT clients.id) AS count_all FROM clients + LEFT OUTER JOIN orders ON orders.client_id = client.id WHERE (clients.first_name = 'name' AND orders.status = 'received') ------------------------------------------------------- @@ -655,6 +658,7 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] +* Wednesday 16 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. * October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg * October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg -- cgit v1.2.3 From 3e762e8a97d3dbb60e12f369d70f46e2b10e01a0 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Fri, 21 Nov 2008 11:27:54 +1030 Subject: Updated finders guide based on: http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13 --- railties/doc/guides/source/finders.txt | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 6f1329d474..53de3093e1 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -78,7 +78,7 @@ Note that if you pass in a list of numbers that the result will be returned as a NOTE: If +find(id)+ or +find([id1, id2])+ fails to find any records, it will raise a +RecordNotFound+ exception. -If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client created in your clients table: +If you wanted to find the first Client object you would simply type +Client.first+ and that would find the first client in your clients table: ------------------------------------------------------- >> Client.first @@ -95,7 +95,7 @@ SELECT * FROM clients LIMIT 1 Indicating the query that Rails has performed on your database. -To find the last Client object you would simply type +Client.find(:last)+ and that would find the last client created in your clients table: +To find the last Client object you would simply type +Client.last+ and that would find the last client created in your clients table: ------------------------------------------------------- >> Client.last @@ -103,6 +103,15 @@ To find the last Client object you would simply type +Client.find(:last)+ and th created_at: "2008-09-28 13:12:40", updated_at: "2008-09-28 13:12:40"> ------------------------------------------------------- +If you were reading your log file (the default is log/development.log) you may see something like this: + +[source,sql] +------------------------------------------------------- +SELECT * FROM clients ORDER BY id DESC LIMIT 1 +------------------------------------------------------- + +NOTE: Please be aware that the syntax that Rails uses to find the first record in the table means that it may not be the actual first record. If you want the actual first record based on a field in your table (e.g. +created_at+) specify an order option in your find call. The last method call works differently: it finds the last record on your table based on the primary key column. + [source,sql] ------------------------------------------------------- SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1 @@ -658,7 +667,8 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] -* Wednesday 16 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] +* November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment] +* November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. * October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section by Ryan Bigg * October 27, 2008: Fixed up all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-6[this comment] with an exception of the final point by Ryan Bigg -- cgit v1.2.3 From 76018a16587611c64a852c4bb9662df56b5cd1f0 Mon Sep 17 00:00:00 2001 From: Mike Gunderloy Date: Fri, 21 Nov 2008 10:20:21 -0600 Subject: Final changes for 2.2 release notes --- railties/doc/guides/html/2_2_release_notes.html | 4 ++-- railties/doc/guides/source/2_2_release_notes.txt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index 1c44c1fcd9..778144b688 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -974,7 +974,7 @@ The addition of ActiveSupport::Rescuable allows any class to mix in the
  • -Array#second through Array#tenth as aliases for Array#[1] through Array#[9] +Array#second through Array#fifth as aliases for Array#[1] through Array#[4]

  • @@ -994,7 +994,7 @@ The addition of ActiveSupport::Rescuable allows any class to mix in the
  • -The included TzInfo library has been upgraded to version 0.3.11. +The included TzInfo library has been upgraded to version 0.3.12.

  • diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt index 59701ca24c..6aa9fa19ce 100644 --- a/railties/doc/guides/source/2_2_release_notes.txt +++ b/railties/doc/guides/source/2_2_release_notes.txt @@ -365,11 +365,11 @@ Lead Contributor: link:http://workingwithrails.com/person/5830-daniel-schierbeck * Extensive updates to +ActiveSupport::Multibyte+, including Ruby 1.9 compatibility fixes. * The addition of +ActiveSupport::Rescuable+ allows any class to mix in the +rescue_from+ syntax. * +past?+, +today?+ and +future?+ for +Date+ and +Time+ classes to facilitate date/time comparisons. -* +Array#second+ through +Array#tenth+ as aliases for +Array#[1]+ through +Array#[9]+ +* +Array#second+ through +Array#fifth+ as aliases for +Array#[1]+ through +Array#[4]+ * +Enumerable#many?+ to encapsulate +collection.size > 1+ * +Inflector#parameterize+ produces a URL-ready version of its input, for use in +to_param+. * +Time#advance+ recognizes fractional days and weeks, so you can do +1.7.weeks.ago+, +1.5.hours.since+, and so on. -* The included TzInfo library has been upgraded to version 0.3.11. +* The included TzInfo library has been upgraded to version 0.3.12. * +ActiveSuport::StringInquirer+ gives you a pretty way to test for equality in strings: +ActiveSupport::StringInquirer.new("abc").abc? => true+ == Railties -- cgit v1.2.3 From e04abd574120d80903e728913d37356468de6fbb Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 23 Nov 2008 21:09:58 +1030 Subject: Updated finders guide to include newcomers find_last_by and find_by_bang! --- railties/doc/guides/source/finders.txt | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 53de3093e1..55ba744591 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -369,7 +369,14 @@ Client.first(:include => "orders", :conditions => == Dynamic finders -For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. These finders are an excellent alternative to using the conditions option, mainly because it's shorter to type +find_by_name(params[:name])+ than it is to type +first(:conditions => ["name = ?", params[:name]])+. +For every field (also known as an attribute) you define in your table, Active Record provides a finder method. If you have a field called +name+ on your Client model for example, you get +find_by_name+ and +find_all_by_name+ for free from Active Record. If you have also have a +locked+ field on the client model, you also get +find_by_locked+ and +find_all_by_locked+. + +You can do +find_last_by_*+ methods too which will find the last record matching your parameter. + +You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!('Ryan')+ + +If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked('Ryan', true)+. + There's another set of dynamic finders that let you find or create/initialize objects if they aren't find. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name('Ryan')+: @@ -382,7 +389,7 @@ INSERT INTO clients (name, updated_at, created_at, orders_count, locked) COMMIT ------------------------------------------------------- -+find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will call +new+ with the parameters you passed in. For example: ++find_or_create+'s sibling, +find_or_initialize+, will find an object and if it does not exist will act similar to calling +new+ with the parameters you passed in. For example: [source, ruby] ------------------------------------------------------- @@ -391,6 +398,7 @@ client = Client.find_or_initialize_by_name('Ryan') will either assign an existing client object with the name 'Ryan' to the client local variable, or initialize new object similar to calling +Client.new(:name => 'Ryan')+. From here, you can modify other fields in client by calling the attribute setters on it: +client.locked = true+ and when you want to write it to the database just call +save+ on it. + == Finding By SQL If you'd like to use your own SQL to find records a table you can use +find_by_sql+. The +find_by_sql+ method will return an array of objects even if it only returns a single record in it's call to the database. For example you could run this query: -- cgit v1.2.3 From e95f5417e8c15dec4f51afeb69945fdc89f1f2e3 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Sun, 23 Nov 2008 22:28:05 +1030 Subject: Was very naughty and did not add changelog message to guide. --- railties/doc/guides/source/finders.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 55ba744591..5fc77a5415 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -675,6 +675,7 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] +* November 23 2008: Added documentation for +find_by_last+ and +find_by_bang!+ * November 21 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-13[this comment] and http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-14[this comment] * November 18 2008: Fixed all points specified in http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16-activerecord-finders#ticket-16-11[this comment] * November 8, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. -- cgit v1.2.3 From 490e02b17d26471e74bd9cbdc3ff368f88f6cccb Mon Sep 17 00:00:00 2001 From: CassioMarques Date: Sun, 23 Nov 2008 16:31:10 -0200 Subject: Added some more text on Active Record callbacks --- .../html/activerecord_validations_callbacks.html | 137 ++++++++++++++++++++- .../source/activerecord_validations_callbacks.txt | 48 +++++++- 2 files changed, 177 insertions(+), 8 deletions(-) diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 4b860eeec0..1656cea492 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -282,7 +282,26 @@ ul#navMain {
  • - Callbacks that get triggered when an objects is saved + Available callbacks + +
  • +
  • + Halting Execution +
  • +
  • + Callback classes and objects
  • Changelog @@ -376,7 +395,7 @@ http://www.gnu.org/software/src-highlite --> >> p.new_record? => false -

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save, update_attribute or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    +

    Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either save or update_attributes) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one.

    @@ -952,17 +971,125 @@ Readability, since your callback declarations will live at the beggining of your
    -

    9. Callbacks that get triggered when an objects is saved

    +

    9. Available callbacks

    +

    Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations.

    +

    9.1. Callbacks called both when creating or updating a record.

    +
      +
    • +

      +before_validation +

      +
    • +
    • +

      +after_validation +

      +
    • +
    • +

      +before_save +

      +
    • +
    • +

      +INSERT OR UPDATE OPERATION +

      +
    • +
    • +

      +after_save +

      +
    • +
    +

    9.2. Callbacks called only when creating a new record.

    +
      +
    • +

      +before_validation_on_create +

      +
    • +
    • +

      +after_validation_on_create +

      +
    • +
    • +

      +before_create +

      +
    • +
    • +

      +INSERT OPERATION +

      +
    • +
    • +

      +after_create +

      +
    • +
    +

    9.3. Callbacks called only when updating an existing record.

    • -before_validation will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. +before_validation_on_update +

      +
    • +
    • +

      +after_validation_on_update +

      +
    • +
    • +

      +before_update +

      +
    • +
    • +

      +UPDATE OPERATION +

      +
    • +
    • +

      +after_update +

      +
    • +
    +

    9.4. Callbacks called when removing a record from the database.

    +
      +
    • +

      +before_destroy +

      +
    • +
    • +

      +DELETE OPERATION +

      +
    • +
    • +

      +after_destroy

    +

    The before_destroy and after_destroy callbacks will only be called if you delete the model using either the destroy instance method or one of the destroy or destroy_all class methods of your Active Record class. If you use delete or delete_all no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database.

    +

    9.5. The after_initialize and after_find callbacks

    +

    The after_initialize callback will be called whenever an Active Record object is instantiated, either by direcly using new or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record initialize method.

    +

    The after_find callback will be called whenever Active Record loads a record from the database. When used together with after_initialize it will run first, since Active Record will first read the record from the database and them create the model object that will hold it.

    +

    The after_initialize and after_find callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register after_initialize or after_find using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since after_initialize and after_find will both be called for each record found in the database, significantly slowing down the queries.

    +
    +

    10. Halting Execution

    +
    +

    As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean false (not nil) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.

    +
    +

    11. Callback classes and objects

    +
    -

    10. Changelog

    +

    12. Changelog

    diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index a369a66bd3..02cdbcf146 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -47,7 +47,7 @@ We can see how it works by looking at the following script/console output: => false ------------------------------------------------------------------ -Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+, +update_attribute+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. +Saving new records means sending an SQL insert operation to the database, while saving existing records (by calling either +save+ or +update_attributes+) will result in a SQL update operation. Active Record will use this facts to perform validations upon your objects, avoiding then to be recorded to the database if their inner state is invalid in some way. You can specify validations that will be beformed every time a object is saved, just when you're creating a new record or when you're updating an existing one. CAUTION: There are four methods that when called will trigger validation: +save+, +save!+, +update_attributes+ and +update_attributes!+. There is one method left, which is +update_attribute+. This method will update the value of an attribute without triggering any validation, so be careful when using +update_attribute+, since it can let you save your objects in an invalid state. @@ -541,14 +541,56 @@ In Rails, the preferred way of registering callbacks is by using macro-style cla CAUTION: Remember to always declare the callback methods as being protected or private. These methods should never be public, otherwise it will be possible to call them from code outside the model, violating object encapsulation and exposing implementation details. -== Callbacks that get triggered when an objects is saved +== Available callbacks + +Here is a list with all the available Active Record callbacks, listed in the same order in which they will get called during the respective operations. -* +before_validation+ will be triggered before any validation upon your object is done. You can use this callback to change the object's state so it becames valid. +=== Callbacks called both when creating or updating a record. +* +before_validation+ +* +after_validation+ +* +before_save+ +* *INSERT OR UPDATE OPERATION* +* +after_save+ +=== Callbacks called only when creating a new record. +* +before_validation_on_create+ +* +after_validation_on_create+ +* +before_create+ +* *INSERT OPERATION* +* +after_create+ +=== Callbacks called only when updating an existing record. +* +before_validation_on_update+ +* +after_validation_on_update+ +* +before_update+ +* *UPDATE OPERATION* +* +after_update+ + +=== Callbacks called when removing a record from the database. + +* +before_destroy+ +* *DELETE OPERATION* +* +after_destroy+ + +The +before_destroy+ and +after_destroy+ callbacks will only be called if you delete the model using either the +destroy+ instance method or one of the +destroy+ or +destroy_all+ class methods of your Active Record class. If you use +delete+ or +delete_all+ no callback operations will run, since Active Record will not instantiate any objects, accessing the records to be deleted directly in the database. + +=== The +after_initialize+ and +after_find+ callbacks + +The +after_initialize+ callback will be called whenever an Active Record object is instantiated, either by direcly using +new+ or when a record is loaded from the database. It can be useful to avoid the need to directly override your Active Record +initialize+ method. + +The +after_find+ callback will be called whenever Active Record loads a record from the database. When used together with +after_initialize+ it will run first, since Active Record will first read the record from the database and them create the model object that will hold it. + +The +after_initialize+ and +after_find+ callbacks are a bit different from the others, since the only way to register those callbacks is by defining them as methods. If you try to register +after_initialize+ or +after_find+ using macro-style class methods, they will just be ignored. This behaviour is due to performance reasons, since +after_initialize+ and +after_find+ will both be called for each record found in the database, significantly slowing down the queries. + +== Halting Execution + +As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. + + +== Callback classes and objects -- cgit v1.2.3 From 5df4a6779715859b3a0626b52ddb2e0874f78547 Mon Sep 17 00:00:00 2001 From: Aditya Date: Sun, 23 Nov 2008 13:34:35 -0500 Subject: Fixed width font changes --- railties/doc/guides/source/caching_with_rails.txt | 34 +++++++++++------------ 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index e680b79d55..7a4074570e 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -10,8 +10,8 @@ need to return to those hungry web clients in the shortest time possible. This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins. -To get started make sure config.action_controller.perform_caching is set -to true for your environment. This flag is normally set in the +To get started make sure `config.action_controller.perform_caching` is set +to `true` for your environment. This flag is normally set in the corresponding config/environments/*.rb and caching is disabled by default there for development and test, and enabled for production. @@ -45,21 +45,21 @@ end ----------------------------------------------------- The first time anyone requests products/index, Rails will generate a file -called index.html and the webserver will then look for that file before it +called `index.html` and the webserver will then look for that file before it passes the next request for products/index to your Rails application. By default, the page cache directory is set to Rails.public_path (which is -usually set to RAILS_ROOT + "/public") and this can be configured by -changing the configuration setting ActionController::Base.page_cache_directory. Changing the -default from /public helps avoid naming conflicts, since you may want to -put other static html in /public, but changing this will require web -server reconfiguration to let the web server know where to serve the -cached files from. - -The Page Caching mechanism will automatically add a .html exxtension to +usually set to `RAILS_ROOT + "/public"`) and this can be configured by +changing the configuration setting `config.action_controller.page_cache_directory`. +Changing the default from /public helps avoid naming conflicts, since you may +want to put other static html in /public, but changing this will require web +server reconfiguration to let the web server know where to serve the cached +files from. + +The Page Caching mechanism will automatically add a `.html` exxtension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the -configuration setting ActionController::Base.page_cache_extension. +configuration setting `config.action_controller.page_cache_extension`. In order to expire this page when a new product is added we could extend our example controler like this: @@ -119,8 +119,8 @@ class ProductsController < ActionController end ----------------------------------------------------- -And you can also use :if (or :unless) to pass a Proc that specifies when the -action should be cached. Also, you can use :layout => false to cache without +And you can also use `:if` (or `:unless`) to pass a Proc that specifies when the +action should be cached. Also, you can use `:layout => false` to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2. @@ -164,7 +164,7 @@ could use this piece of code: The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you -want to cache multiple fragments per action, you should provide an action_suffix to the cache call: +want to cache multiple fragments per action, you should provide an `action_suffix` to the cache call: [source, ruby] ----------------------------------------------------- @@ -172,7 +172,7 @@ want to cache multiple fragments per action, you should provide an action_suffix All available products: ----------------------------------------------------- -and you can expire it using the expire_fragment method, like so: +and you can expire it using the `expire_fragment` method, like so: [source, ruby] ----------------------------------------------------- @@ -185,7 +185,7 @@ expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix = Cache sweeping is a mechanism which allows you to get around having a ton of expire_{page,action,fragment} calls in your code by moving all the work -required to expire cached content into a ActionController::Caching::Sweeper +required to expire cached content into a `ActionController::Caching::Sweeper` class that is an Observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object n an around or after filter. -- cgit v1.2.3 From 54f4be83035bba1e2f1ec44334efff7d7a6cb4fe Mon Sep 17 00:00:00 2001 From: Aditya Date: Sun, 23 Nov 2008 14:09:36 -0500 Subject: Add config.cache_store blurb and note about Rails using the bundled memcached-client gem --- railties/doc/guides/source/caching_with_rails.txt | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index 7a4074570e..e29156d4e7 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -340,8 +340,7 @@ ActionController::Base.cache_store = :drb_store, "druby://localhost:9192" ----------------------------------------------------- 4) MemCached store: Works like DRbStore, but uses Danga's MemCache instead. - Requires the ruby-memcache library: - gem install ruby-memcache. + Rails uses the bundled memcached-client gem by default. [source, ruby] ----------------------------------------------------- @@ -355,6 +354,10 @@ ActionController::Base.cache_store = :mem_cache_store, "localhost" ActionController::Base.cache_store = MyOwnStore.new("parameter") ----------------------------------------------------- ++Note: config.cache_store can be used in place of +ActionController::Base.cache_store in your Rails::Initializer.run block in +environment.rb+ + == Advanced Caching Along with the built-in mechanisms outlined above, a number of excellent -- cgit v1.2.3 From f3ac3fafbc6146337592c2dd4a37e5eb06912757 Mon Sep 17 00:00:00 2001 From: Aditya Date: Sun, 23 Nov 2008 14:32:42 -0500 Subject: Updated with Conditional GET section lifted from Ryan's posts on the topic --- railties/doc/guides/source/caching_with_rails.txt | 58 +++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index e29156d4e7..7cef6bf060 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -358,6 +358,64 @@ ActionController::Base.cache_store = MyOwnStore.new("parameter") ActionController::Base.cache_store in your Rails::Initializer.run block in environment.rb+ +== Conditional GET support + +Conditional GETs are a facility of the HTTP spec that provide a way for web +servers to tell browsers that the response to a GET request hasn’t changed +since the last request and can be safely pulled from the browser cache. + +They work by using the HTTP_IF_NONE_MATCH and HTTP_IF_MODIFIED_SINCE headers to +pass back and forth both a unique content identifier and the timestamp of when +the content was last changed. If the browser makes a request where the content +identifier (etag) or last modified since timestamp matches the server’s version +then the server only needs to send back an empty response with a not modified +status. + +It is the server’s (i.e. our) responsibility to look for a last modified +timestamp and the if-none-match header and determine whether or not to send +back the full response. With conditional-get support in rails this is a pretty +easy task: + +[source, ruby] +----------------------------------------------------- +class ProductsController < ApplicationController + + def show + @product = Product.find(params[:id]) + + # If the request is stale according to the given timestamp and etag value + # (i.e. it needs to be processed again) then execute this block + if stale?(:last_modified => @product.updated_at.utc, :etag => @product) + respond_to do |wants| + # ... normal response processing + end + end + + # If the request is fresh (i.e. it's not modified) then you don't need to do + # anything. The default render checks for this using the parameters + # used in the previous call to stale? and will automatically send a + # :not_modified. So that's it, you're done. +end +----------------------------------------------------- + +If you don’t have any special response processing and are using the default +rendering mechanism (i.e. you’re not using respond_to or calling render +yourself) then you’ve got an easy helper in fresh_when: + +[source, ruby] +----------------------------------------------------- +class ProductsController < ApplicationController + + # This will automatically send back a :not_modified if the request is fresh, + # and will render the default template (product.*) if it's stale. + + def show + @product = Product.find(params[:id]) + fresh_when :last_modified => @product.published_at.utc, :etag => @article + end +end +----------------------------------------------------- + == Advanced Caching Along with the built-in mechanisms outlined above, a number of excellent -- cgit v1.2.3 From d67adf1e33b5ef93c7d414f87bdd68787297dd2f Mon Sep 17 00:00:00 2001 From: Aditya Date: Sun, 23 Nov 2008 15:17:03 -0500 Subject: Update with globally keyed fragments --- railties/doc/guides/source/caching_with_rails.txt | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index 7cef6bf060..16dac19e08 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -176,7 +176,25 @@ and you can expire it using the `expire_fragment` method, like so: [source, ruby] ----------------------------------------------------- -expire_fragment(:controller => 'producst', :action => 'recent', :action_suffix => 'all_products) +expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products) +----------------------------------------------------- + +If you don't want the cache block to bind to the action that called it, You can +also use globally keyed fragments by calling the cache method with a key, like +so: + +[source, ruby] +----------------------------------------------------- +<% cache(:key => ['all_available_products', @latest_product.created_at].join(':')) do %> + All available products: +----------------------------------------------------- + +This fragment is then available to all actions in the ProductsController using +the key and can be expired the same way: + +[source, ruby] +----------------------------------------------------- +expire_fragment(:key => ['all_available_products', @latest_product.created_at].join(':')) ----------------------------------------------------- [More: more examples? description of fragment keys and expiration, etc? pagination?] -- cgit v1.2.3 From c98bcfa55c8e61a0a956ebd2cc15b9e5216aa685 Mon Sep 17 00:00:00 2001 From: Yaroslav Markin Date: Mon, 24 Nov 2008 12:28:29 +0300 Subject: I18n guide: changed to reflect new i18n locale naming, added a link to rails-i18n.org --- railties/doc/guides/source/i18n.txt | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/railties/doc/guides/source/i18n.txt b/railties/doc/guides/source/i18n.txt index c9867ba0ac..76f081e0bc 100644 --- a/railties/doc/guides/source/i18n.txt +++ b/railties/doc/guides/source/i18n.txt @@ -58,14 +58,14 @@ You can pick whatever directory and translation file naming scheme makes sense f I18n.load_path += Dir[ File.join(RAILS_ROOT, 'lib', 'locale', '*.{rb,yml}') ] # you can omit this if you're happy with English as a default locale -I18n.default_locale = :"pt-BR" +I18n.default_locale = :"pt" ------------------------------------------------------- I18n.load_path is just a Ruby Array of paths to your translation files. The backend will lazy-load these translations when a translation is looked up for the first time. This makes it possible to just swap the backend with something else even after translations have already been announced. === Set the locale in each request -By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en-US (American English). +By default the I18n library will use the I18n.default_locale for looking up translations (if you do not specify a locale for a lookup) and this will, by default, en (English). If you want to translate your Rails application to a single language other than English you can set I18n.default_locale to your locale. If you want to change the locale on a per-request basis though you can set it in a before_filter on the ApplicationController like this: @@ -137,7 +137,7 @@ So let's add the missing translations (i.e. do the "localization" part): [source, ruby] ------------------------------------------------------- -# lib/locale/en-US.yml +# lib/locale/en.yml en-US: hello_world: Hello World hello_flash: Hello Flash @@ -252,7 +252,7 @@ All options besides :default and :scope that are passed to #translate will be in [source, ruby] ------------------------------------------------------- -I18n.backend.store_translations 'en-US', :thanks => 'Thanks {{name}}!' +I18n.backend.store_translations 'en', :thanks => 'Thanks {{name}}!' I18n.translate :thanks, :name => 'Jeremy' # => 'Thanks Jeremy!' ------------------------------------------------------- @@ -294,7 +294,7 @@ If no locale is passed I18n.locale is used: [source, ruby] ------------------------------------------------------- -I18n.locale = :'de-DE' +I18n.locale = :'de' I18n.t :foo I18n.l Time.now ------------------------------------------------------- @@ -303,15 +303,15 @@ Explicitely passing a locale: [source, ruby] ------------------------------------------------------- -I18n.t :foo, :locale => :'de-DE' -I18n.l Time.now, :locale => :'de-DE' +I18n.t :foo, :locale => :'de' +I18n.l Time.now, :locale => :'de' ------------------------------------------------------- -I18n.locale defaults to I18n.default_locale which defaults to :'en-US'. The default locale can be set like this: +I18n.locale defaults to I18n.default_locale which defaults to :'en'. The default locale can be set like this: [source, ruby] ------------------------------------------------------- -I18n.default_locale = :'de-DE' +I18n.default_locale = :'de' ------------------------------------------------------- == How to store your custom translations @@ -346,7 +346,7 @@ Here is a "real" example from the ActiveSupport en-US translations YAML file: [source, ruby] ------------------------------------------------------- -"en-US": +"en": date: formats: default: "%Y-%m-%d" @@ -370,7 +370,7 @@ You can use the methods Model.human_name and Model.human_attribute_name(attribut For example when you add the following translations: -en-US: +en: activerecord: models: user: Dude @@ -479,7 +479,7 @@ Rails ships with the following translations: [source, ruby] ------------------------------------------------------- -"en-US": +"en": activerecord: errors: template: @@ -526,6 +526,7 @@ TODO == Resources +* http://rails-i18n.org == Footnotes -- cgit v1.2.3 From 010cce6ad1d134786eaa3f814319ebbe2e63123b Mon Sep 17 00:00:00 2001 From: Yaroslav Markin Date: Tue, 25 Nov 2008 12:26:46 +0300 Subject: Fix an example of using Inflector's #parameterize. --- activesupport/lib/active_support/inflector.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/inflector.rb b/activesupport/lib/active_support/inflector.rb index ba52e41c08..5cb665ef75 100644 --- a/activesupport/lib/active_support/inflector.rb +++ b/activesupport/lib/active_support/inflector.rb @@ -256,7 +256,7 @@ module ActiveSupport # @person = Person.find(1) # # => # # - # <%= link_to(@person.name, person_path %> + # <%= link_to(@person.name, person_path(@person)) %> # # => Donald E. Knuth def parameterize(string, sep = '-') re_sep = Regexp.escape(sep) -- cgit v1.2.3 From 1f31ba7163db7ff1d6d2e55fa374c87c6d879383 Mon Sep 17 00:00:00 2001 From: Daniel Schierbeck Date: Tue, 25 Nov 2008 20:48:29 +0100 Subject: Made documentation of validates_presence_of use monospaced fonts correctly. --- activerecord/lib/active_record/validations.rb | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 9220eae4d1..dae00aa7db 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -494,18 +494,20 @@ module ActiveRecord # The first_name attribute must be in the object and it cannot be blank. # # If you want to validate the presence of a boolean field (where the real values are true and false), - # you will want to use validates_inclusion_of :field_name, :in => [true, false] - # This is due to the way Object#blank? handles boolean values. false.blank? # => true + # you will want to use validates_inclusion_of :field_name, :in => [true, false]. + # + # This is due to the way Object#blank? handles boolean values: false.blank? # => true. # # Configuration options: # * message - A custom error message (default is: "can't be blank"). - # * on - Specifies when this validation is active (default is :save, other options :create, :update). + # * on - Specifies when this validation is active (default is :save, other options :create, + # :update). # * if - Specifies a method, proc or string to call to determine if the validation should - # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). + # The method, proc or string should return or evaluate to a true or false value. # * unless - Specifies a method, proc or string to call to determine if the validation should - # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The - # method, proc or string should return or evaluate to a true or false value. + # not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). + # The method, proc or string should return or evaluate to a true or false value. # def validates_presence_of(*attr_names) configuration = { :on => :save } -- cgit v1.2.3 From 55d70f3a9848f5c3cafe99f9d3553418e4b6045f Mon Sep 17 00:00:00 2001 From: CassioMarques Date: Tue, 25 Nov 2008 20:36:29 -0200 Subject: Added some text about callbacks classes --- .../html/activerecord_validations_callbacks.html | 50 +++++++++++++++++++++- .../source/activerecord_validations_callbacks.txt | 43 ++++++++++++++++++- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index 1656cea492..097ad76d1e 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -301,7 +301,7 @@ ul#navMain { Halting Execution
  • - Callback classes and objects + Callback classes
  • Changelog @@ -1086,8 +1086,54 @@ Readability, since your callback declarations will live at the beggining of your

    As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean false (not nil) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on.

    -

    11. Callback classes and objects

    +

    11. Callback classes

    +

    Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them.

    +

    Here's an example where we create a class with a after_destroy callback for a PictureFile model.

    +
    +
    +
    class PictureFileCallbacks
    +  def after_destroy(picture_file)
    +    File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
    +  end
    +end
    +
    +

    When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way:

    +
    +
    +
    class PictureFile < ActiveRecord::Base
    +  after_destroy PictureFileCallbacks.new
    +end
    +
    +

    Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method.

    +
    +
    +
    class PictureFileCallbacks
    +  def self.after_destroy(picture_file)
    +    File.delete(picture_file.filepath) if File.exists?(picture_file.filepath)
    +  end
    +end
    +
    +

    If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object.

    +
    +
    +
    class PictureFile < ActiveRecord::Base
    +  after_destroy PictureFileCallbacks
    +end
    +
    +

    You can declare as many callbacks as you want inside your callback classes.

    12. Changelog

    diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index 02cdbcf146..3db98027d2 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -589,10 +589,51 @@ The +after_initialize+ and +after_find+ callbacks are a bit different from the o As you start registering new callbacks for your models, they will be queued for execution. This queue will include all your model's validations, the registered callbacks and the database operation to be executed. However, if at any moment one of the callback methods returns a boolean +false+ (not +nil+) value, this execution chain will be halted and the desired operation will not complete: your model will not get persisted in the database, or your records will not get deleted and so on. +== Callback classes -== Callback classes and objects +Sometimes the callback methods that you'll write will be useful enough to be reused at other models. Active Record makes it possible to create classes that encapsulate the callback methods, so it becomes very easy to reuse them. +Here's an example where we create a class with a after_destroy callback for a PictureFile model. +[source, ruby] +------------------------------------------------------------------ +class PictureFileCallbacks + def after_destroy(picture_file) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) + end +end +------------------------------------------------------------------ + +When declared inside a class the callback method will receive the model object as a parameter. We can now use it this way: + +[source, ruby] +------------------------------------------------------------------ +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks.new +end +------------------------------------------------------------------ + +Note that we needed to instantiate a new PictureFileCallbacks object, since we declared our callback as an instance method. Sometimes it will make more sense to have it as a class method. + +[source, ruby] +------------------------------------------------------------------ +class PictureFileCallbacks + def self.after_destroy(picture_file) + File.delete(picture_file.filepath) if File.exists?(picture_file.filepath) + end +end +------------------------------------------------------------------ + +If the callback method is declared this way, it won't be necessary to instantiate a PictureFileCallbacks object. + +[source, ruby] +------------------------------------------------------------------ +class PictureFile < ActiveRecord::Base + after_destroy PictureFileCallbacks +end +------------------------------------------------------------------ + +You can declare as many callbacks as you want inside your callback classes. == Changelog -- cgit v1.2.3 From d18bfa2a4165297dbf5e6b1fff1731fefa9dd135 Mon Sep 17 00:00:00 2001 From: Vincent Woo Date: Tue, 18 Nov 2008 22:29:16 -0800 Subject: Tiny doc example change for escape_once() Signed-off-by: Pratik Naik --- actionpack/lib/action_view/helpers/tag_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_view/helpers/tag_helper.rb b/actionpack/lib/action_view/helpers/tag_helper.rb index d37ca766af..72d761581a 100644 --- a/actionpack/lib/action_view/helpers/tag_helper.rb +++ b/actionpack/lib/action_view/helpers/tag_helper.rb @@ -98,7 +98,7 @@ module ActionView # Returns an escaped version of +html+ without affecting existing escaped entities. # # ==== Examples - # escape_once("1 > 2 & 3") + # escape_once("1 < 2 & 3") # # => "1 < 2 & 3" # # escape_once("<< Accept & Checkout") -- cgit v1.2.3