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 (limited to 'railties') 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:

    +

    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 582aa2ead58eacffca13e7efe94235958ee4db1b Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Fri, 7 Nov 2008 16:23:22 -0500 Subject: Set up fixtures in app's test_help --- railties/lib/test_help.rb | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 3cc61d7932..442ce3fadc 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -4,18 +4,19 @@ require_dependency 'application' # so fixtures are loaded to the right database silence_warnings { RAILS_ENV = "test" } -require 'test/unit' -require 'active_support/test_case' -require 'active_record/fixtures' -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 +require 'active_record/fixtures' +class ActiveSupport::TestCase + include ActiveRecord::TestFixtures +end + +ActiveSupport::TestCase.fixture_path = "#{RAILS_ROOT}/test/fixtures/" +ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path def create_fixtures(*table_names) - Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) + Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names) end begin -- cgit v1.2.3 From a0e7b99443cccbd01b0eefcd53b0e20878f54deb Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 12 Nov 2008 11:32:36 -0800 Subject: Remove deprecated Gem.manage_gems --- railties/lib/tasks/framework.rake | 1 - 1 file changed, 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index 66ab78c3b2..5d1f8cf945 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -5,7 +5,6 @@ namespace :rails do deps = %w(actionpack activerecord actionmailer activesupport activeresource) require 'rubygems' require 'rubygems/gem_runner' - Gem.manage_gems rails = (version = ENV['VERSION']) ? Gem.cache.find_name('rails', "= #{version}").first : -- cgit v1.2.3 From b17eb65d00242ae10ac9ed97ef22d88fdd710533 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 --- railties/lib/test_help.rb | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 442ce3fadc..a7be514cf0 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -7,16 +7,22 @@ silence_warnings { RAILS_ENV = "test" } require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -require 'active_record/fixtures' -class ActiveSupport::TestCase - include ActiveRecord::TestFixtures -end +if defined?(ActiveRecord) + require 'active_record/test_case' + require 'active_record/fixtures' + + class ActiveSupport::TestCase + include ActiveRecord::TestFixtures + self.fixture_path = "#{RAILS_ROOT}/test/fixtures/" + self.use_instantiated_fixtures = false + self.use_transactional_fixtures = true + end -ActiveSupport::TestCase.fixture_path = "#{RAILS_ROOT}/test/fixtures/" -ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path + ActionController::IntegrationTest.fixture_path = ActiveSupport::TestCase.fixture_path -def create_fixtures(*table_names) - Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names) + def create_fixtures(*table_names, &block) + Fixtures.create_fixtures(ActiveSupport::TestCase.fixture_path, table_names, {}, &block) + end end begin -- 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 --- railties/lib/test_help.rb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) (limited to 'railties') 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 334178722b8c33aba4acefe7f89e767a5660fc46 Mon Sep 17 00:00:00 2001 From: Chris Wanstrath Date: Thu, 13 Nov 2008 21:06:11 -0800 Subject: Properly check silence_spec_warnings class variable [#1372 state:committed] Signed-off-by: David Heinemeier Hansson --- railties/lib/rails/vendor_gem_source_index.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/lib/rails/vendor_gem_source_index.rb b/railties/lib/rails/vendor_gem_source_index.rb index dc821693ac..5b7721f303 100644 --- a/railties/lib/rails/vendor_gem_source_index.rb +++ b/railties/lib/rails/vendor_gem_source_index.rb @@ -81,7 +81,7 @@ module Rails spec.files = files else $stderr.puts("config.gem: Unpacked gem #{dir_name} in vendor/gems not in a versioned directory."+ - " Giving up.") unless @silence_spec_warnings + " Giving up.") unless @@silence_spec_warnings next end end @@ -137,4 +137,4 @@ module Rails end end -end \ No newline at end of file +end -- cgit v1.2.3 From ff4ccb8334e4f5b5bdccbd5dc6876b4e43d9565e Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 14 Nov 2008 12:01:26 +0100 Subject: Revert "Move fixtures settings from AR::TestCase to railties test_help" -- it broke all the tests! This reverts commit 9a88ab64bb45ddb2bdcf80fab9203111d8f8abb4. --- railties/lib/test_help.rb | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 367533cf0f..3cc61d7932 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -11,22 +11,11 @@ require 'action_controller/test_case' require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -if defined?(ActiveRecord) - require 'active_record/test_case' - require 'active_record/fixtures' +Test::Unit::TestCase.fixture_path = RAILS_ROOT + "/test/fixtures/" +ActionController::IntegrationTest.fixture_path = Test::Unit::TestCase.fixture_path - 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 +def create_fixtures(*table_names) + Fixtures.create_fixtures(Test::Unit::TestCase.fixture_path, table_names) end begin -- cgit v1.2.3 From 61e43700b85de753b6254893d5365e04d3465b9a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 14 Nov 2008 12:26:50 +0100 Subject: Prepare for RC2 --- railties/CHANGELOG | 2 +- railties/lib/rails/version.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 058afddbde..ae20cb50da 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,4 +1,4 @@ -*2.2.1 [RC2 or 2.2 final]* +*2.2.1 [RC2] (November 14th, 2008)* * Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 [Mathias Meyer] diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index a0986a2e05..bd835fba26 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -2,7 +2,7 @@ module Rails module VERSION #:nodoc: MAJOR = 2 MINOR = 2 - TINY = 0 + TINY = 1 STRING = [MAJOR, MINOR, TINY].join('.') end -- cgit v1.2.3 From 549b18c9286b6cccf4978093576325fd711dc421 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 14 Nov 2008 17:09:40 +0530 Subject: Rails now requires rubygems 1.3.1 of higher. --- railties/environments/boot.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/environments/boot.rb b/railties/environments/boot.rb index 6a30b54973..57c256e438 100644 --- a/railties/environments/boot.rb +++ b/railties/environments/boot.rb @@ -82,7 +82,7 @@ module Rails def load_rubygems require 'rubygems' - min_version = '1.1.1' + min_version = '1.3.1' unless rubygems_version >= min_version $stderr.puts %Q(Rails requires RubyGems >= #{min_version} (you have #{rubygems_version}). Please `gem update --system` and try again.) exit 1 -- cgit v1.2.3 From c70b993a9e01547de88417cb8fa95b48acbed2db Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 14 Nov 2008 17:47:21 +0530 Subject: Merge docrails. --- railties/doc/README_FOR_APP | 7 +- railties/doc/guides/html/2_2_release_notes.html | 33 +- .../doc/guides/html/actioncontroller_basics.html | 45 +- .../html/activerecord_validations_callbacks.html | 492 ++++++++- railties/doc/guides/html/caching_with_rails.html | 72 +- railties/doc/guides/html/command_line.html | 434 ++++++++ railties/doc/guides/html/configuring.html | 438 ++++++++ railties/doc/guides/html/creating_plugins.html | 1152 ++++++++++++-------- .../guides/html/debugging_rails_applications.html | 4 +- railties/doc/guides/html/finders.html | 204 ++-- .../guides/html/getting_started_with_rails.html | 4 +- .../doc/guides/html/layouts_and_rendering.html | 13 + railties/doc/guides/html/migrations.html | 4 +- railties/doc/guides/html/routing_outside_in.html | 48 +- .../guides/html/testing_rails_applications.html | 541 +++++---- railties/doc/guides/source/2_2_release_notes.txt | 19 +- .../source/actioncontroller_basics/http_auth.txt | 4 +- .../source/actioncontroller_basics/methods.txt | 8 +- .../source/actioncontroller_basics/params.txt | 10 +- .../request_response_objects.txt | 2 +- .../source/actioncontroller_basics/session.txt | 14 +- .../source/actioncontroller_basics/streaming.txt | 2 +- .../source/activerecord_validations_callbacks.txt | 383 ++++++- railties/doc/guides/source/caching_with_rails.txt | 74 +- railties/doc/guides/source/command_line.txt | 147 +++ .../source/creating_plugins/acts_as_yaffle.txt | 140 ++- .../guides/source/creating_plugins/basics.markdown | 861 --------------- .../guides/source/creating_plugins/controllers.txt | 59 + .../guides/source/creating_plugins/core_ext.txt | 123 +++ .../source/creating_plugins/custom_generator.txt | 69 -- .../source/creating_plugins/custom_route.txt | 16 +- .../doc/guides/source/creating_plugins/gem.txt | 1 + .../source/creating_plugins/generator_method.txt | 89 ++ .../doc/guides/source/creating_plugins/helpers.txt | 51 + .../doc/guides/source/creating_plugins/index.txt | 108 +- .../creating_plugins/migration_generator.txt | 127 ++- .../doc/guides/source/creating_plugins/models.txt | 76 ++ .../source/creating_plugins/odds_and_ends.txt | 57 +- .../guides/source/creating_plugins/preparation.txt | 169 --- .../source/creating_plugins/string_to_squawk.txt | 103 -- .../guides/source/creating_plugins/test_setup.txt | 230 ++++ .../guides/source/creating_plugins/view_helper.txt | 61 -- .../guides/source/debugging_rails_applications.txt | 4 +- railties/doc/guides/source/finders.txt | 84 +- .../guides/source/getting_started_with_rails.txt | 4 +- .../doc/guides/source/layouts_and_rendering.txt | 3 + .../doc/guides/source/migrations/foreign_keys.txt | 2 +- railties/doc/guides/source/migrations/scheming.txt | 2 +- railties/doc/guides/source/routing_outside_in.txt | 38 +- .../guides/source/testing_rails_applications.txt | 390 ++++--- 50 files changed, 4448 insertions(+), 2573 deletions(-) create mode 100644 railties/doc/guides/html/command_line.html create mode 100644 railties/doc/guides/html/configuring.html create mode 100644 railties/doc/guides/source/command_line.txt delete mode 100644 railties/doc/guides/source/creating_plugins/basics.markdown create mode 100644 railties/doc/guides/source/creating_plugins/controllers.txt create mode 100644 railties/doc/guides/source/creating_plugins/core_ext.txt delete mode 100644 railties/doc/guides/source/creating_plugins/custom_generator.txt create mode 100644 railties/doc/guides/source/creating_plugins/gem.txt create mode 100644 railties/doc/guides/source/creating_plugins/generator_method.txt create mode 100644 railties/doc/guides/source/creating_plugins/helpers.txt create mode 100644 railties/doc/guides/source/creating_plugins/models.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 delete mode 100644 railties/doc/guides/source/creating_plugins/view_helper.txt (limited to 'railties') diff --git a/railties/doc/README_FOR_APP b/railties/doc/README_FOR_APP index fe41f5cc24..e33b85817b 100644 --- a/railties/doc/README_FOR_APP +++ b/railties/doc/README_FOR_APP @@ -1,2 +1,5 @@ -Use this README file to introduce your application and point to useful places in the API for learning more. -Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries. +To build the guides: + +* Install source-highlighter (http://www.gnu.org/software/src-highlite/source-highlight.html) +* Install the mizuho gem (http://github.com/FooBarWidget/mizuho/tree/master) +* Run `rake guides` from the railties directory \ No newline at end of file diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index 931786ef6c..e79f7ec511 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -243,6 +243,8 @@ ul#navMain {
  • Method Arrays for Member or Collection Routes
  • +
  • Resources With Specific Actions
  • +
  • Other Action Controller Changes
  • @@ -525,7 +527,7 @@ More information :

    There are two big additions to talk about here: transactional migrations and pooled database transactions. There's also a new (and cleaner) syntax for join table conditions, as well as a number of smaller improvements.

    5.1. Transactional Migrations

    -

    Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by rake db:migrate:redo after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL only. The code is extensible to other database types in the future.

    +

    Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by rake db:migrate:redo after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter.

    @@ -693,9 +700,9 @@ Counter cache columns (for associations declared with :counter_cache ⇒

    6. Action Controller

    -

    On the controller side, there are a couple of changes that will help tidy up your routes.

    +

    On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications.

    6.1. Shallow Route Nesting

    -

    Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you can supply more information.

    +

    Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with.

    +
    map.resources :photos, :only => [:index, :show]
    +map.resources :products, :except => :destroy
    +
    +
    +

    6.4. Other Action Controller Changes

    • diff --git a/railties/doc/guides/html/actioncontroller_basics.html b/railties/doc/guides/html/actioncontroller_basics.html index d58536cc37..66563bf1a3 100644 --- a/railties/doc/guides/html/actioncontroller_basics.html +++ b/railties/doc/guides/html/actioncontroller_basics.html @@ -349,7 +349,7 @@ Deal with exceptions that may be raised during request processing

    2. Methods and Actions

    -

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

    +

    A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. 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 public method with the same name as the action.

    def new end - # These methods are responsible for producing output + # Action methods are responsible for producing output def edit end @@ -373,8 +373,8 @@ 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, 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:

    +

    There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.

    +

    As an example, if a user goes to /clients/new in your application to add a new client, Rails will create an instance of ClientsController 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:

    GET /clients?ids[]=1&ids[]=2&ids[]=3
    +
    +
    + + +
    +Note +The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.
    +

    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:

    @@ -442,7 +450,8 @@ http://www.gnu.org/software/src-highlite --> <input type="text" name="client[address][city]" value="Carrot City" /> </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].

    +

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

    +

    Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.

    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:

    @@ -461,18 +470,18 @@ map.connect "/c
    class ApplicationController < ActionController::Base
     
    -  #The options parameter is the hash passed in to url_for
    +  #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.

    +

    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

    -

    Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms:

    +

    Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:

    • @@ -481,12 +490,12 @@ CookieStore - Stores everything on the client.

    • -DRBStore - Stores the data on a DRb client. +DRbStore - Stores the data on a DRb server.

    • -MemCacheStore - Stores the data in MemCache. +MemCacheStore - Stores the data in a memcache.

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

    -

    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.

    +

    All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL).

    +

    Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, 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 (Rails will not accept it if it has been edited). 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 most common 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 CookieStore 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:

    @@ -547,7 +556,7 @@ http://www.gnu.org/software/src-highlite --> Note -There are two session methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters. +There are two session methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.

    Session values are stored using key/value pairs like a hash:

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

    The destroy action redirects to the application's root_url, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout:

    +

    The destroy action redirects to the application's root_url, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout:

    <html>
    @@ -916,7 +925,7 @@ http://www.gnu.org/software/src-highlite -->
     

    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:

    +

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

    • @@ -1030,7 +1039,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->

      class AdminController < ApplicationController
       
      -  USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
      +  USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
       
         before_filter :authenticate
       
      @@ -1038,7 +1047,7 @@ private
       
         def authenticate
           authenticate_or_request_with_http_basic do |username, password|
      -      username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD
      +      username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD
           end
         end
       
      @@ -1095,7 +1104,7 @@ http://www.gnu.org/software/src-highlite -->
       
       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.

    +

    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.

    - +
    diff --git a/railties/doc/guides/html/activerecord_validations_callbacks.html b/railties/doc/guides/html/activerecord_validations_callbacks.html index c9128a8533..0aa507a9b9 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -199,10 +199,72 @@ ul#navMain {

    Chapters

    1. - Active Record Validations + Motivations to validate your Active Record objects
    2. - Credits + How it works + +
    3. +
    4. + The declarative validation helpers + +
    5. +
    6. + Common validation options + +
    7. +
    8. + Conditional validation + +
    9. +
    10. + Writing your own validation methods
    11. Changelog @@ -250,13 +312,433 @@ Create Observers - classes with callback methods specific for each of your model -

      1. Active Record Validations

      +

      1. Motivations to validate your Active Record objects

      +
      +

      The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly.

      +

      There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons:

      +
        +
      • +

        +Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level. +

        +
      • +
      • +

        +Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data. +

        +
      • +
      • +

        +Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods. +

        +
      • +
      +
      +

      2. How it works

      +
      +

      2.1. When does validation happens?

      +

      There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the new method, that object does not belong to the database yet. Once you call save upon that object it'll be recorded to it's table. Active Record uses the new_record? instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class:

      +
      +
      +
      class Person < ActiveRecord::Base
      +end
      +
      +

      We can see how it works by looking at the following script/console output:

      +
      +
      +
      >> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979"))
      +=> #<Person id: nil, name: "John Doe", birthdate: "1979-09-03", created_at: nil, updated_at: nil>
      +>> p.new_record?
      +=> true
      +>> p.save
      +=> true
      +>> 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.

      +

      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.

      +
      +

      3. The declarative validation helpers

      +
      +

      Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's errors collection, this message being associated with the field being validated.

      +

      Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes.

      +

      All these helpers accept the :on and :message options, which define when the validation should be applied and what message should be added to the errors collection when it fails, respectively. The :on option takes one the values :save (it's the default), :create or :update. There is a default error message for each one of the validation helpers. These messages are used when the :message option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order.

      +

      3.1. The validates_acceptance_of helper

      +

      Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this acceptance does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute).

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_acceptance_of :terms_of_service
      +end
      +
      +

      The default error message for validates_acceptance_of is "must be accepted"

      +

      validates_acceptance_of can receive an :accept option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_acceptance_of :terms_of_service, :accept => 'yes'
      +end
      +
      +

      3.2. The validates_associated helper

      +

      You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, valid? will be called upon each one of the associated objects.

      +
      +
      +
      class Library < ActiveRecord::Base
      +  has_many :books
      +  validates_associated :books
      +end
      +
      +

      This validation will work with all the association types.

      +
      + + + +
      +Caution +Pay attention not to use validates_associated on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack.
      +
      +

      The default error message for validates_associated is "is invalid". Note that the errors for each failed validation in the associated objects will be set there and not in this model.

      +

      3.3. The validates_confirmation_of helper

      +

      You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with _confirmation appended.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_confirmation_of :email
      +end
      +
      +

      In your view template you could use something like

      +
      +
      +
      <%= text_field :person, :email %>
      +<%= text_field :person, :email_confirmation %>
      +
      +
      + + + +
      +Note +This check is performed only if email_confirmation is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at validates_presence_of later on this guide):
      +
      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_confirmation_of :email
      +  validates_presence_of :email_confirmation
      +end
      +
      +

      The default error message for validates_confirmation_of is "doesn't match confirmation"

      +

      3.4. The validates_each helper

      +

      This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to validates_each will be tested against it. In the following example, we don't want names and surnames to begin with lower case.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_each :name, :surname do |model, attr, value|
      +    model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/
      +  end
      +end
      +
      +

      The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid.

      +

      3.5. The validates_exclusion_of helper

      +

      This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object.

      +
      +
      +
      class MovieFile < ActiveRecord::Base
      +  validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed"
      +end
      +
      +

      The validates_exclusion_of helper has an option :in that receives the set of values that will not be accepted for the validated attributes. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.

      +

      The default error message for validates_exclusion_of is "is not included in the list".

      +

      3.6. The validates_format_of helper

      +

      This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the :with option.

      +
      +
      +
      class Product < ActiveRecord::Base
      +  validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed"
      +end
      +
      +

      The default error message for validates_format_of is "is invalid".

      +

      3.7. The validates_inclusion_of helper

      +

      This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object.

      +
      +
      +
      class Coffee < ActiveRecord::Base
      +  validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size"
      +end
      +
      +

      The validates_inclusion_of helper has an option :in that receives the set of values that will be accepted. The :in option has an alias called :within that you can use for the same purpose, if you'd like to. In the previous example we used the :message option to show how we can personalize it with the current attribute's value, through the %s format mask.

      +

      The default error message for validates_inclusion_of is "is not included in the list".

      +

      3.8. The validates_length_of helper

      +

      This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_length_of :name, :minimum => 2
      +  validates_length_of :bio, :maximum => 500
      +  validates_length_of :password, :in => 6..20
      +  validates_length_of :registration_number, :is => 6
      +end
      +
      +

      The possible length constraint options are:

      +
        +
      • +

        +:minimum - The attribute cannot have less than the specified length. +

        +
      • +
      • +

        +:maximum - The attribute cannot have more than the specified length. +

        +
      • +
      • +

        +:in (or :within) - The attribute length must be included in a given interval. The value for this option must be a Ruby range. +

        +
      • +
      • +

        +:is - The attribute length must be equal to a given value. +

        +
      • +
      +

      The default error messages depend on the type of length validation being performed. You can personalize these messages, using the :wrong_length, :too_long and :too_short options and the %d format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the :message option to specify an error message.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed."
      +end
      +
      +

      This helper has an alias called validates_size_of, it's the same helper with a different name. You can use it if you'd like to.

      +

      3.9. The validates_numericallity_of helper

      +

      This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the :integer_only option set to true, you can specify that only integral numbers are allowed.

      +

      If you use :integer_only set to true, then it will use the /\A[+\-]?\d+\Z/ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using Kernel.Float.

      +
      +
      +
      class Player < ActiveRecord::Base
      +  validates_numericallity_of :points
      +  validates_numericallity_of :games_played, :integer_only => true
      +end
      +
      +

      The default error message for validates_numericallity_of is "is not a number".

      +

      3.10. The validates_presence_of helper

      +

      This helper validates that the attributes are not empty. It uses the blank? method to check if the value is either nil or an empty string (if the string has only spaces, it will still be considered empty).

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_presence_of :name, :login, :email
      +end
      +
      +
      + + + +
      +Note +If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself.
      +
      +
      +
      +
      class LineItem < ActiveRecord::Base
      +  belongs_to :order
      +  validates_presence_of :order_id
      +end
      +
      +
      + + + +
      +Note +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
      +
      +

      The default error message for validates_presence_of is "can't be empty".

      +

      3.11. The validates_uniqueness_of helper

      +

      This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database.

      +
      +
      +
      class Account < ActiveRecord::Base
      +  validates_uniqueness_of :email
      +end
      +
      +

      The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated.

      +

      There is a :scope option that you can use to specify other attributes that must be used to define uniqueness:

      +
      +
      +
      class Holiday < ActiveRecord::Base
      +  validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year"
      +end
      +
      +

      There is also a :case_sensitive option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_uniqueness_of :name, :case_sensitive => false
      +end
      +
      +

      The default error message for validates_uniqueness_of is "has already been taken".

      +
      +

      4. Common validation options

      +
      +

      There are some common options that all the validation helpers can use. Here they are, except for the :if and :unless options, which we'll cover right at the next topic.

      +

      4.1. The :allow_nil option

      +

      You may use the :allow_nil option everytime you just want to trigger a validation if the value being validated is not nil. You may be asking yourself if it makes any sense to use :allow_nil and validates_presence_of together. Well, it does. Remember, validation will be skipped only for nil attributes, but empty strings are not considered nil.

      +
      +
      +
      class Coffee < ActiveRecord::Base
      +  validates_inclusion_of :size, :in => %w(small medium large),
      +    :message => "%s is not a valid size", :allow_nil => true
      +end
      +
      +

      4.2. The :message option

      +

      As stated before, the :message option lets you specify the message that will be added to the errors collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper.

      +

      4.3. The :on option

      +

      As stated before, the :on option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use :on => :create to run the validation only when a new record is created or :on => :update to run the validation only when a record is updated.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value
      +  validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age'
      +  validates_presence_of :name, :on => :save # => that's the default
      +end
      +
      +
      +

      5. Conditional validation

      +

      Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the :if and :unless options, which can take a symbol, a string or a Ruby Proc. You may use the :if option when you want to specify when the validation should happen. If you want to specify when the validation should not happen, then you may use the :unless option.

      +

      5.1. Using a symbol with the :if and :unless options

      +

      You can associated the :if and :unless options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option.

      +
      +
      +
      class Order < ActiveRecord::Base
      +  validates_presence_of :card_number, :if => :paid_with_card?
      +
      +  def paid_with_card?
      +    payment_type == "card"
      +  end
      +end
      +
      +

      5.2. Using a string with the :if and :unless options

      +

      You can also use a string that will be evaluated using :eval and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition.

      +
      +
      +
      class Person < ActiveRecord::Base
      +  validates_presence_of :surname, :if => "name.nil?"
      +end
      +
      +

      5.3. Using a Proc object with the :if and :unless options

      +

      Finally, it's possible to associate :if and :unless with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners.

      +
      +
      +
      class Account < ActiveRecord::Base
      +  validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? }
      +end
      +
      -

      2. Credits

      +

      6. Writing your own validation methods

      +

      When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the validate, validate_on_create or validate_on_update methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's errors collection.

      +
      +
      +
      class Invoice < ActiveRecord::Base
      +  def validate_on_create
      +    errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
      +  end
      +end
      +
      +

      If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of validate, validate_on_create or validate_on_update methods, passing it the symbols for the methods' names.

      +
      +
      +
      class Invoice < ActiveRecord::Base
      +  validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value
      +
      +  def expiration_date_cannot_be_in_the_past
      +    errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today
      +  end
      +
      +  def discount_cannot_be_greater_than_total_value
      +    errors.add(:discount, "can't be greater than total value") unless discount <= total_value
      +  end
      +end
      +
      -

      3. Changelog

      +

      7. Changelog

      diff --git a/railties/doc/guides/html/caching_with_rails.html b/railties/doc/guides/html/caching_with_rails.html index df30c46c35..7aa5999e1a 100644 --- a/railties/doc/guides/html/caching_with_rails.html +++ b/railties/doc/guides/html/caching_with_rails.html @@ -235,48 +235,54 @@ 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 Base.perform_caching is set to true for your -environment.

      +

      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.

      -
      Base.perform_caching = true
      +
      config.action_controller.perform_caching = true
       

      1.1. Page Caching

      Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver, without ever having to go through the -Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be +Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.

      So, how do you enable this super-fast cache behavior? Simple, let's say you -have a controller called ProductController and a list action that lists all +have a controller called ProductsController and a list action that lists all the products

      -
      class ProductController < ActionController
      +
      class ProductsController < ActionController
       
      -  cache_page :list
      +  caches_page :index
       
      -  def list; end
      +  def index; end
       
       end
       
      -

      The first time anyone requestsion products/list, Rails will generate a file -called list.html and the webserver will then look for that file before it -passes the next request for products/list to your Rails application.

      +

      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 +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 Base.cache_public_directory

      -

      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 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 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 Base.page_cache_extension

      +configuration setting ActionController::Base.page_cache_extension.

      In order to expire this page when a new product is added we could extend our example controler like this:

      @@ -284,9 +290,9 @@ example controler like this:

      by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
      class ProductController < ActionController
      +
      class ProductsController < ActionController
       
      -  cache_page :list
      +  caches_page :list
       
         def list; end
       
      @@ -299,11 +305,11 @@ http://www.gnu.org/software/src-highlite -->
       

      If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.

      1.2. Action Caching

      -

      One of the issues with page caching is that you cannot use it for pages that +

      One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so -that before_filters can be run on it before the cache is served, so that +that before filters can be run on it before the cache is served, so that authentication and other restrictions can be used while still serving the result of the output from a cached copy.

      Clearing the cache works in the exact same way as with Page Caching.

      @@ -314,10 +320,10 @@ object, but still cache those pages:

      by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
      class ProductController < ActionController
      +
      class ProductsController < ActionController
       
         before_filter :authenticate, :only => [ :edit, :create ]
      -  cache_page :list
      +  caches_page :list
         caches_action :edit
       
         def list; end
      @@ -336,7 +342,7 @@ action should be cached. Also, you can use :layout ⇒ false to cache withou
       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.

      -

      [More: more examples? Walk-through of action caching from request to response? +

      [More: more examples? Walk-through of Action Caching from request to response? Description of Rake tasks to clear cached files? Show example of subdomain caching? Talk about :cache_path, :if and assing blocks/Procs to expire_action?]

      @@ -346,13 +352,13 @@ a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired -differently Rails provides a mechanism called Fragment caching.

      -

      Fragment caching allows a fragment of view logic to be wrapped in a cache +differently Rails provides a mechanism called Fragment Caching.

      +

      Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.

      -

      As an example, if you wanted to show all the orders placed on your website in -real time and didn't want to cache that part of the page, but did want to -cache the part of the page which lists all products available, you could use -this piece of code:

      +

      As an example, if you wanted to show all the orders placed on your website +in real time and didn't want to cache that part of the page, but did want +to cache the part of the page which lists all products available, you +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_path to the cache call:

      +want to cache multiple fragments per action, you should provide an action_suffix to the cache call:

      -
      class ProductController < ActionController
      +
      class ProductsController < ActionController
       
         before_filter :authenticate, :only => [ :edit, :create ]
      -  cache_page :list
      +  caches_page :list
         caches_action :edit
         cache_sweeper :store_sweeper, :only => [ :create ]
       
      @@ -468,10 +474,10 @@ database again.

      by Lorenzo Bettini http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite --> -
      class ProductController < ActionController
      +
      class ProductsController < ActionController
       
         before_filter :authenticate, :only => [ :edit, :create ]
      -  cache_page :list
      +  caches_page :list
         caches_action :edit
         cache_sweeper :store_sweeper, :only => [ :create ]
       
      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/configuring.html b/railties/doc/guides/html/configuring.html new file mode 100644 index 0000000000..4aa3a0f545 --- /dev/null +++ b/railties/doc/guides/html/configuring.html @@ -0,0 +1,438 @@ + + + + + Configuring Rails Applications + + + + + + + + + +
      + + + +
      +

      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 +

        +
      • +
      +
      +
      +

      1. Locations for Initialization Code

      +
      +

      preinitializers +environment.rb first +env-specific files +initializers (load_application_initializers) +after-initializer

      +
      +

      2. Using a Preinitializer

      +
      +
      +

      3. 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. Using Initializers

      +
      +
      +
      +
      organization, controlling load order
      +
      +
      +

      5. Using an After-Initializer

      +
      +
      +

      6. Changelog

      +
      + +
      +

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

      +
      + +
      +
      + + diff --git a/railties/doc/guides/html/creating_plugins.html b/railties/doc/guides/html/creating_plugins.html index 48d5f03687..375d216b4a 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -204,26 +204,61 @@ ul#navMain {
    12. Create the basic app
    13. -
    14. Create the plugin
    15. +
    16. Generate the plugin skeleton
    17. Setup the plugin for testing
    18. +
    19. Run the plugin tests
    20. + + +
    21. +
    22. + Extending core classes + +
    23. +
    24. + Add an acts_as_yaffle method to Active Record +
    25. - Add a to_squawk method to String + Create a generator +
    26. - Add an acts_as_yaffle method to ActiveRecord + Add a custom generator command
    27. - Create a squawk_info_for view helper + Add a model
    28. - Create a migration generator + Add a controller
    29. - Add a custom generator command + Add a helper
    30. Add a Custom Route @@ -232,12 +267,8 @@ ul#navMain { Odds and ends
        -
      • Work with init.rb
      • -
      • Generate RDoc Documentation
      • -
      • Store models, views, helpers, and controllers in your plugins
      • -
      • Write custom Rake tasks in your plugin
      • Store plugins in alternate locations
      • @@ -265,123 +296,107 @@ 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

        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 +407,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,51 +447,37 @@ 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
    -
    +

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

    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.

    +

    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:

    -

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

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

    sqlite:
       :adapter: sqlite
    -  :dbfile: yaffle_plugin.sqlite.db
    +  :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
    @@ -486,11 +489,12 @@ postgresql:
     mysql:
       :adapter: mysql
       :host: localhost
    -  :username: rails
    -  :password:
    +  :username: root
    +  :password: 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.string :last_tweet t.datetime :last_tweeted_at end + create_table :woodpeckers, :force => true do |t| + t.string :name + 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'
     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']
     
    -# no db passed, try one of these fine config-free DBs before bombing.
    -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
    +
    +  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."
    +  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.

    +

    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'
     
    -ActiveRecord::Base.establish_connection(config[db_adapter])
    +class YaffleTest < Test::Unit::TestCase
    +  load_schema
     
    -load(File.dirname(__FILE__) + "/schema.rb")
    +  class Hickwall < ActiveRecord::Base
    +  end
     
    -require File.dirname(__FILE__) + '/../init.rb'
    +  class Wickwall < ActiveRecord::Base
    +  end
     
    -class Hickwall < ActiveRecord::Base
    -  acts_as_yaffle
    -end
    +  def test_schema_has_loaded_correctly
    +    assert_equal [], Hickwall.all
    +    assert_equal [], Wickwall.all
    +  end
     
    -class Wickwall < ActiveRecord::Base
    -  acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
     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!

    -

    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:

    +

    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

    -
    # File: vendor/plugins/yaffle/test/core_ext_test.rb
    -
    -require 'test/unit'
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class CoreExtTest < Test::Unit::TestCase
    -  # Replace this with your real tests.
    -  def test_this_plugin
    -    flunk
    +  def test_to_squawk_prepends_the_word_squawk
    +    assert_equal "squawk! Hello World", "Hello World".to_squawk
       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:

    +

    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.

    +

    2.2. Organize your files

    +

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

    -
    1.) Failure ...
    -No tests were specified
    +
    |-- lib
    +|   |-- yaffle
    +|   |   `-- core_ext.rb
    +|   `-- yaffle.rb
    -

    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:

    +

    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

    -
    # 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
    +
    require 'yaffle'
     
    +

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

    +

    vendor/plugins/yaffle/lib/yaffle.rb

    -
    # File: vendor/plugins/yaffle/init.rb
    -
    -require "core_ext"
    +
    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

    -
    # File: vendor/plugins/yaffle/lib/core_ext.rb
    -
    -String.class_eval do
    +
    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:

    +

    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.

    +

    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

    -
    # 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
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
     class ActsAsYaffleTest < Test::Unit::TestCase
     end
     
    +

    vendor/plugins/yaffle/lib/yaffle.rb

    -
    # File: vendor/plugins/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    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:

    +

    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:

    +

    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

    -
    module ClassMethods
    -  def acts_as_yaffle(options = {})
    -    send :include, InstanceMethods
    -  end
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +
    +class Hickwall < ActiveRecord::Base
    +  acts_as_yaffle
     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 Wickwall < ActiveRecord::Base
    +  acts_as_yaffle :yaffle_text_field => :last_tweet
    +end
     
     class ActsAsYaffleTest < Test::Unit::TestCase
    +  load_schema
    +
       def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
         assert_equal "last_squawk", Hickwall.yaffle_text_field
       end
     
    -  def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
    -    assert_equal "last_squawked_at", Hickwall.yaffle_date_field
    -  end
    -
       def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
         assert_equal "last_tweet", Wickwall.yaffle_text_field
       end
    -
    -  def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
    -    assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
    -  end
     end
     

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

    +

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

    -
    # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    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
    +      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

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

    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

    -
    # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
    -
    -module Yaffle
    +
    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
    +      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
    @@ -867,130 +920,122 @@ 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
     
    -

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

    -
    -

    4. Create a squawk_info_for view helper

    -
    -

    Creating a view helper is a 3-step process:

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

    • -Add an appropriately named file to the lib directory. +Creates a new fake rails root directory that will serve as destination

    • -Require the file and hooks in init.rb. +Runs the generator forward and backward, making whatever assertions are necessary

    • -Write the tests. +Removes the fake rails root

    -

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

    +

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

    +

    vendor/plugins/yaffle/test/yaffle_generator_test.rb

    -
    # File: vendor/plugins/yaffle/test/view_helpers_test.rb
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +require 'rails_generator'
    +require 'rails_generator/scripts/generate'
    +require 'rails_generator/scripts/destroy'
     
    -require File.dirname(__FILE__) + '/test_helper.rb'
    -include YaffleViewHelper
    +class GeneratorTest < Test::Unit::TestCase
     
    -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)
    +  def fake_rails_root
    +    File.join(File.dirname(__FILE__), 'rails_root')
       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
    +  def file_list
    +    Dir.glob(File.join(fake_rails_root, "db", "migrate", "*"))
       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

    -
    -

    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
    +  def setup
    +    FileUtils.mkdir_p(fake_rails_root)
    +    @original_files = file_list
    +  end
     
    -    This will create:
    -        db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
    -
    -

    Now you can add code to your generator:

    + 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

    -
    # 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,
             :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
    -       }
    +      }
         end
       end
     
    @@ -1006,91 +1051,100 @@ 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.

    +

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

    -
    # 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
       end
     
       def self.down
    -    remove_column :birds, :last_squawked_at
         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
    +
    -

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

    +

    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

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

    -
    # File: vendor/plugins/yaffle/lib/commands.rb
    -
    -require 'rails_generator'
    +
    require "yaffle/commands"
    +
    +

    vendor/plugins/yaffle/lib/commands.rb

    +
    +
    +
    require 'rails_generator'
     require 'rails_generator/commands'
     
     module Yaffle #:nodoc:
    @@ -1113,42 +1167,230 @@ 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
    +
    +

    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

    +
    +

    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:

    -
    # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
    -
    -Yaffle is a bird
    +
    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:

    -
    # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
     
    -class YaffleGenerator < Rails::Generator::NamedBase
    -  def manifest
    -    m.yaffle_definition
    +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
     
    -

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

    +

    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 Custom Route

    +

    7. Add a controller

    -

    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.

    +

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

    -
    # File: vendor/plugins/yaffle/test/routing_test.rb
    +
    require File.dirname(__FILE__) + '/test_helper.rb'
    +include WoodpeckersHelper
     
    -require "#{File.dirname(__FILE__)}/test_helper"
    +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:

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

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

    +
    +

    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

    +
    +
    +
    require "#{File.dirname(__FILE__)}/test_helper"
     
     class RoutingTest < Test::Unit::TestCase
     
    @@ -1174,24 +1416,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
    @@ -1201,51 +1441,22 @@ 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
     

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

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

      @@ -1277,35 +1488,16 @@ Warning, gotchas or tips that might help save users time.
      rake rdoc
    -

    8.3. 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.4. 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

    -
    # 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!"
    @@ -1318,7 +1510,7 @@ namespace :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

    +

    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!

    @@ -1329,14 +1521,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.6. 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.7. 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

    • @@ -1359,7 +1551,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/html/debugging_rails_applications.html b/railties/doc/guides/html/debugging_rails_applications.html index 95f5b39e4c..0653caaf7a 100644 --- a/railties/doc/guides/html/debugging_rails_applications.html +++ b/railties/doc/guides/html/debugging_rails_applications.html @@ -939,7 +939,7 @@ No breakpoints.
  • -finish [frame-number] (or fin): execute until the selected stack frame returns. If no frame number is given, the application run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns. +finish [frame-number] (or fin): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns.

  • @@ -1062,7 +1062,7 @@ http://www.gnu.org/software/src-highlite -->
    • -Footnotes: Every Rails page has footnotes that link give request information and link back to your source via TextMate. +Footnotes: Every Rails page has footnotes that give request information and link back to your source via TextMate.

    • diff --git a/railties/doc/guides/html/finders.html b/railties/doc/guides/html/finders.html index 18bc32306f..02c1654aa5 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -198,9 +198,6 @@ ul#navMain { -

      3. Database Agnostic

      +

      2. Database Agnostic

      Active Record will perform queries on the database for you and is compatible with most database systems (MySQL, PostgreSQL and SQLite to name a few). Regardless of which database system you're using, the Active Record method format will always be the same.

      -

      4. IDs, First, Last and All

      +

      3. IDs, First, Last and All

      ActiveRecord::Base has methods defined on it to make interacting with your database and the tables within it much, much easier. For finding records, the key method is find. This method allows you to pass arguments into it to perform certain queries on your database without the need of SQL. If you wanted to find the record with the id of 1, you could type Client.find(1) which would execute this query on your database:

      @@ -381,6 +416,14 @@ http://www.gnu.org/software/src-highlite --> 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.

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

      @@ -423,15 +466,21 @@ http://www.gnu.org/software/src-highlite -->

      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.

      -

      5. Conditions

      +

      4. Conditions

      -

      5.1. Pure String Conditions

      +

      The find method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash.

      +

      4.1. Pure String Conditions

      If you'd like to add conditions to your find, you could just specify them in there, just like Client.first(:conditions ⇒ "orders_count = 2"). This will find all clients where the orders_count field's value is 2.

      -

      5.2. 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.
      -
      +
      + + + +
      +Warning +Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, Client.first(:conditions ⇒ "name LIKE %#{params[:name]}%") is not safe. See the next section for the preferred way to handle conditions using an array.
      +
      +

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

      The reason for doing code like:

      ["created_at >= ? AND created_at <= ?", params[:start_date], params[:end_date]])

      Just like in Ruby.

      -

      5.3. Hash Conditions

      +

      4.3. Hash Conditions

      Similar to the array style of params you can also specify keys in your conditions:

      This makes for clearer readability if you have a large number of variable conditions.

      -

      6. Ordering

      +

      5. Ordering

      If you're getting a set of records and want to force an order, you can use Client.all(:order ⇒ "created_at") which by default will sort the records by ascending order. If you'd like to order it in descending order, just tell it to do that using Client.all(:order ⇒ "created_at desc")

      -

      7. Selecting Certain Fields

      +

      6. Selecting Certain Fields

      To select certain fields, you can use the select option like this: Client.first(:select ⇒ "viewable_by, locked"). This select option does not use an array of fields, but rather requires you to type SQL-like code. The above code will execute SELECT viewable_by, locked FROM clients LIMIT 0,1 on your database.

      -

      8. Limit & Offset

      +

      7. Limit & Offset

      -

      If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:

      +

      If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example:

      SELECT * FROM clients LIMIT 5, 5
       
      -

      9. Group

      +

      8. Group

      The group option for find is useful, for example, if you want to find a collection of the dates orders were created on. You could use the option in this context:

      @@ -595,9 +644,9 @@ http://www.gnu.org/software/src-highlite -->
      SELECT * FROM +orders+ GROUP BY date(created_at)
       
      -

      10. Read Only

      +

      9. Read Only

      -

      Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an Active Record::ReadOnlyRecord error. To set this option, specify it like this:

      +

      Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an Active Record::ReadOnlyRecord exception. To set this option, specify it like this:

      Client.first(:readonly => true)
       
      -

      If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord:

      +

      If you assign this record to a variable client, calling the following code will raise an ActiveRecord::ReadOnlyRecord exception:

      end
      -

      12. Making It All Work Together

      +

      11. Making It All Work Together

      -

      You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter.

      +

      You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter.

      -

      13. Eager Loading

      +

      12. Eager Loading

      -

      Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use Client.all(:include ⇒ :address). If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include ⇒ [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:

      +

      Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use Client.all(:include ⇒ :address). If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include ⇒ [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this:

      ["orders.created_at >= ? AND orders.created_at <= ?", Time.now - 2.weeks, Time.now])
      -

      14. Dynamic finders

      +

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

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

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

    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.

    -

    15. Finding By SQL

    +

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

    @@ -714,11 +763,11 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc")
     
    -

    find_by_sql provides you with a simple way of making custom calls to the database and retreiving instantiated objects.

    +

    find_by_sql provides you with a simple way of making custom calls to the database and retrieving instantiated objects.

    -

    16. select_all

    +

    15. select_all

    -

    find_by_sql has a close relative called select_all. select_all will retreive objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.

    +

    find_by_sql has a close relative called connection#select_all. select_all will retrieve objects from the database using custom SQL just like find_by_sql but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record.

    Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'")
     
    -

    17. Working with Associations

    +

    16. Working with Associations

    -

    When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like Client.find(params[:id]).orders.find_by_sent_and_received(true, false). Having this find method available on associations is extremely helpful when using nested controllers.

    +

    When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like Client.find(params[:id]).orders.find_by_sent_and_received(true, false). Having this find method available on associations is extremely helpful when using nested controllers.

    -

    18. Named Scopes

    +

    17. Named Scopes

    -

    Named scopes are another way to add custom finding behavior to the models in the application. Suppose want to find all clients who are male. Yould use this code:

    +

    Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query.

    +

    17.1. Simple Named Scopes

    +

    Suppose want to find all clients who are male. You could use this code:

    named_scope :males, :conditions => { :gender => "male" } end
    -

    And you could call it like Client.males.all to get all the clients who are male. Please note that if you do not specify the all on the end you will get a Scope object back, not a set of records which you do get back if you put the all on the end.

    +

    Then you could call Client.males.all to get all the clients who are male. Please note that if you do not specify the all on the end you will get a Scope object back, not a set of records which you do get back if you put the all on the end.

    If you wanted to find all the clients who are active, you could use this:

    named_scope :active, :conditions => { :active => true } end
    -

    You can call this new named_scope by doing Client.active.all and this will do the same query as if we just used Client.all(:conditions ⇒ ["active = ?", true]). Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do Client.active.first.

    +

    You can call this new named_scope with Client.active.all and this will do the same query as if we just used Client.all(:conditions ⇒ ["active = ?", true]). Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do Client.active.first.

    +

    17.2. Combining Named Scopes

    If you wanted to find all the clients who are active and male you can stack the named scopes like this:

    Client.males.active.all(:conditions => ["age > ?", params[:age]])
     
    +

    17.3. Runtime Evaluation of Named Scope Conditions

    Consider the following code:

    end

    And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded.

    +

    17.4. Named Scopes with Multiple Models

    In a named scope you can use :include and :joins options just like in find.

    end

    This method, called as Client.active_within_2_weeks.all, will return all clients who have placed orders in the past 2 weeks.

    +

    17.5. Arguments to Named Scopes

    If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this:

    This will work with Client.recent(2.weeks.ago).all and Client.recent.all, with the latter always returning records with a created_at date between right now and 2 weeks ago.

    Remember that named scopes are stackable, so you will be able to do Client.recent(2.weeks.ago).unlocked.all to find all clients created between right now and 2 weeks ago and have their locked field set to false.

    -

    Finally, if you wish to define named scopes on the fly you can use the scoped method:

    +

    17.6. Anonymous Scopes

    +

    All Active Record models come with a named scope named scoped, which allows you to create anonymous scopes. For example:

    end end
    +

    Anonymous scopes are most useful to create scopes "on the fly":

    +
    +
    +
    Client.scoped(:conditions => { :gender => "male" })
    +
    +

    Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes.

    -

    19. Existence of Objects

    +

    18. Existence of Objects

    If you simply want to check for the existence of the object there's a method called exists?. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false.

    @@ -849,7 +914,7 @@ http://www.lorenzobettini.it http://www.gnu.org/software/src-highlite -->
    Client.exists?(1)
     
    -

    The above code will check for the existance of a clients table record with the id of 1 and return true if it exists.

    +

    The above code will check for the existence of a clients table record with the id of 1 and return true if it exists.

    Client.exists?(:conditions => "first_name = 'Ryan'")
     
    -

    20. Calculations

    +

    19. Calculations

    This section uses count as an example method in this preamble, but the options described apply to all sub-sections.

    count takes conditions much in the same way exists? does:

    @@ -907,10 +972,10 @@ http://www.gnu.org/software/src-highlite --> (clients.first_name = 'name' AND orders.status = 'received')

    This code specifies clients.first_name just in case one of the join tables has a field also called first_name and it uses orders.status because that's the name of our join table.

    -

    20.1. Count

    +

    19.1. Count

    If you want to see how many records are in your model's table you could call Client.count and that will return the number. If you want to be more specific and find all the clients with their age present in the database you can use Client.count(:age).

    For options, please see the parent section, Calculations.

    -

    20.2. Average

    +

    19.2. Average

    If you want to see the average of a certain number in one of your tables you can call the average method on the class that relates to the table. This method call will look something like this:

    This will return a number (possibly a floating point number such as 3.14159265) representing the average value in the field.

    For options, please see the parent section, Calculations

    -

    20.3. Minimum

    +

    19.3. Minimum

    If you want to find the minimum value of a field in your table you can call the minimum method on the class that relates to the table. This method call will look something like this:

    Client.minimum("age")
     

    For options, please see the parent section, Calculations

    -

    20.4. Maximum

    +

    19.4. Maximum

    If you want to find the maximum value of a field in your table you can call the maximum method on the class that relates to the table. This method call will look something like this:

    Client.maximum("age")
     

    For options, please see the parent section, Calculations

    -

    20.5. Sum

    +

    19.5. Sum

    If you want to find the sum of a field for all records in your table you can call the sum method on the class that relates to the table. This method call will look something like this:

    For options, please see the parent section, Calculations

    -

    21. Credits

    +

    20. Credits

    Thanks to Ryan Bates for his awesome screencast on named scope #108. The information within the named scope section is intentionally similar to it, and without the cast may have not been possible.

    Thanks to Mike Gunderloy for his tips on creating this guide.

    -

    22. Changelog

    +

    21. Changelog

    • -October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section. +November 8, 2008: Editing pass by 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 this comment with an exception of the final point. +October 27, 2008: Fixed up all points specified in this comment with an exception of the final point by Ryan Bigg

    • diff --git a/railties/doc/guides/html/getting_started_with_rails.html b/railties/doc/guides/html/getting_started_with_rails.html index 1b2eac0ce5..5111d0c645 100644 --- a/railties/doc/guides/html/getting_started_with_rails.html +++ b/railties/doc/guides/html/getting_started_with_rails.html @@ -712,7 +712,7 @@ The production environment is used when you deploy your application for

    3.3.1. Configuring a SQLite Database

    -

    Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.

    +

    Rails comes with built-in support for SQLite, which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later.

    Here's the section of the default configuration file with connection information for the development environment:

    For more information on finding records with Active Record, see Active Record Finders.
    -

    The respond_to block handles both HTML and XML calls to this action. If you borwse to http://localhost:3000/posts.xml, you'll see all of the posts in XML format. The HTML format looks for a view in app/views/posts/ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's app/view/posts/index.html.erb:

    +

    The respond_to block handles both HTML and XML calls to this action. If you browse to http://localhost:3000/posts.xml, you'll see all of the posts in XML format. The HTML format looks for a view in app/views/posts/ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's app/view/posts/index.html.erb:

    <%= render :partial => "product", :collection => @products, :as => :item %>
     

    With this change, you can access an instance of the @products collection as the item local variable within the partial.

    +
    + + + +
    +Tip +Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by _counter. For example, if you're rendering @products, within the partial you can refer to product_counter to tell you how many times the partial has been rendered.
    +

    You can also specify a second partial to be rendered between instances of the main partial by using the :spacer_template option:

    • +November 9, 2008: Added partial collection counter by Mike Gunderloy +

      +
    • +
    • +

      November 1, 2008: Added :js option for render by Mike Gunderloy

    • diff --git a/railties/doc/guides/html/migrations.html b/railties/doc/guides/html/migrations.html index 5d0f450634..8b580d8086 100644 --- a/railties/doc/guides/html/migrations.html +++ b/railties/doc/guides/html/migrations.html @@ -865,7 +865,7 @@ http://www.gnu.org/software/src-highlite -->

      Migrations, mighty as they may be, are not the authoritative source for your database schema. That role falls to either schema.rb or an SQL file which Active Record generates by examining the database. They are not designed to be edited, they just represent the current state of the database.

      There is no need (and it is error prone) to deploy a new instance of an app by replaying the entire migration history. It is much simpler and faster to just load into the database a description of the current schema.

      For example, this is how the test database is created: the current development database is dumped (either to schema.rb or development.sql) and then loaded into the test database.

      -

      Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.

      +

      Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The annotate_models plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest.

      6.2. Types of schema dumps

      There are two ways to dump the schema. This is set in config/environment.rb by the config.active_record.schema_format setting, which may be either :sql or :ruby.

      If :ruby is selected then the schema is stored in db/schema.rb. If you look at this file you'll find that it looks an awful lot like one very big migration:

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

    7. Active Record and Referential Integrity

    -

    The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.

    +

    The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used.

    Validations such as validates_uniqueness_of are one way in which models can enforce data integrity. The :dependent option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints.

    Although Active Record does not provide any tools for working directly with such features, the execute method can be used to execute arbitrary SQL. There are also a number of plugins such as redhillonrails which add foreign key support to Active Record (including support for dumping foreign keys in schema.rb).

    diff --git a/railties/doc/guides/html/routing_outside_in.html b/railties/doc/guides/html/routing_outside_in.html index a1f1f98cfb..947d0836ce 100644 --- a/railties/doc/guides/html/routing_outside_in.html +++ b/railties/doc/guides/html/routing_outside_in.html @@ -925,6 +925,16 @@ cellspacing="0" cellpadding="4"> :name_prefix

    +
  • +

    +:only +

    +
  • +
  • +

    +:except +

    +
  • You can also add additional routes via the :member and :collection options, which are discussed later in this guide.

    3.6.1. Using :controller

    @@ -1419,6 +1429,34 @@ map.resources : You can also use :name_prefix with non-RESTful routes.
    +

    3.7.8. Using :only and :except

    +

    By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the :only and :except options to fine-tune this behavior. The :only option specifies that only certain routes should be generated:

    +
    +
    +
    map.resources :photos, :only => [:index, :show]
    +
    +

    With this declaration, a GET request to /photos would succeed, but a POST request to /photos (which would ordinarily be routed to the create action) will fail.

    +

    The :except option specifies a route or list of routes that should not be generated:

    +
    +
    +
    map.resources :photos, :except => :destroy
    +
    +

    In this case, all of the normal routes except the route for destroy (a DELETE request to /photos/id) will be generated.

    +

    In addition to an action or a list of actions, you can also supply the special symbols :all or :none to the :only and :except options.

    +
    + + + +
    +Tip +If your application has many RESTful routes, using :only and :accept 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

    It's common to have resources that are logically children of other resources. For example, suppose your application includes these models:

    @@ -1690,15 +1728,7 @@ http://www.gnu.org/software/src-highlite --> /magazines/2/photos ==> magazines_photos_path(2) /photos/3 ==> photo_path(3)
    -

    With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you can supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource:

    -
    -
    -
    /publishers/1/magazines/2/photos/3   ==> publisher_magazine_photo_path(1,2,3)
    -/magazines/2/photos/3                ==> magazine_photo_path(2,3)
    -/photos/3                            ==> photo_path(3)
    -
    -

    Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity.

    -

    If you like, you can combine shallow nesting with the :has_one and :has_many options:

    +

    With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the :has_one and :has_many options:

    # 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/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt index 715648b95e..f78c179ba1 100644 --- a/railties/doc/guides/source/2_2_release_notes.txt +++ b/railties/doc/guides/source/2_2_release_notes.txt @@ -118,11 +118,12 @@ There are two big additions to talk about here: transactional migrations and poo === Transactional Migrations -Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported *on PostgreSQL only*. The code is extensible to other database types in the future. +Historically, multiple-step Rails migrations have been a source of trouble. If something went wrong during a migration, everything before the error changed the database and everything after the error wasn't applied. Also, the migration version was stored as having been executed, which means that it couldn't be simply rerun by +rake db:migrate:redo+ after you fix the problem. Transactional migrations change this by wrapping migration steps in a DDL transaction, so that if any of them fail, the entire migration is undone. In Rails 2.2, transactional migrations are supported on PostgreSQL out of the box. The code is extensible to other database types in the future - and IBM has already extended it to support the DB2 adapter. * Lead Contributor: link:http://adam.blog.heroku.com/[Adam Wiggins] * More information: - link:http://adam.blog.heroku.com/past/2008/9/3/ddl_transactions/[DDL Transactions] + - link:http://db2onrails.com/2008/11/08/a-major-milestone-for-db2-on-rails/[A major milestone for DB2 on Rails] === Connection Pooling @@ -208,11 +209,11 @@ Active Record association proxies now respect the scope of methods on the proxie == Action Controller -On the controller side, there are a couple of changes that will help tidy up your routes. +On the controller side, there are several changes that will help tidy up your routes. There are also some internal changes in the routing engine to lower memory usage on complex applications. === Shallow Route Nesting -Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ supply more information. +Shallow route nesting provides a solution to the well-known difficulty of using deeply-nested resources. With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. [source, ruby] ------------------------------------------------------- @@ -249,7 +250,17 @@ map.resources :photos, :collection => { :search => [:get, :post] } * Lead Contributor: link:http://brennandunn.com/[Brennan Dunn] -Action Controller now offers good support for HTTP conditional GET requests, as well as some other additions. +=== Resources With Specific Actions + +By default, when you use +map.resources+ to create a route, Rails generates routes for seven default actions (index, show, create, new, edit, update, and destroy). But each of these routes takes up memory in your application, and causes Rails to generate additional routing logic. Now you can use the +:only+ and +:except+ options to fine-tune the routes that Rails will generate for resources. You can supply a single action, an array of actions, or the special +:all+ or +:none+ options. These options are inherited by nested resources. + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :only => [:index, :show] +map.resources :products, :except => :destroy +------------------------------------------------------- + +* Lead Contributor: link:http://experthuman.com/[Tom Stuart] === Other Action Controller Changes diff --git a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt index 954b8a525e..8deb40c2c9 100644 --- a/railties/doc/guides/source/actioncontroller_basics/http_auth.txt +++ b/railties/doc/guides/source/actioncontroller_basics/http_auth.txt @@ -6,7 +6,7 @@ Rails comes with built-in HTTP Basic authentication. This is an authentication s ------------------------------------- class AdminController < ApplicationController - USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c" + USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8" before_filter :authenticate @@ -14,7 +14,7 @@ private def authenticate authenticate_or_request_with_http_basic do |username, password| - username == USERNAME && Digest::MD5.hexdigest(password) == PASSWORD + username == USERNAME && Digest::SHA1.hexdigest(password) == PASSWORD end end diff --git a/railties/doc/guides/source/actioncontroller_basics/methods.txt b/railties/doc/guides/source/actioncontroller_basics/methods.txt index c6ae54a540..68204c189a 100644 --- a/railties/doc/guides/source/actioncontroller_basics/methods.txt +++ b/railties/doc/guides/source/actioncontroller_basics/methods.txt @@ -1,6 +1,6 @@ == Methods and Actions == -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). +A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. 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 public method with the same name as the action. [source, ruby] ---------------------------------------------- @@ -10,7 +10,7 @@ class ClientsController < ApplicationController def new end - # These methods are responsible for producing output + # Action methods are responsible for producing output def edit end @@ -23,9 +23,9 @@ private end ---------------------------------------------- -Private methods in a controller are also used as filters, which will be covered later in this guide. +There's no rule saying a method on a controller has to be an action; they may well be used for other purposes such 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, 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: +As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of ClientsController 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] ---------------------------------------------- diff --git a/railties/doc/guides/source/actioncontroller_basics/params.txt b/railties/doc/guides/source/actioncontroller_basics/params.txt index fb380519fd..e8a2d3d058 100644 --- a/railties/doc/guides/source/actioncontroller_basics/params.txt +++ b/railties/doc/guides/source/actioncontroller_basics/params.txt @@ -43,6 +43,8 @@ The params hash is not limited to one-dimensional keys and values. It can contai GET /clients?ids[]=1&ids[]=2&ids[]=3 ------------------------------------- +NOTE: The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don't have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind. + 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: @@ -56,7 +58,9 @@ 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]`. +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]`. + +Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys. === Routing Parameters === @@ -78,7 +82,7 @@ You can set global default parameters that will be used when generating URLs wit ------------------------------------ class ApplicationController < ActionController::Base - #The options parameter is the hash passed in to url_for + #The options parameter is the hash passed in to +url_for+ def default_url_options(options) {:locale => I18n.locale} end @@ -86,4 +90,4 @@ class ApplicationController < ActionController::Base 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. +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 250f84bd72..07a8ec2574 100644 --- a/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt +++ b/railties/doc/guides/source/actioncontroller_basics/request_response_objects.txt @@ -4,7 +4,7 @@ In every controller there are two accessor methods pointing to the request and t === 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]. Among the properties that you can access on this 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]. 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"). diff --git a/railties/doc/guides/source/actioncontroller_basics/session.txt b/railties/doc/guides/source/actioncontroller_basics/session.txt index 3b69ec82ef..ae5f876777 100644 --- a/railties/doc/guides/source/actioncontroller_basics/session.txt +++ b/railties/doc/guides/source/actioncontroller_basics/session.txt @@ -1,15 +1,15 @@ == Session == -Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and can use one of a number of different storage mechanisms: +Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms: * CookieStore - Stores everything on the client. - * DRBStore - Stores the data on a DRb client. - * MemCacheStore - Stores the data in MemCache. + * DRbStore - Stores the data on a DRb server. + * MemCacheStore - Stores the data in a memcache. * ActiveRecordStore - Stores the data in a database using Active Record. -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. +All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can't use the query string to pass a session ID) because of security concerns (it's easier to hijack a session when the ID is part of the URL). -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. +Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, 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 (Rails will not accept it if it has been edited). 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 most common 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 CookieStore 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]. @@ -56,7 +56,7 @@ end In your controller you can access the session through the `session` instance method. -NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. The class method is used outside of method definitions while the instance methods is used inside methods, in actions or filters. +NOTE: There are two `session` methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values. Session values are stored using key/value pairs like a hash: @@ -129,7 +129,7 @@ class LoginsController < ApplicationController end ------------------------------------------ -The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to a display eventual errors or notices from the flash in the application's layout: +The `destroy` action redirects to the application's `root_url`, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display eventual errors or notices from the flash in the application's layout: ------------------------------------------ diff --git a/railties/doc/guides/source/actioncontroller_basics/streaming.txt b/railties/doc/guides/source/actioncontroller_basics/streaming.txt index f42480ba25..dc8ebe6d55 100644 --- a/railties/doc/guides/source/actioncontroller_basics/streaming.txt +++ b/railties/doc/guides/source/actioncontroller_basics/streaming.txt @@ -48,7 +48,7 @@ class ClientsController < ApplicationController 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. +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 that might allow someone to gain access to files they are not meant to see. diff --git a/railties/doc/guides/source/activerecord_validations_callbacks.txt b/railties/doc/guides/source/activerecord_validations_callbacks.txt index cd698d0c1e..fd6eb86b0b 100644 --- a/railties/doc/guides/source/activerecord_validations_callbacks.txt +++ b/railties/doc/guides/source/activerecord_validations_callbacks.txt @@ -12,13 +12,392 @@ After reading this guide and trying out the presented concepts, we hope that you * 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 +== Motivations to validate your Active Record objects +The main reason for validating your objects before they get into the database is to ensure that only valid data is recorded. It's important to be sure that an email address column only contains valid email addresses, or that the customer's name column will never be empty. Constraints like that keep your database organized and helps your application to work properly. +There are several ways to validate the data that goes to the database, like using database native constraints, implementing validations only at the client side or implementing them directly into your models. Each one has pros and cons: -== Credits +* Using database constraints and/or stored procedures makes the validation mechanisms database-dependent and may turn your application into a hard to test and mantain beast. However, if your database is used by other applications, it may be a good idea to use some constraints also at the database level. +* Implementing validations only at the client side can be problematic, specially with web-based applications. Usually this kind of validation is done using javascript, which may be turned off in the user's browser, leading to invalid data getting inside your database. However, if combined with server side validation, client side validation may be useful, since the user can have a faster feedback from the application when trying to save invalid data. +* Using validation directly into your Active Record classes ensures that only valid data gets recorded, while still keeping the validation code in the right place, avoiding breaking the MVC pattern. Since the validation happens on the server side, the user cannot disable it, so it's also safer. It may be a hard and tedious work to implement some of the logic involved in your models' validations, but fear not: Active Record gives you the hability to easily create validations, using several built-in helpers while still allowing you to create your own validation methods. +== How it works +=== When does validation happens? + +There are two kinds of Active Record objects: those that correspond to a row inside your database and those who do not. When you create a fresh object, using the +new+ method, that object does not belong to the database yet. Once you call +save+ upon that object it'll be recorded to it's table. Active Record uses the +new_record?+ instance method to discover if an object is already in the database or not. Consider the following simple and very creative Active Record class: + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base +end +------------------------------------------------------------------ + +We can see how it works by looking at the following script/console output: + +------------------------------------------------------------------ +>> p = Person.new(:name => "John Doe", :birthdate => Date.parse("09/03/1979")) +=> # +>> p.new_record? +=> true +>> p.save +=> true +>> 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. + +=== 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. + +== The declarative validation helpers + +Active Record offers many pre-defined validation helpers that you can use directly inside your class definitions. These helpers create validations rules that are commonly used in most of the applications that you'll write, so you don't need to recreate it everytime, avoiding code duplication, keeping everything organized and boosting your productivity. Everytime a validation fails, an error message is added to the object's +errors+ collection, this message being associated with the field being validated. + +Each helper accepts an arbitrary number of attributes, received as symbols, so with a single line of code you can add the same kind of validation to several attributes. + +All these helpers accept the +:on+ and +:message+ options, which define when the validation should be applied and what message should be added to the +errors+ collection when it fails, respectively. The +:on+ option takes one the values +:save+ (it's the default), +:create+ or +:update+. There is a default error message for each one of the validation helpers. These messages are used when the +:message+ option isn't used. Let's take a look at each one of the available helpers, listed in alphabetic order. + +=== The +validates_acceptance_of+ helper + +Validates that a checkbox has been checked for agreement purposes. It's normally used when the user needs to agree with your application's terms of service, confirm reading some clauses or any similar concept. This validation is very specific to web applications and actually this 'acceptance' does not need to be recorded anywhere in your database (if you don't have a field for it, the helper will just create a virtual attribute). + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service +end +------------------------------------------------------------------ + +The default error message for +validates_acceptance_of+ is "_must be accepted_" + ++validates_acceptance_of+ can receive an +:accept+ option, which determines the value that will be considered acceptance. It defaults to "1", but you can change it. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_acceptance_of :terms_of_service, :accept => 'yes' +end +------------------------------------------------------------------ + + +=== The +validates_associated+ helper + +You should use this helper when your model has associations with other models and they also need to be validated. When you try to save your object, +valid?+ will be called upon each one of the associated objects. + +[source, ruby] +------------------------------------------------------------------ +class Library < ActiveRecord::Base + has_many :books + validates_associated :books +end +------------------------------------------------------------------ + +This validation will work with all the association types. + +CAUTION: Pay attention not to use +validates_associated+ on both ends of your associations, because this will lead to several recursive calls and blow up the method calls' stack. + +The default error message for +validates_associated+ is "_is invalid_". Note that the errors for each failed validation in the associated objects will be set there and not in this model. + +=== The +validates_confirmation_of+ helper + +You should use this helper when you have two text fields that should receive exactly the same content, like when you want to confirm an email address or password. This validation creates a virtual attribute, using the name of the field that has to be confirmed with '_confirmation' appended. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_confirmation_of :email +end +------------------------------------------------------------------ + +In your view template you could use something like +------------------------------------------------------------------ +<%= text_field :person, :email %> +<%= text_field :person, :email_confirmation %> +------------------------------------------------------------------ + +NOTE: This check is performed only if +email_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute (we'll take a look at +validates_presence_of+ later on this guide): + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_confirmation_of :email + validates_presence_of :email_confirmation +end +------------------------------------------------------------------ + +The default error message for +validates_confirmation_of+ is "_doesn't match confirmation_" + +=== The +validates_each+ helper + +This helper validates attributes against a block. It doesn't have a predefined validation function. You should create one using a block, and every attribute passed to +validates_each+ will be tested against it. In the following example, we don't want names and surnames to begin with lower case. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_each :name, :surname do |model, attr, value| + model.errors.add(attr, 'Must start with upper case') if value =~ /^[a-z]/ + end +end +------------------------------------------------------------------ + +The block receives the model, the attribute's name and the attribute's value. If your validation fails, you can add an error message to the model, therefore making it invalid. + +=== The +validates_exclusion_of+ helper + +This helper validates that the attributes' values are not included in a given set. In fact, this set can be any enumerable object. + +[source, ruby] +------------------------------------------------------------------ +class MovieFile < ActiveRecord::Base + validates_exclusion_of :format, :in => %w(mov avi), :message => "Extension %s is not allowed" +end +------------------------------------------------------------------ + +The +validates_exclusion_of+ helper has an option +:in+ that receives the set of values that will not be accepted for the validated attributes. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask. + +The default error message for +validates_exclusion_of+ is "_is not included in the list_". + +=== The +validates_format_of+ helper + +This helper validates the attributes's values by testing if they match a given pattern. This pattern must be specified using a Ruby regular expression, which must be passed through the +:with+ option. + +[source, ruby] +------------------------------------------------------------------ +class Product < ActiveRecord::Base + validates_format_of :description, :with => /^[a-zA-Z]+$/, :message => "Only letters allowed" +end +------------------------------------------------------------------ + +The default error message for +validates_format_of+ is "_is invalid_". + +=== The +validates_inclusion_of+ helper + +This helper validates that the attributes' values are included in a given set. In fact, this set can be any enumerable object. + +[source, ruby] +------------------------------------------------------------------ +class Coffee < ActiveRecord::Base + validates_inclusion_of :size, :in => %w(small medium large), :message => "%s is not a valid size" +end +------------------------------------------------------------------ + +The +validates_inclusion_of+ helper has an option +:in+ that receives the set of values that will be accepted. The +:in+ option has an alias called +:within+ that you can use for the same purpose, if you'd like to. In the previous example we used the +:message+ option to show how we can personalize it with the current attribute's value, through the +%s+ format mask. + +The default error message for +validates_inclusion_of+ is "_is not included in the list_". + +=== The +validates_length_of+ helper + +This helper validates the length of your attribute's value. It can receive a variety of different options, so you can specify length contraints in different ways. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_length_of :name, :minimum => 2 + validates_length_of :bio, :maximum => 500 + validates_length_of :password, :in => 6..20 + validates_length_of :registration_number, :is => 6 +end +------------------------------------------------------------------ + +The possible length constraint options are: + +* +:minimum+ - The attribute cannot have less than the specified length. +* +:maximum+ - The attribute cannot have more than the specified length. +* +:in+ (or +:within+) - The attribute length must be included in a given interval. The value for this option must be a Ruby range. +* +:is+ - The attribute length must be equal to a given value. + +The default error messages depend on the type of length validation being performed. You can personalize these messages, using the +:wrong_length+, +:too_long+ and +:too_short+ options and the +%d+ format mask as a placeholder for the number corresponding to the length contraint being used. You can still use the +:message+ option to specify an error message. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_length_of :bio, :too_long => "you're writing too much. %d characters is the maximum allowed." +end +------------------------------------------------------------------ + +This helper has an alias called +validates_size_of+, it's the same helper with a different name. You can use it if you'd like to. + +=== The +validates_numericallity_of+ helper + +This helper validates that your attributes have only numeric values. By default, it will match an optional sign followed by a integral or floating point number. Using the +:integer_only+ option set to true, you can specify that only integral numbers are allowed. + +If you use +:integer_only+ set to +true+, then it will use the +$$/\A[+\-]?\d+\Z/$$+ regular expression to validate the attribute's value. Otherwise, it will try to convert the value using +Kernel.Float+. + +[source, ruby] +------------------------------------------------------------------ +class Player < ActiveRecord::Base + validates_numericallity_of :points + validates_numericallity_of :games_played, :integer_only => true +end +------------------------------------------------------------------ + +The default error message for +validates_numericallity_of+ is "_is not a number_". + +=== The +validates_presence_of+ helper + +This helper validates that the attributes are not empty. It uses the +blank?+ method to check if the value is either +nil+ or an empty string (if the string has only spaces, it will still be considered empty). + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :name, :login, :email +end +------------------------------------------------------------------ + +NOTE: If you want to be sure that an association is present, you'll need to test if the foreign key used to map the association is present, and not the associated object itself. + +[source, ruby] +------------------------------------------------------------------ +class LineItem < ActiveRecord::Base + belongs_to :order + validates_presence_of :order_id +end +------------------------------------------------------------------ + +NOTE: 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 + +The default error message for +validates_presence_of+ is "_can't be empty_". + +=== The +validates_uniqueness_of+ helper + +This helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint directly into your database, so it may happen that two different database connections create two records with the same value for a column that you wish were unique. To avoid that, you must create an unique index in your database. + +[source, ruby] +------------------------------------------------------------------ +class Account < ActiveRecord::Base + validates_uniqueness_of :email +end +------------------------------------------------------------------ + +The validation happens by performing a SQL query into the model's table, searching for a record where the attribute that must be validated is equal to the value in the object being validated. + +There is a +:scope+ option that you can use to specify other attributes that must be used to define uniqueness: + +[source, ruby] +------------------------------------------------------------------ +class Holiday < ActiveRecord::Base + validates_uniqueness_of :name, :scope => :year, :message => "Should happen once per year" +end +------------------------------------------------------------------ + +There is also a +:case_sensitive+ option that you can use to define if the uniqueness contraint will be case sensitive or not. This option defaults to true. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_uniqueness_of :name, :case_sensitive => false +end +------------------------------------------------------------------ + +The default error message for +validates_uniqueness_of+ is "_has already been taken_". + +== Common validation options + +There are some common options that all the validation helpers can use. Here they are, except for the +:if+ and +:unless+ options, which we'll cover right at the next topic. + +=== The +:allow_nil+ option + +You may use the +:allow_nil+ option everytime you just want to trigger a validation if the value being validated is not +nil+. You may be asking yourself if it makes any sense to use +:allow_nil+ and +validates_presence_of+ together. Well, it does. Remember, validation will be skipped only for +nil+ attributes, but empty strings are not considered +nil+. + +[source, ruby] +------------------------------------------------------------------ +class Coffee < ActiveRecord::Base + validates_inclusion_of :size, :in => %w(small medium large), + :message => "%s is not a valid size", :allow_nil => true +end +------------------------------------------------------------------ + +=== The +:message+ option + +As stated before, the +:message+ option lets you specify the message that will be added to the +errors+ collection when validation fails. When this option is not used, Active Record will use the respective default error message for each validation helper. + +=== The +:on+ option + +As stated before, the +:on+ option lets you specify when the validation should happen. The default behaviour for all the built-in validation helpers is to be ran on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use +:on =$$>$$ :create+ to run the validation only when a new record is created or +:on =$$>$$ :update+ to run the validation only when a record is updated. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_uniqueness_of :email, :on => :create # => it will be possible to update email with a duplicated value + validates_numericallity_of :age, :on => :update # => it will be possible to create the record with a 'non-numerical age' + validates_presence_of :name, :on => :save # => that's the default +end +------------------------------------------------------------------ + +== Conditional validation + +Sometimes it will make sense to validate an object just when a given predicate is satisfied. You can do that by using the +:if+ and +:unless+ options, which can take a symbol, a string or a Ruby Proc. You may use the +:if+ option when you want to specify when the validation *should* happen. If you want to specify when the validation *should not* happen, then you may use the +:unless+ option. + +=== Using a symbol with the +:if+ and +:unless+ options + +You can associated the +:if+ and +:unless+ options with a symbol corresponding to the name of a method that will get called right before validation happens. This is the most commonly used option. + +[source, ruby] +------------------------------------------------------------------ +class Order < ActiveRecord::Base + validates_presence_of :card_number, :if => :paid_with_card? + + def paid_with_card? + payment_type == "card" + end +end +------------------------------------------------------------------ + +=== Using a string with the +:if+ and +:unless+ options + +You can also use a string that will be evaluated using +:eval+ and needs to contain valid Ruby code. You should use this option only when the string represents a really short condition. + +[source, ruby] +------------------------------------------------------------------ +class Person < ActiveRecord::Base + validates_presence_of :surname, :if => "name.nil?" +end +------------------------------------------------------------------ + +=== Using a Proc object with the +:if+ and :+unless+ options + +Finally, it's possible to associate +:if+ and +:unless+ with a Ruby Proc object which will be called. Using a Proc object can give you the hability to write a condition that will be executed only when the validation happens and not when your code is loaded by the Ruby interpreter. This option is best suited when writing short validation methods, usually one-liners. + +[source, ruby] +------------------------------------------------------------------ +class Account < ActiveRecord::Base + validates_confirmation_of :password, :unless => Proc.new { |a| a.password.blank? } +end +------------------------------------------------------------------ + +== Writing your own validation methods + +When the built-in validation helpers are not enough for your needs, you can write your own validation methods, by implementing one or more of the +validate+, +validate_on_create+ or +validate_on_update+ methods. As the names of the methods states, the right method to implement depends on when you want the validations to be ran. The meaning of valid is still the same: to make an object invalid you just need to add a message to it's +errors+ collection. + +[source, ruby] +------------------------------------------------------------------ +class Invoice < ActiveRecord::Base + def validate_on_create + errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today + end +end +------------------------------------------------------------------ + +If your validation rules are too complicated and you want to break it in small methods, you can implement all of them and call one of +validate+, +validate_on_create+ or +validate_on_update+ methods, passing it the symbols for the methods' names. + +[source, ruby] +------------------------------------------------------------------ +class Invoice < ActiveRecord::Base + validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_more_than_total_value + + def expiration_date_cannot_be_in_the_past + errors.add(:expiration_date, "can't be in the past") if !expiration_date.blank? and expiration_date < Date.today + end + + def discount_cannot_be_greater_than_total_value + errors.add(:discount, "can't be greater than total value") unless discount <= total_value + end +end +------------------------------------------------------------------ == Changelog diff --git a/railties/doc/guides/source/caching_with_rails.txt b/railties/doc/guides/source/caching_with_rails.txt index d5b8b03669..e680b79d55 100644 --- a/railties/doc/guides/source/caching_with_rails.txt +++ b/railties/doc/guides/source/caching_with_rails.txt @@ -10,59 +10,65 @@ 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 Base.perform_caching is set to true for your -environment. +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. [source, ruby] ----------------------------------------------------- -Base.perform_caching = true +config.action_controller.perform_caching = true ----------------------------------------------------- === Page Caching Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver, without ever having to go through the -Rails stack at all. Obviously, this is super fast. Unfortunately, it can't be +Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with. So, how do you enable this super-fast cache behavior? Simple, let's say you -have a controller called ProductController and a 'list' action that lists all +have a controller called ProductsController and a 'list' action that lists all the products [source, ruby] ----------------------------------------------------- -class ProductController < ActionController +class ProductsController < ActionController - cache_page :list + caches_page :index - def list; end + def index; end end ----------------------------------------------------- -The first time anyone requestsion products/list, Rails will generate a file -called list.html and the webserver will then look for that file before it -passes the next request for products/list to your Rails application. +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 +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 Base.cache_public_directory - -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 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 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 Base.page_cache_extension +configuration setting ActionController::Base.page_cache_extension. In order to expire this page when a new product is added we could extend our example controler like this: [source, ruby] ----------------------------------------------------- -class ProductController < ActionController +class ProductsController < ActionController - cache_page :list + caches_page :list def list; end @@ -80,11 +86,11 @@ to expire cached objects when things change. This is covered in the section on S === Action Caching -One of the issues with page caching is that you cannot use it for pages that +One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so -that before_filters can be run on it before the cache is served, so that +that before filters can be run on it before the cache is served, so that authentication and other restrictions can be used while still serving the result of the output from a cached copy. @@ -95,10 +101,10 @@ object, but still cache those pages: [source, ruby] ----------------------------------------------------- -class ProductController < ActionController +class ProductsController < ActionController before_filter :authenticate, :only => [ :edit, :create ] - cache_page :list + caches_page :list caches_action :edit def list; end @@ -120,7 +126,7 @@ or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2. -[More: more examples? Walk-through of action caching from request to response? +[More: more examples? Walk-through of Action Caching from request to response? Description of Rake tasks to clear cached files? Show example of subdomain caching? Talk about :cache_path, :if and assing blocks/Procs to expire_action?] @@ -132,15 +138,15 @@ a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired -differently Rails provides a mechanism called Fragment caching. +differently Rails provides a mechanism called Fragment Caching. -Fragment caching allows a fragment of view logic to be wrapped in a cache +Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in. -As an example, if you wanted to show all the orders placed on your website in -real time and didn't want to cache that part of the page, but did want to -cache the part of the page which lists all products available, you could use -this piece of code: +As an example, if you wanted to show all the orders placed on your website +in real time and didn't want to cache that part of the page, but did want +to cache the part of the page which lists all products available, you +could use this piece of code: [source, ruby] ----------------------------------------------------- @@ -158,7 +164,7 @@ 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_path to the cache call: +want to cache multiple fragments per action, you should provide an action_suffix to the cache call: [source, ruby] ----------------------------------------------------- @@ -225,10 +231,10 @@ following: [source, ruby] ----------------------------------------------------- -class ProductController < ActionController +class ProductsController < ActionController before_filter :authenticate, :only => [ :edit, :create ] - cache_page :list + caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] @@ -257,10 +263,10 @@ For example: [source, ruby] ----------------------------------------------------- -class ProductController < ActionController +class ProductsController < ActionController before_filter :authenticate, :only => [ :edit, :create ] - cache_page :list + caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] diff --git a/railties/doc/guides/source/command_line.txt b/railties/doc/guides/source/command_line.txt new file mode 100644 index 0000000000..5f7c6ceff5 --- /dev/null +++ b/railties/doc/guides/source/command_line.txt @@ -0,0 +1,147 @@ +A Guide to The Rails Command Line +================================= + +Rails comes with every command line tool you'll need to + +* Create a Rails application +* Generate models, controllers, database migrations, and unit tests +* Start a development server +* Mess with objects through an interactive shell +* Profile and benchmark your new creation + +... and much, much more! (Buy now!) + +This tutorial assumes you have basic Rails knowledge from reading the Getting Started with Rails Guide. + +== Command Line Basics == + +There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are: + +* console +* server +* rake +* generate +* rails + +Let's create a simple Rails application to step through each of these commands in context. + +=== rails === + +The first thing we'll want to do is create a new Rails application by running the `rails` command after installing Rails. + +NOTE: You know you need the rails gem installed by typing `gem install rails` first, right? Okay, okay, just making sure. + +[source,shell] +------------------------------------------------------ +$ rails commandsapp + + create + create app/controllers + create app/helpers + create app/models + ... + ... + create log/production.log + create log/development.log + create log/test.log +------------------------------------------------------ + +Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box. + +NOTE: This output will seem very familiar when we get to the `generate` command. Creepy foreshadowing! + +=== server === + +Let's try it! The `server` command launches a small web server written in Ruby named WEBrick which was also installed when you installed Rails. You'll use this any time you want to view your work through a web browser. + +NOTE: WEBrick isn't your only option for serving Rails. We'll get to that in a later section. [XXX: which section] + +Here we'll flex our `server` command, which without any prodding of any kind will run our new shiny Rails app: + +[source,shell] +------------------------------------------------------ +$ cd commandsapp +$ ./script/server +=> Booting WEBrick... +=> Rails 2.2.0 application started on http://0.0.0.0:3000 +=> Ctrl-C to shutdown server; call with --help for options +[2008-11-04 10:11:38] INFO WEBrick 1.3.1 +[2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux] +[2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000 +------------------------------------------------------ + +WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait. + +See? Cool! It doesn't do much yet, but we'll change that. + +=== generate === + +The `generate` command uses templates to create a whole lot of things. You can always find out what's available by running `generate` by itself. Let's do that: + +[source,shell] +------------------------------------------------------ +$ ./script/generate +Usage: ./script/generate generator [options] [args] + +... +... + +Installed Generators + Builtin: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration + +... +... +------------------------------------------------------ + +NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own! + +Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right? + +Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator: + +NOTE: All Rails console utilities have help text. For commands that require a lot of input to run correctly, you can just try the command without any parameters (like `rails` or `./script/generate`). For others, you can try adding `--help` or `-h` to the end, as in `./script/server --help`. + +[source,shell] +------------------------------------------------------ +$ ./script/generate controller +Usage: ./script/generate controller ControllerName [options] + +... +... + +Example: + `./script/generate controller CreditCard open debit credit close` + + Credit card controller with URLs like /credit_card/debit. + Controller: app/controllers/credit_card_controller.rb + Views: app/views/credit_card/debit.html.erb [...] + Helper: app/helpers/credit_card_helper.rb + Test: test/functional/credit_card_controller_test.rb + +Modules Example: + `./script/generate controller 'admin/credit_card' suspend late_fee` + + Credit card admin controller with URLs /admin/credit_card/suspend. + Controller: app/controllers/admin/credit_card_controller.rb + Views: app/views/admin/credit_card/debit.html.erb [...] + Helper: app/helpers/admin/credit_card_helper.rb + Test: test/functional/admin/credit_card_controller_test.rb +------------------------------------------------------ + +Ah, the controller generator is expecting parameters in the form of `generate controller ControllerName action1 action2`. Let's make a `Greetings` controller with an action of *hello*, which will say something nice to us. + +[source,shell] +------------------------------------------------------ +$ ./script/generate controller Greeting hello + exists app/controllers/ + exists app/helpers/ + create app/views/greeting + exists test/functional/ + create app/controllers/greetings_controller.rb + create test/functional/greetings_controller_test.rb + create app/helpers/greetings_helper.rb + create app/views/greetings/hello.html.erb +------------------------------------------------------ + +Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file. All from one command! + diff --git a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt index 12d40deb18..de116af7db 100644 --- a/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt +++ b/railties/doc/guides/source/creating_plugins/acts_as_yaffle.txt @@ -1,32 +1,40 @@ -== Add an `acts_as_yaffle` method to ActiveRecord == +== Add an `acts_as_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* [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end - class ActsAsYaffleTest < Test::Unit::TestCase end ------------------------------------------------------ +*vendor/plugins/yaffle/lib/yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/lib/acts_as_yaffle.rb +require 'yaffle/acts_as_yaffle' +------------------------------------------------------ + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* +[source, ruby] +------------------------------------------------------ module Yaffle + # your code will go here end ------------------------------------------------------ -One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: +Note that after requiring 'acts_as_yaffle' you also have to include it into ActiveRecord::Base so that your plugin methods will be available to the rails models. + +One of the most common plugin patterns for 'acts_as_yaffle' plugins is to structure your file like so: + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* [source, ruby] ------------------------------------------------------ @@ -50,52 +58,45 @@ end With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`). -Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. +=== Add a class method === -Back in your `acts_as_yaffle` file, update ClassMethods like so: +This plugin will expect that you've added a method to your model named 'last_squawk'. However, the plugin users might have already defined a method on their model named 'last_squawk' that they use for something else. This plugin will allow the name to be changed by adding a class method called 'yaffle_text_field'. -[source, ruby] ------------------------------------------------------- -module ClassMethods - def acts_as_yaffle(options = {}) - send :include, InstanceMethods - end -end ------------------------------------------------------- +To start out, write a failing test that shows the behavior you'd like: -Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + class ActsAsYaffleTest < Test::Unit::TestCase + load_schema + def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end - - def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end end ------------------------------------------------------ To make these tests pass, you could modify your `acts_as_yaffle` file like so: +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - module Yaffle def self.included(base) base.send :extend, ClassMethods @@ -103,70 +104,66 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_field self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods end end - - module InstanceMethods - end end + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ -Now you can add tests for the instance methods, and the instance method itself: +=== Add an instance method === + +This plugin will add a method named 'squawk' to any Active Record objects that call 'acts_as_yaffle'. The 'squawk' method will simply set the value of one of the fields in the database. + +To start out, write a failing test that shows the behavior you'd like: + +*vendor/plugins/yaffle/test/acts_as_yaffle_test.rb* [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - require File.dirname(__FILE__) + '/test_helper.rb' +class Hickwall < ActiveRecord::Base + acts_as_yaffle +end + +class Wickwall < ActiveRecord::Base + acts_as_yaffle :yaffle_text_field => :last_tweet +end + class ActsAsYaffleTest < Test::Unit::TestCase + load_schema def test_a_hickwalls_yaffle_text_field_should_be_last_squawk assert_equal "last_squawk", Hickwall.yaffle_text_field end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_squawk + def test_a_wickwalls_yaffle_text_field_should_be_last_tweet assert_equal "last_tweet", Wickwall.yaffle_text_field end - def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - + def test_hickwalls_squawk_should_populate_last_squawk hickwall = Hickwall.new hickwall.squawk("Hello World") assert_equal "squawk! Hello World", hickwall.last_squawk - end - def test_hickwalls_squawk_should_populate_last_squawked_at - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal Date.today, hickwall.last_squawked_at - end - - def test_wickwalls_squawk_should_populate_last_tweet - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal "squawk! Hello World", wickwall.last_tweet - end + end + def test_wickwalls_squawk_should_populate_last_tweeted_at wickwall = Wickwall.new wickwall.squawk("Hello World") - assert_equal Date.today, wickwall.last_tweeted_at - end + assert_equal "squawk! Hello World", wickwall.last_tweet + end end ------------------------------------------------------ +Run this test to make sure the last two tests fail, then update 'acts_as_yaffle.rb' to look like this: + +*vendor/plugins/yaffle/lib/yaffle/acts_as_yaffle.rb* + [source, ruby] ------------------------------------------------------ -# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - module Yaffle def self.included(base) base.send :extend, ClassMethods @@ -174,9 +171,8 @@ module Yaffle module ClassMethods def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field + cattr_accessor :yaffle_text_field self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s send :include, InstanceMethods end end @@ -184,10 +180,12 @@ module Yaffle module InstanceMethods def squawk(string) write_attribute(self.class.yaffle_text_field, string.to_squawk) - write_attribute(self.class.yaffle_date_field, Date.today) end end end + +ActiveRecord::Base.send :include, Yaffle ------------------------------------------------------ -Note the use of `write_attribute` to write to the field in model. +.Editor's note: +NOTE: The use of `write_attribute` to write to the field in model is just one example of how a plugin can interact with the model, and will not always be the right method to use. For example, you could also use `send("#{self.class.yaffle_text_field}=", string.to_squawk)`. diff --git a/railties/doc/guides/source/creating_plugins/basics.markdown b/railties/doc/guides/source/creating_plugins/basics.markdown deleted file mode 100644 index f59e8728d7..0000000000 --- a/railties/doc/guides/source/creating_plugins/basics.markdown +++ /dev/null @@ -1,861 +0,0 @@ -Creating Plugin Basics -==================== - -Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. - -In this tutorial you will learn how to create a plugin that includes: - -Core Extensions - extending String: - - # Anywhere - "hello".squawk # => "squawk! hello! squawk!" - -An `acts_as_yaffle` method for Active Record models that adds a "squawk" method: - - class Hickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_sang_at - end - - Hickwall.new.squawk("Hello World") - -A view helper that will print out squawking info: - - squawk_info_for(@hickwall) - -A generator that creates a migration to add squawk columns to a model: - - script/generate yaffle hickwall - -A custom generator command: - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end - end - end - -A custom route method: - - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - -In addition you'll learn how to: - -* test your plugins -* work with init.rb, how to store model, views, controllers, helpers and even other plugins in your plugins -* create documentation for your plugin. -* write custom rake tasks in your plugin - -Create the basic app ---------------------- - -In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: - -> The following instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - rails plugin_demo - cd plugin_demo - script/generate scaffold bird name:string - rake db:migrate - script/server - -Then navigate to [http://localhost:3000/birds](http://localhost:3000/birds). Make sure you have a functioning rails app before continuing. - -Create the plugin ------------------------ - -The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either CamelCased or under_scored, as an argument. Pass --with-generator to add an example generator also. - -This creates a plugin in vendor/plugins including an init.rb and README as well as standard lib, task, and test directories. - -Examples: - - ./script/generate plugin BrowserFilters - ./script/generate plugin BrowserFilters --with-generator - -Later in the plugin we will create a generator, so go ahead and add the --with-generator option now: - - script/generate plugin yaffle --with-generator - -You should see the following output: - - create vendor/plugins/yaffle/lib - create vendor/plugins/yaffle/tasks - create vendor/plugins/yaffle/test - create vendor/plugins/yaffle/README - create vendor/plugins/yaffle/MIT-LICENSE - create vendor/plugins/yaffle/Rakefile - create vendor/plugins/yaffle/init.rb - create vendor/plugins/yaffle/install.rb - create vendor/plugins/yaffle/uninstall.rb - create vendor/plugins/yaffle/lib/yaffle.rb - create vendor/plugins/yaffle/tasks/yaffle_tasks.rake - create vendor/plugins/yaffle/test/core_ext_test.rb - create vendor/plugins/yaffle/generators - create vendor/plugins/yaffle/generators/yaffle - create vendor/plugins/yaffle/generators/yaffle/templates - create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - create vendor/plugins/yaffle/generators/yaffle/USAGE - -For this plugin you won't need the file vendor/plugins/yaffle/lib/yaffle.rb so you can delete that. - - rm vendor/plugins/yaffle/lib/yaffle.rb - -> Editor's note: many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"` -> If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean - -Setup the plugin for testing ------------------------- - -Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - -* A database.yml file with all of your connection strings -* A schema.rb file with your table definitions -* A test helper that sets up the database before your tests - -For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: - - # File: vendor/plugins/yaffle/test/database.yml - - sqlite: - :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db - sqlite3: - :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db - postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: yaffle_plugin_test - - # File: vendor/plugins/yaffle/test/test_helper.rb - - ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end - end - - # File: vendor/plugins/yaffle/test/test_helper.rb - - ENV['RAILS_ENV'] = 'test' - ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - - require 'test/unit' - require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - - config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) - ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - - db_adapter = ENV['DB'] - - # no db passed, try one of these fine config-free DBs before bombing. - db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - - if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." - end - - ActiveRecord::Base.establish_connection(config[db_adapter]) - - load(File.dirname(__FILE__) + "/schema.rb") - - require File.dirname(__FILE__) + '/../init.rb' - - class Hickwall < ActiveRecord::Base - acts_as_yaffle - end - - class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at - end - -Add a `to_squawk` method to String ------------------------ - -To update a core class you will have to: - -* Write tests for the desired functionality -* Create a file for the code you wish to use -* Require that file from your init.rb - -Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from init.rb. The file you are going to add for this tutorial is `lib/core_ext.rb` - -First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: - - # File: vendor/plugins/yaffle/test/core_ext_test.rb - - require 'test/unit' - - class CoreExtTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end - end - -Start off by removing the default test, and adding a require statement for your test helper. - - # File: vendor/plugins/yaffle/test/core_ext_test.rb - - require 'test/unit' - require File.dirname(__FILE__) + '/test_helper.rb' - - class CoreExtTest < Test::Unit::TestCase - end - -Navigate to your plugin directory and run `rake test` - - cd vendor/plugins/yaffle - rake test - -Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file `lib/core_ext.rb` and re-run the tests. You should see a different error message: - - 1.) Failure ... - No tests were specified - -Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word "squawk! ". The test will look something like this: - - # File: vendor/plugins/yaffle/init.rb - - class CoreExtTest < Test::Unit::TestCase - def test_string_should_respond_to_squawk - assert_equal true, "".respond_to?(:to_squawk) - end - def test_string_prepend_empty_strings_with_the_word_squawk - assert_equal "squawk!", "".to_squawk - end - def test_string_prepend_non_empty_strings_with_the_word_squawk - assert_equal "squawk! Hello World", "Hello World".to_squawk - end - end - - # File: vendor/plugins/yaffle/init.rb - - require "core_ext" - - # File: vendor/plugins/yaffle/lib/core_ext.rb - - String.class_eval do - def to_squawk - "squawk! #{self}".strip - end - end - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - - script/console - >> "Hello World".to_squawk - => "squawk! Hello World" - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. - -Add an `acts_as_yaffle` method to ActiveRecord ------------------------ - -A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a squawk method to your models. - -To keep things clean, create a new test file called `acts_as_yaffle_test.rb` in your plugin's test directory and require your test helper. - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class Hickwall < ActiveRecord::Base - acts_as_yaffle - end - - class ActsAsYaffleTest < Test::Unit::TestCase - end - - # File: vendor/plugins/lib/acts_as_yaffle.rb - - module Yaffle - end - -One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so: - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - # any method placed here will apply to classes, like Hickwall - def acts_as_something - send :include, InstanceMethods - end - end - - module InstanceMethods - # any method placed here will apply to instaces, like @hickwall - end - end - -With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`). - -Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail. - -Back in your `acts_as_yaffle` file, update ClassMethods like so: - - module ClassMethods - def acts_as_yaffle(options = {}) - send :include, InstanceMethods - end - end - -Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this: - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class ActsAsYaffleTest < Test::Unit::TestCase - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - def test_a_wickwalls_yaffle_text_field_should_be_last_tweet - assert_equal "last_tweet", Wickwall.yaffle_text_field - end - def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - end - -To make these tests pass, you could modify your `acts_as_yaffle` file like so: - - # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods - end - end - - module InstanceMethods - end - end - -Now you can add tests for the instance methods, and the instance method itself: - - # File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - - class ActsAsYaffleTest < Test::Unit::TestCase - - def test_a_hickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_squawk", Hickwall.yaffle_text_field - end - def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_squawked_at", Hickwall.yaffle_date_field - end - - def test_a_wickwalls_yaffle_text_field_should_be_last_squawk - assert_equal "last_tweet", Wickwall.yaffle_text_field - end - def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at - assert_equal "last_tweeted_at", Wickwall.yaffle_date_field - end - - def test_hickwalls_squawk_should_populate_last_squawk - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal "squawk! Hello World", hickwall.last_squawk - end - def test_hickwalls_squawk_should_populate_last_squawked_at - hickwall = Hickwall.new - hickwall.squawk("Hello World") - assert_equal Date.today, hickwall.last_squawked_at - end - - def test_wickwalls_squawk_should_populate_last_tweet - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal "squawk! Hello World", wickwall.last_tweet - end - def test_wickwalls_squawk_should_populate_last_tweeted_at - wickwall = Wickwall.new - wickwall.squawk("Hello World") - assert_equal Date.today, wickwall.last_tweeted_at - end - end - - # File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb - - module Yaffle - def self.included(base) - base.send :extend, ClassMethods - end - - module ClassMethods - def acts_as_yaffle(options = {}) - cattr_accessor :yaffle_text_field, :yaffle_date_field - self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s - self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s - send :include, InstanceMethods - end - end - - module InstanceMethods - def squawk(string) - write_attribute(self.class.yaffle_text_field, string.to_squawk) - write_attribute(self.class.yaffle_date_field, Date.today) - end - end - end - -Note the use of write_attribute to write to the field in model. - -Create a view helper ------------------------ - -Creating a view helper is a 3-step process: - -* Add an appropriately named file to the lib directory -* Require the file and hooks in init.rb -* Write the tests - -First, create the test to define the functionality you want: - - # File: vendor/plugins/yaffle/test/view_helpers_test.rb - - require File.dirname(__FILE__) + '/test_helper.rb' - include YaffleViewHelper - - class ViewHelpersTest < Test::Unit::TestCase - def test_squawk_info_for_should_return_the_text_and_date - time = Time.now - hickwall = Hickwall.new - hickwall.last_squawk = "Hello World" - hickwall.last_squawked_at = time - assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) - end - end - -Then add the following statements to init.rb: - - # File: vendor/plugins/yaffle/init.rb - - require "view_helpers" - ActionView::Base.send :include, YaffleViewHelper - -Then add the view helpers file and - - # File: vendor/plugins/yaffle/lib/view_helpers.rb - - module YaffleViewHelper - def squawk_info_for(yaffle) - returning "" do |result| - result << yaffle.read_attribute(yaffle.class.yaffle_text_field) - result << ", " - result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s - end - end - end - -You can also test this in script/console by using the "helper" method: - - script/console - >> helper.squawk_info_for(@some_yaffle_instance) - -Create a migration generator ------------------------ - -When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin. - -We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial. - -Type: - - script/generate - -You should see the line: - - Plugins (vendor/plugins): yaffle - -When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: - - Description: - Creates a migration that adds yaffle squawk fields to the given model - - Example: - ./script/generate yaffle hickwall - - This will create: - db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall - -Now you can add code to your generator: - - # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - record do |m| - m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, - :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } - end - end - - private - def custom_file_name - custom_name = class_name.underscore.downcase - custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names - end - - def yaffle_local_assigns - returning(assigns = {}) do - assigns[:migration_action] = "add" - assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}" - assigns[:table_name] = custom_file_name - assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")] - assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime") - end - end - end - -Note that you need to be aware of whether or not table names are pluralized. - -This does a few things: - -* Reuses the built in rails migration_template method -* Reuses the built-in rails migration template - -When you run the generator like - - script/generate yaffle bird - -You will see a new file: - - # File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb - - class AddYaffleFieldsToBirds < ActiveRecord::Migration - def self.up - add_column :birds, :last_squawk, :string - add_column :birds, :last_squawked_at, :datetime - end - - def self.down - remove_column :birds, :last_squawked_at - remove_column :birds, :last_squawk - end - end - -Add a custom generator command ------------------------- - -You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: - -1. Add the require and hook statements to init.rb -2. Create the commands - creating 3 sets, Create, Destroy, List -3. Add the method to your generator - -Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: - - # File: vendor/plugins/yaffle/init.rb - - require "commands" - Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create - Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy - Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List - - # File: vendor/plugins/yaffle/lib/commands.rb - - require 'rails_generator' - require 'rails_generator/commands' - - module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end - end - - # File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt - - Yaffle is a bird - - # File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - - class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end - end - end - -This example just uses the built-in "file" method, but you could do anything that ruby allows. - -Add a Custom Route ------------------------- - -Testing routes in plugins can be complex, especially if the controllers are also in the plugin itself. Jamis Buck showed a great example of this in [http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2](http://weblog.jamisbuck.org/2006/10/26/monkey-patching-rails-extending-routes-2) - - # File: vendor/plugins/yaffle/test/routing_test.rb - - require "#{File.dirname(__FILE__)}/test_helper" - - class RoutingTest < Test::Unit::TestCase - - def setup - ActionController::Routing::Routes.draw do |map| - map.yaffles - end - end - - def test_yaffles_route - assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index" - end - - private - - # yes, I know about assert_recognizes, but it has proven problematic to - # use in these tests, since it uses RouteSet#recognize (which actually - # tries to instantiate the controller) and because it uses an awkward - # parameter order. - def assert_recognition(method, path, options) - result = ActionController::Routing::Routes.recognize_path(path, :method => method) - assert_equal options, result - end - end - - # File: vendor/plugins/yaffle/init.rb - - require "routing" - ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions - - # File: vendor/plugins/yaffle/lib/routing.rb - - module Yaffle #:nodoc: - module Routing #:nodoc: - module MapperExtensions - def yaffles - @set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"}) - end - end - end - end - - # File: config/routes.rb - - ActionController::Routing::Routes.draw do |map| - ... - map.yaffles - end - -You can also see if your routes work by running `rake routes` from your app directory. - -Generate RDoc Documentation ------------------------ - -Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. - -The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are: - -* Your name -* How to install -* How to add the functionality to the app (several examples of common use cases) -* Warning, gotchas or tips that might help save users time - -Once your README is solid, go through and add rdoc comments to all of the methods that developers will use. - -Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users. - -Once your comments are good to go, navigate to your plugin directory and run - - rake rdoc - -Work with init.rb ------------------------- - -The plugin initializer script init.rb is invoked via `eval` (not require) so it has slightly different behavior. - -If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this: - -The first way is to explicitly define the top-level module space for all modules and classes, like ::Hash - - # File: vendor/plugins/yaffle/init.rb - - class ::Hash - def is_a_special_hash? - true - end - end - -OR you can use `module_eval` or `class_eval` - - # File: vendor/plugins/yaffle/init.rb - - Hash.class_eval do - def is_a_special_hash? - true - end - end - -Store models, views, helpers, and controllers in your plugins ------------------------- - -You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: - - # File: vendor/plugins/yaffle/init.rb - - %w{ models controllers helpers }.each do |dir| - path = File.join(directory, 'lib', dir) - $LOAD_PATH << path - Dependencies.load_paths << path - Dependencies.load_once_paths.delete(path) - end - -Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. - -Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. - -Write custom rake tasks in your plugin -------------------------- - -When you created the plugin with the built-in rails generator, it generated a rake file for you in `vendor/plugins/yaffle/tasks/yaffle.rake`. Any rake task you add here will be available to the app. - -Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: - - # File: vendor/plugins/yaffle/tasks/yaffle.rake - - namespace :yaffle do - desc "Prints out the word 'Yaffle'" - task :squawk => :environment do - puts "squawk!" - end - end - -When you run `rake -T` from your plugin you will see - - yaffle:squawk "Prints out..." - -You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up. - -Store plugins in alternate locations -------------------------- - -You can store plugins wherever you want - you just have to add those plugins to the plugins path in environment.rb - -Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now. - -You can even store plugins inside of other plugins for complete plugin madness! - - config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins") - -Create your own Plugin Loaders and Plugin Locators ------------------------- - -If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial. - -Use Custom Plugin Generators ------------------------- - -If you are an RSpec fan, you can install the `rspec_plugin_generator`, which will generate the spec folder and database for you. - -[http://github.com/pat-maddox/rspec-plugin-generator/tree/master](http://github.com/pat-maddox/rspec-plugin-generator/tree/master) - -References ------------------------- - -* [http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i](http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i) -* [http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii](http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii) -* [http://github.com/technoweenie/attachment_fu/tree/master](http://github.com/technoweenie/attachment_fu/tree/master) -* [http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html](http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html) - -Appendices ------------------------- - -The final plugin should have a directory structure that looks something like this: - - |-- MIT-LICENSE - |-- README - |-- Rakefile - |-- generators - | `-- yaffle - | |-- USAGE - | |-- templates - | | `-- definition.txt - | `-- yaffle_generator.rb - |-- init.rb - |-- install.rb - |-- lib - | |-- acts_as_yaffle.rb - | |-- commands.rb - | |-- core_ext.rb - | |-- routing.rb - | `-- view_helpers.rb - |-- tasks - | `-- yaffle_tasks.rake - |-- test - | |-- acts_as_yaffle_test.rb - | |-- core_ext_test.rb - | |-- database.yml - | |-- debug.log - | |-- routing_test.rb - | |-- schema.rb - | |-- test_helper.rb - | `-- view_helpers_test.rb - |-- uninstall.rb - `-- yaffle_plugin.sqlite3.db diff --git a/railties/doc/guides/source/creating_plugins/controllers.txt b/railties/doc/guides/source/creating_plugins/controllers.txt new file mode 100644 index 0000000000..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/core_ext.txt b/railties/doc/guides/source/creating_plugins/core_ext.txt new file mode 100644 index 0000000000..ca8efc3df1 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/core_ext.txt @@ -0,0 +1,123 @@ +== 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 === + +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 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* + +[source, ruby] +-------------------------------------------------------- +require "yaffle/core_ext" +-------------------------------------------------------- + +Finally, create the 'core_ext.rb' file and add the 'to_squawk' method: + +*vendor/plugins/yaffle/lib/yaffle/core_ext.rb* + +[source, ruby] +-------------------------------------------------------- +String.class_eval do + def to_squawk + "squawk! #{self}".strip + end +end +-------------------------------------------------------- + +To test that your method does what it says it does, run the unit tests with `rake` from your plugin directory. To see this in action, fire up a console and start squawking: + +-------------------------------------------------------- +$ ./script/console +>> "Hello World".to_squawk +=> "squawk! Hello World" +-------------------------------------------------------- + +=== Working with init.rb === + +When rails loads plugins it looks for the file named init.rb. 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/custom_generator.txt b/railties/doc/guides/source/creating_plugins/custom_generator.txt deleted file mode 100644 index 6d9613ea01..0000000000 --- a/railties/doc/guides/source/creating_plugins/custom_generator.txt +++ /dev/null @@ -1,69 +0,0 @@ -== Add a custom generator command == - -You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps: - - 1. Add the require and hook statements to init.rb. - 2. Create the commands - creating 3 sets, Create, Destroy, List. - 3. Add the method to your generator. - -Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example: - -[source, ruby] ------------------------------------------------------------ -# File: vendor/plugins/yaffle/init.rb -require "commands" -Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create -Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy -Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List ------------------------------------------------------------ - -[source, ruby] ------------------------------------------------------------ -# File: vendor/plugins/yaffle/lib/commands.rb - -require 'rails_generator' -require 'rails_generator/commands' - -module Yaffle #:nodoc: - module Generator #:nodoc: - module Commands #:nodoc: - module Create - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module Destroy - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - - module List - def yaffle_definition - file("definition.txt", "definition.txt") - end - end - end - end -end ------------------------------------------------------------ - ------------------------------------------------------------ -# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt - -Yaffle is a bird ------------------------------------------------------------ - -[source, ruby] ------------------------------------------------------------ -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end ------------------------------------------------------------ - -This example just uses the built-in "file" method, but you could do anything that Ruby allows. diff --git a/railties/doc/guides/source/creating_plugins/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/gem.txt b/railties/doc/guides/source/creating_plugins/gem.txt new file mode 100644 index 0000000000..93f5e0ee89 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/gem.txt @@ -0,0 +1 @@ +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_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/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 f2ed6ed8bb..19484e2830 100644 --- a/railties/doc/guides/source/creating_plugins/index.txt +++ b/railties/doc/guides/source/creating_plugins/index.txt @@ -1,81 +1,49 @@ The Basics of Creating Rails Plugins ==================================== -Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. - -In this tutorial you will learn how to create a plugin that includes: - - * Core Extensions - extending String with a `to_squawk` method: -+ -[source, ruby] -------------------------------------------- -# Anywhere -"hello!".to_squawk # => "squawk! hello!" -------------------------------------------- - -* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method: -+ -[source, ruby] -------------------------------------------- -class Hickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_sang_at -end - -Hickwall.new.squawk("Hello World") -------------------------------------------- - -* A view helper that will print out squawking info: -+ -[source, ruby] -------------------------------------------- -squawk_info_for(@hickwall) -------------------------------------------- - -* A generator that creates a migration to add squawk columns to a model: -+ -------------------------------------------- -script/generate yaffle hickwall -------------------------------------------- - -* A custom generator command: -+ -[source, ruby] -------------------------------------------- -class YaffleGenerator < Rails::Generator::NamedBase - def manifest - m.yaffle_definition - end -end -------------------------------------------- - -* A custom route method: -+ -[source, ruby] -------------------------------------------- -ActionController::Routing::Routes.draw do |map| - map.yaffles -end -------------------------------------------- - -In addition you'll learn how to: - - * test your plugins. - * work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins. - * create documentation for your plugin. - * write custom Rake tasks in your plugin. - - -include::preparation.txt[] - -include::string_to_squawk.txt[] +A Rails plugin is either an extension or a modification of the core framework. Plugins provide: + + * a way for developers to share bleeding-edge ideas without hurting the stable code base + * a segmented architecture so that units of code can be fixed or updated on their own release schedule + * an outlet for the core developers so that they don’t have to include every cool new feature under the sun + +After reading this guide you should be familiar with: + + * Creating a plugin from scratch + * Writing and running tests for the plugin + * Storing models, views, controllers, helpers and even other plugins in your plugins + * Writing generators + * Writing custom Rake tasks in your plugin + * Generating RDoc documentation for your plugin + * Avoiding common pitfalls with 'init.rb' + +This guide describes how to build a test-driven plugin that will: + + * Extend core ruby classes like Hash and String + * Add methods to ActiveRecord::Base in the tradition of the 'acts_as' plugins + * Add a view helper that can be used in erb templates + * Add a new generator that will generate a migration + * Add a custom generator command + * A custom route method that can be used in routes.rb + +For the purpose of this guide pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness. First, you need to get setup for development. -include::acts_as_yaffle.txt[] -include::view_helper.txt[] +include::test_setup.txt[] + +include::core_ext.txt[] + +include::acts_as_yaffle.txt[] include::migration_generator.txt[] -include::custom_generator.txt[] +include::generator_method.txt[] + +include::models.txt[] + +include::controllers.txt[] + +include::helpers.txt[] include::custom_route.txt[] diff --git a/railties/doc/guides/source/creating_plugins/migration_generator.txt b/railties/doc/guides/source/creating_plugins/migration_generator.txt index 598a0c8437..f4fc32481c 100644 --- a/railties/doc/guides/source/creating_plugins/migration_generator.txt +++ b/railties/doc/guides/source/creating_plugins/migration_generator.txt @@ -1,42 +1,79 @@ -== Create a migration generator == +== Create a 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: -When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this: + * 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] ------------------------------------------------------------------ -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 GeneratorTest < 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* [source, ruby] ------------------------------------------------------------------ -# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb - class YaffleGenerator < Rails::Generator::NamedBase def manifest record do |m| m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns, :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}" - } + } end end @@ -52,38 +89,68 @@ 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 +and you will see a new file: -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 - 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/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 eb127f73ca..e328c04a79 100644 --- a/railties/doc/guides/source/creating_plugins/odds_and_ends.txt +++ b/railties/doc/guides/source/creating_plugins/odds_and_ends.txt @@ -1,36 +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. There are 2 ways around this: - -The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`: - -[source, ruby] ---------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -class ::Hash - def is_a_special_hash? - true - end -end ---------------------------------------------------- - -OR you can use `module_eval` or `class_eval`: - ---------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -Hash.class_eval do - def is_a_special_hash? - true - end -end ---------------------------------------------------- - === Generate RDoc Documentation === Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy. @@ -50,38 +19,16 @@ Once your comments are good to go, navigate to your plugin directory and run: rake rdoc - -=== Store models, views, helpers, and controllers in your plugins === - -You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path: - -[source, ruby] ---------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -%w{ models controllers helpers }.each do |dir| - path = File.join(directory, 'lib', dir) - $LOAD_PATH << path - Dependencies.load_paths << path - Dependencies.load_once_paths.delete(path) -end ---------------------------------------------------------- - -Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser. - -Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server. - - === Write custom Rake tasks in your plugin === When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app. Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so: +*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/preparation.txt b/railties/doc/guides/source/creating_plugins/preparation.txt deleted file mode 100644 index 77e3a3561f..0000000000 --- a/railties/doc/guides/source/creating_plugins/preparation.txt +++ /dev/null @@ -1,169 +0,0 @@ -== Preparation == - -=== Create the basic app === - -In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app: - ------------------------------------------------- -rails plugin_demo -cd plugin_demo -script/generate scaffold bird name:string -rake db:migrate -script/server ------------------------------------------------- - -Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing. - -NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs. - - -=== Create the plugin === - -The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also. - -This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories. - -Examples: ----------------------------------------------- -./script/generate plugin BrowserFilters -./script/generate plugin BrowserFilters --with-generator ----------------------------------------------- - -Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now: - ----------------------------------------------- -script/generate plugin yaffle --with-generator ----------------------------------------------- - -You should see the following output: - ----------------------------------------------- -create vendor/plugins/yaffle/lib -create vendor/plugins/yaffle/tasks -create vendor/plugins/yaffle/test -create vendor/plugins/yaffle/README -create vendor/plugins/yaffle/MIT-LICENSE -create vendor/plugins/yaffle/Rakefile -create vendor/plugins/yaffle/init.rb -create vendor/plugins/yaffle/install.rb -create vendor/plugins/yaffle/uninstall.rb -create vendor/plugins/yaffle/lib/yaffle.rb -create vendor/plugins/yaffle/tasks/yaffle_tasks.rake -create vendor/plugins/yaffle/test/core_ext_test.rb -create vendor/plugins/yaffle/generators -create vendor/plugins/yaffle/generators/yaffle -create vendor/plugins/yaffle/generators/yaffle/templates -create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb -create vendor/plugins/yaffle/generators/yaffle/USAGE ----------------------------------------------- - -For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that. - ----------------------------------------------- -rm vendor/plugins/yaffle/lib/yaffle.rb ----------------------------------------------- - -.Editor's note: -NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean - - -=== Setup the plugin for testing === - -Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests. - -To setup your plugin to allow for easy testing you'll need to add 3 files: - - * A 'database.yml' file with all of your connection strings. - * A 'schema.rb' file with your table definitions. - * A test helper that sets up the database before your tests. - -For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files: - -*vendor/plugins/yaffle/test/database.yml:* - ----------------------------------------------- -sqlite: - :adapter: sqlite - :dbfile: yaffle_plugin.sqlite.db - -sqlite3: - :adapter: sqlite3 - :dbfile: yaffle_plugin.sqlite3.db - -postgresql: - :adapter: postgresql - :username: postgres - :password: postgres - :database: yaffle_plugin_test - :min_messages: ERROR - -mysql: - :adapter: mysql - :host: localhost - :username: rails - :password: - :database: yaffle_plugin_test ----------------------------------------------- - -*vendor/plugins/yaffle/test/test_helper.rb:* - -[source, ruby] ----------------------------------------------- -ActiveRecord::Schema.define(:version => 0) do - create_table :hickwalls, :force => true do |t| - t.string :name - t.string :last_squawk - t.datetime :last_squawked_at - end - create_table :wickwalls, :force => true do |t| - t.string :name - t.string :last_tweet - t.datetime :last_tweeted_at - end -end - -# File: vendor/plugins/yaffle/test/test_helper.rb - -ENV['RAILS_ENV'] = 'test' -ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..' - -require 'test/unit' -require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb')) - -config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml')) -ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log") - -db_adapter = ENV['DB'] - -# no db passed, try one of these fine config-free DBs before bombing. -db_adapter ||= - begin - require 'rubygems' - require 'sqlite' - 'sqlite' - rescue MissingSourceFile - begin - require 'sqlite3' - 'sqlite3' - rescue MissingSourceFile - end - end - -if db_adapter.nil? - raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3." -end - -ActiveRecord::Base.establish_connection(config[db_adapter]) - -load(File.dirname(__FILE__) + "/schema.rb") - -require File.dirname(__FILE__) + '/../init.rb' - -class Hickwall < ActiveRecord::Base - acts_as_yaffle -end - -class Wickwall < ActiveRecord::Base - acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at -end ----------------------------------------------- diff --git a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt b/railties/doc/guides/source/creating_plugins/string_to_squawk.txt deleted file mode 100644 index 50516cef69..0000000000 --- a/railties/doc/guides/source/creating_plugins/string_to_squawk.txt +++ /dev/null @@ -1,103 +0,0 @@ -== Add a `to_squawk` method to String == - -To update a core class you will have to: - - * Write tests for the desired functionality. - * Create a file for the code you wish to use. - * Require that file from your 'init.rb'. - -Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'. - -First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this: - -[source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/test/core_ext_test.rb - -require 'test/unit' - -class CoreExtTest < Test::Unit::TestCase - # Replace this with your real tests. - def test_this_plugin - flunk - end -end --------------------------------------------------------- - -Start off by removing the default test, and adding a require statement for your test helper. - -[source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/test/core_ext_test.rb - -require 'test/unit' -require File.dirname(__FILE__) + '/test_helper.rb' - -class CoreExtTest < Test::Unit::TestCase -end --------------------------------------------------------- - -Navigate to your plugin directory and run `rake test`: - --------------------------------------------------------- -cd vendor/plugins/yaffle -rake test --------------------------------------------------------- - -Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message: - --------------------------------------------------------- -1.) Failure ... -No tests were specified --------------------------------------------------------- - -Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this: - -[source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -class CoreExtTest < Test::Unit::TestCase - def test_string_should_respond_to_squawk - assert_equal true, "".respond_to?(:to_squawk) - end - - def test_string_prepend_empty_strings_with_the_word_squawk - assert_equal "squawk!", "".to_squawk - end - - def test_string_prepend_non_empty_strings_with_the_word_squawk - assert_equal "squawk! Hello World", "Hello World".to_squawk - end -end --------------------------------------------------------- - -[source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -require "core_ext" --------------------------------------------------------- - -[source, ruby] --------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/core_ext.rb - -String.class_eval do - def to_squawk - "squawk! #{self}".strip - end -end --------------------------------------------------------- - -When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly. - -To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking: - --------------------------------------------------------- -$ ./script/console ->> "Hello World".to_squawk -=> "squawk! Hello World" --------------------------------------------------------- - -If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class. diff --git a/railties/doc/guides/source/creating_plugins/test_setup.txt b/railties/doc/guides/source/creating_plugins/test_setup.txt new file mode 100644 index 0000000000..64236ff110 --- /dev/null +++ b/railties/doc/guides/source/creating_plugins/test_setup.txt @@ -0,0 +1,230 @@ +== 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/view_helper.txt b/railties/doc/guides/source/creating_plugins/view_helper.txt deleted file mode 100644 index b03a190e1a..0000000000 --- a/railties/doc/guides/source/creating_plugins/view_helper.txt +++ /dev/null @@ -1,61 +0,0 @@ -== Create a `squawk_info_for` view helper == - -Creating a view helper is a 3-step process: - - * Add an appropriately named file to the 'lib' directory. - * Require the file and hooks in 'init.rb'. - * Write the tests. - -First, create the test to define the functionality you want: - -[source, ruby] ---------------------------------------------------------------- -# File: vendor/plugins/yaffle/test/view_helpers_test.rb - -require File.dirname(__FILE__) + '/test_helper.rb' -include YaffleViewHelper - -class ViewHelpersTest < Test::Unit::TestCase - def test_squawk_info_for_should_return_the_text_and_date - time = Time.now - hickwall = Hickwall.new - hickwall.last_squawk = "Hello World" - hickwall.last_squawked_at = time - assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall) - end -end ---------------------------------------------------------------- - -Then add the following statements to init.rb: - -[source, ruby] ---------------------------------------------------------------- -# File: vendor/plugins/yaffle/init.rb - -require "view_helpers" -ActionView::Base.send :include, YaffleViewHelper ---------------------------------------------------------------- - -Then add the view helpers file and - -[source, ruby] ---------------------------------------------------------------- -# File: vendor/plugins/yaffle/lib/view_helpers.rb - -module YaffleViewHelper - def squawk_info_for(yaffle) - returning "" do |result| - result << yaffle.read_attribute(yaffle.class.yaffle_text_field) - result << ", " - result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s - end - end -end ---------------------------------------------------------------- - -You can also test this in script/console by using the `helper` method: - ---------------------------------------------------------------- -$ ./script/console ->> helper.squawk_info_for(@some_yaffle_instance) ---------------------------------------------------------------- diff --git a/railties/doc/guides/source/debugging_rails_applications.txt b/railties/doc/guides/source/debugging_rails_applications.txt index b45473fc14..4425d9240b 100644 --- a/railties/doc/guides/source/debugging_rails_applications.txt +++ b/railties/doc/guides/source/debugging_rails_applications.txt @@ -595,7 +595,7 @@ To list all active catchpoints use `catch`. There are two ways to resume execution of an application that is stopped in the debugger: * `continue` [line-specification] (or `c`): resume program execution, at the address where your script last stopped; any breakpoints set at that address are bypassed. The optional argument line-specification allows you to specify a line number to set a one-time breakpoint which is deleted when that breakpoint is reached. -* `finish` [frame-number] (or `fin`): execute until the selected stack frame returns. If no frame number is given, the application run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns. +* `finish` [frame-number] (or `fin`): execute until the selected stack frame returns. If no frame number is given, the application will run until the currently selected frame returns. The currently selected frame starts out the most-recent frame or 0 if no frame positioning (e.g up, down or frame) has been performed. If a frame number is given it will run until the specified frame returns. === Editing @@ -704,7 +704,7 @@ For further information on how to install Valgrind and use with Ruby, refer to l 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/drnic/rails-footnotes/tree/master[Footnotes]: Every Rails page has footnotes that 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. diff --git a/railties/doc/guides/source/finders.txt b/railties/doc/guides/source/finders.txt index 24d078f9e4..e5d94cffb0 100644 --- a/railties/doc/guides/source/finders.txt +++ b/railties/doc/guides/source/finders.txt @@ -1,21 +1,17 @@ Rails Finders ============= -This guide is all about the +find+ method defined in +ActiveRecord::Base+, finding on associations, and associated goodness such as named scopes. You will learn how to be a find master. +This guide covers the +find+ method defined in +ActiveRecord::Base+, as well as other ways of finding particular instances of your models. By using this guide, you will be able to: -== In the beginning... +* Find records using a variety of methods and conditions +* Specify the order, retrieved attributes, grouping, and other properties of the found records +* Use eager loading to cut down on the number of database queries in your application +* Use dynamic finders +* Create named scopes to add custom finding behavior to your models +* Check for the existence of particular records +* Perform aggregate calculations on Active Record models -In the beginning there was SQL. SQL looked like this: - -[source,sql] -------------------------------------------------------- -SELECT * FROM clients -SELECT * FROM clients WHERE id = '1' -SELECT * FROM clients LIMIT 0,1 -SELECT * FROM clients ORDER BY id DESC LIMIT 0,1 -------------------------------------------------------- - -In Rails (unlike some other frameworks) you don't usually have to type SQL because Active Record is there to help you find your records. +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 Sample Models @@ -78,6 +74,8 @@ SELECT * FROM +clients+ WHERE (+clients+.+id+ IN (1,2)) 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. +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: ------------------------------------------------------- @@ -124,13 +122,17 @@ Be aware that +Client.first+/+Client.find(:first)+ and +Client.last+/+Client.fin == Conditions +The +find+ method allows you to specify conditions to limit the records returned. You can specify conditions as a string, array, or hash. + === Pure String Conditions === If you'd like to add conditions to your find, you could just specify them in there, just like +Client.first(:conditions => "orders_count = '2'")+. This will find all clients where the +orders_count+ field's value is 2. +WARNING: Building your own conditions as pure strings can leave you vulnerable to SQL injection exploits. For example, +Client.first(:conditions => "name LIKE '%#{params[:name]}%'")+ is not safe. See the next section for the preferred way to handle conditions using an array. + === 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: @@ -234,7 +236,7 @@ To select certain fields, you can use the select option like this: +Client.first == Limit & Offset -If you want to limit the amount of records to a certain subset of all the records retreived you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retreived from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example: +If you want to limit the amount of records to a certain subset of all the records retrieved you usually use limit for this, sometimes coupled with offset. Limit is the maximum number of records that will be retrieved from a query, and offset is the number of records it will start reading from from the first record of the set. Take this code for example: [source, ruby] ------------------------------------------------------- @@ -280,14 +282,14 @@ SELECT * FROM +orders+ GROUP BY date(created_at) == Read Only -Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ error. To set this option, specify it like this: +Readonly is a find option that you can set in order to make that instance of the record read-only. Any attempt to alter or destroy the record will not succeed, raising an +Active Record::ReadOnlyRecord+ exception. To set this option, specify it like this: [source, ruby] ------------------------------------------------------- Client.first(:readonly => true) ------------------------------------------------------- -If you assign this record to a variable +client+, calling the following code will raise an ActiveRecord::ReadOnlyRecord: +If you assign this record to a variable +client+, calling the following code will raise an +ActiveRecord::ReadOnlyRecord+ exception: [source, ruby] ------------------------------------------------------- @@ -310,11 +312,11 @@ end == Making It All Work Together -You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement ActiveRecord will use the latter. +You can chain these options together in no particular order as Active Record will write the correct SQL for you. If you specify two instances of the same options inside the find statement Active Record will use the latter. == Eager Loading -Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all), :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this: +Eager loading is loading associated records along with any number of records in as few queries as possible. For example, if you wanted to load all the addresses associated with all the clients in a single query you could use +Client.all(:include => :address)+. If you wanted to include both the address and mailing address for the client you would use +Client.find(:all, :include => [:address, :mailing_address]). Include will first find the client records and then load the associated address records. Running script/server in one window, and executing the code through script/console in another window, the output should look similar to this: [source, sql] ------------------------------------------------------- @@ -386,11 +388,11 @@ If you'd like to use your own SQL to find records a table you can use +find_by_s Client.find_by_sql("SELECT * FROM clients INNER JOIN orders ON clients.id = orders.client_id ORDER clients.created_at desc") ------------------------------------------------------- -+find_by_sql+ provides you with a simple way of making custom calls to the database and retreiving instantiated objects. ++find_by_sql+ provides you with a simple way of making custom calls to the database and retrieving instantiated objects. == +select_all+ == -+find_by_sql+ has a close relative called +select_all+. +select_all+ will retreive objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record. ++find_by_sql+ has a close relative called +connection#select_all+. +select_all+ will retrieve objects from the database using custom SQL just like +find_by_sql+ but will not instantiate them. Instead, you will get an array of hashes where each hash indicates a record. [source, ruby] ------------------------------------------------------- @@ -399,11 +401,15 @@ Client.connection.select_all("SELECT * FROM `clients` WHERE `id` = '1'") == Working with Associations -When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an exisiting record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers. +When you define a has_many association on a model you get the find method and dynamic finders also on that association. This is helpful for finding associated records within the scope of an existing record, for example finding all the orders for a client that have been sent and not received by doing something like +Client.find(params[:id]).orders.find_by_sent_and_received(true, false)+. Having this find method available on associations is extremely helpful when using nested controllers. == Named Scopes -Named scopes are another way to add custom finding behavior to the models in the application. Suppose want to find all clients who are male. Yould use this code: +Named scopes are another way to add custom finding behavior to the models in the application. Named scopes provide an object-oriented way to narrow the results of a query. + +=== Simple Named Scopes + +Suppose want to find all clients who are male. You could use this code: [source, ruby] ------------------------------------------------------- @@ -412,7 +418,7 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- -And you could call it like +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end. +Then you could call +Client.males.all+ to get all the clients who are male. Please note that if you do not specify the +all+ on the end you will get a +Scope+ object back, not a set of records which you do get back if you put the +all+ on the end. If you wanted to find all the clients who are active, you could use this: @@ -423,7 +429,9 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- -You can call this new named_scope by doing +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+. +You can call this new named_scope with +Client.active.all+ and this will do the same query as if we just used +Client.all(:conditions => ["active = ?", true])+. Please be aware that the conditions syntax in named_scope and find is different and the two are not interchangeable. If you want to find the first client within this named scope you could do +Client.active.first+. + +=== Combining Named Scopes If you wanted to find all the clients who are active and male you can stack the named scopes like this: @@ -439,6 +447,8 @@ If you would then like to do a +all+ on that scope, you can. Just like an associ Client.males.active.all(:conditions => ["age > ?", params[:age]]) ------------------------------------------------------- +=== Runtime Evaluation of Named Scope Conditions + Consider the following code: [source, ruby] @@ -459,6 +469,8 @@ end And now every time the recent named scope is called, the code in the lambda block will be parsed, so you'll get actually 2 weeks ago from the code execution, not 2 weeks ago from the time the model was loaded. +=== Named Scopes with Multiple Models + In a named scope you can use +:include+ and +:joins+ options just like in find. [source, ruby] @@ -471,6 +483,8 @@ end This method, called as +Client.active_within_2_weeks.all+, will return all clients who have placed orders in the past 2 weeks. +=== Arguments to Named Scopes + If you want to pass a named scope a compulsory argument, just specify it as a block parameter like this: [source, ruby] @@ -493,7 +507,9 @@ This will work with +Client.recent(2.weeks.ago).all+ and +Client.recent.all+, wi Remember that named scopes are stackable, so you will be able to do +Client.recent(2.weeks.ago).unlocked.all+ to find all clients created between right now and 2 weeks ago and have their locked field set to false. -Finally, if you wish to define named scopes on the fly you can use the scoped method: +=== Anonymous Scopes + +All Active Record models come with a named scope named +scoped+, which allows you to create anonymous scopes. For example: [source, ruby] ------------------------------------------------------- @@ -504,6 +520,15 @@ class Client < ActiveRecord::Base end ------------------------------------------------------- +Anonymous scopes are most useful to create scopes "on the fly": + +[source, ruby] +------------------------------------------------------- +Client.scoped(:conditions => { :gender => "male" }) +------------------------------------------------------- + +Just like named scopes, anonymous scopes can be stacked, either with other anonymous scopes or with regular named scopes. + == Existence of Objects If you simply want to check for the existence of the object there's a method called +exists?+. This method will query the database using the same query as find, but instead of returning an object or collection of objects it will return either true or false. @@ -513,7 +538,7 @@ If you simply want to check for the existence of the object there's a method cal Client.exists?(1) ------------------------------------------------------- -The above code will check for the existance of a clients table record with the id of 1 and return true if it exists. +The above code will check for the existence of a clients table record with the id of 1 and return true if it exists. [source, ruby] ------------------------------------------------------- @@ -630,8 +655,9 @@ Thanks to Mike Gunderloy for his tips on creating this guide. http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/16[Lighthouse ticket] -* October 27, 2008: Added scoped section, added named params for conditions and added sub-section headers for conditions section. -* 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. +* 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 * October 26, 2008: Editing pass by link:../authors.html#mgunderloy[Mike Gunderloy] . First release version. * October 22, 2008: Calculations complete, first complete draft by Ryan Bigg * October 21, 2008: Extended named scope section by Ryan Bigg diff --git a/railties/doc/guides/source/getting_started_with_rails.txt b/railties/doc/guides/source/getting_started_with_rails.txt index f924d0793a..bae8f9a4fd 100644 --- a/railties/doc/guides/source/getting_started_with_rails.txt +++ b/railties/doc/guides/source/getting_started_with_rails.txt @@ -186,7 +186,7 @@ If you open this file in a new Rails application, you'll see a default database ==== Configuring a SQLite Database -Rails comes with built-in support for SQLite, which is a lightweight flat-file based database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. +Rails comes with built-in support for link:http://www.sqlite.org/[SQLite], which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using a SQLite database when creating a new project, but you can always change it later. Here's the section of the default configuration file with connection information for the development environment: @@ -480,7 +480,7 @@ This code sets the +@posts+ instance variable to an array of all posts in the da TIP: For more information on finding records with Active Record, see link:../finders.html[Active Record Finders]. -The +respond_to+ block handles both HTML and XML calls to this action. If you borwse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+: +The +respond_to+ block handles both HTML and XML calls to this action. If you browse to +http://localhost:3000/posts.xml+, you'll see all of the posts in XML format. The HTML format looks for a view in +app/views/posts/+ with a name that corresponds to the action name. Rails makes all of the instance variables from the action available to the view. Here's +app/view/posts/index.html.erb+: [source, ruby] ------------------------------------------------------- diff --git a/railties/doc/guides/source/layouts_and_rendering.txt b/railties/doc/guides/source/layouts_and_rendering.txt index 2f39c70e8c..2cba53b94c 100644 --- a/railties/doc/guides/source/layouts_and_rendering.txt +++ b/railties/doc/guides/source/layouts_and_rendering.txt @@ -877,6 +877,8 @@ When a partial is called with a pluralized collection, then the individual insta With this change, you can access an instance of the +@products+ collection as the +item+ local variable within the partial. +TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by +_counter+. For example, if you're rendering +@products+, within the partial you can refer to +product_counter+ to tell you how many times the partial has been rendered. + You can also specify a second partial to be rendered between instances of the main partial by using the +:spacer_template+ option: [source, html] @@ -933,6 +935,7 @@ In this case, Rails will use the customer or employee partials as appropriate fo http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/15[Lighthouse ticket] +* November 9, 2008: Added partial collection counter by link:../authors.html#mgunderloy[Mike Gunderloy] * November 1, 2008: Added +:js+ option for +render+ by link:../authors.html#mgunderloy[Mike Gunderloy] * October 16, 2008: Ready for publication by link:../authors.html#mgunderloy[Mike Gunderloy] * October 4, 2008: Additional info on partials (+:object+, +:as+, and +:spacer_template+) by link:../authors.html#mgunderloy[Mike Gunderloy] (not yet approved for publication) diff --git a/railties/doc/guides/source/migrations/foreign_keys.txt b/railties/doc/guides/source/migrations/foreign_keys.txt index 8f796843b2..792c41ccdc 100644 --- a/railties/doc/guides/source/migrations/foreign_keys.txt +++ b/railties/doc/guides/source/migrations/foreign_keys.txt @@ -1,6 +1,6 @@ [[foreign_key]] == Active Record and Referential Integrity == -The Active Record way is that intelligence belongs in your models, not in the database. As such features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used. +The Active Record way is that intelligence belongs in your models, not in the database. As such, features such as triggers or foreign key constraints, which push some of that intelligence back into the database are not heavily used. Validations such as `validates_uniqueness_of` are one way in which models can enforce data integrity. The `:dependent` option on associations allows models to automatically destroy child objects when the parent is destroyed. Like anything which operates at the application level these cannot guarantee referential integrity and so some people augment them with foreign key constraints. diff --git a/railties/doc/guides/source/migrations/scheming.txt b/railties/doc/guides/source/migrations/scheming.txt index ba4fea8fe3..7acd3f9190 100644 --- a/railties/doc/guides/source/migrations/scheming.txt +++ b/railties/doc/guides/source/migrations/scheming.txt @@ -7,7 +7,7 @@ There is no need (and it is error prone) to deploy a new instance of an app by r For example, this is how the test database is created: the current development database is dumped (either to `schema.rb` or `development.sql`) and then loaded into the test database. -Schema files are also useful if want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest. +Schema files are also useful if you want a quick look at what attributes an Active Record object has. This information is not in the model's code and is frequently spread across several migrations but is all summed up in the schema file. The http://agilewebdevelopment.com/plugins/annotate_models[annotate_models] plugin, which automatically adds (and updates) comments at the top of each model summarising the schema, may also be of interest. === Types of schema dumps === There are two ways to dump the schema. This is set in `config/environment.rb` by the `config.active_record.schema_format` setting, which may be either `:sql` or `:ruby`. diff --git a/railties/doc/guides/source/routing_outside_in.txt b/railties/doc/guides/source/routing_outside_in.txt index 6d127973b0..0f6cd358e2 100644 --- a/railties/doc/guides/source/routing_outside_in.txt +++ b/railties/doc/guides/source/routing_outside_in.txt @@ -229,6 +229,8 @@ Although the conventions of RESTful routing are likely to be sufficient for many * +:path_names+ * +:path_prefix+ * +:name_prefix+ +* +:only+ +* +:except+ You can also add additional routes via the +:member+ and +:collection+ options, which are discussed later in this guide. @@ -400,6 +402,30 @@ This combination will give you route helpers such as +photographer_photos_path+ NOTE: You can also use +:name_prefix+ with non-RESTful routes. +==== Using :only and :except + +By default, Rails creates routes for all seven of the default actions (index, show, new, create, edit, update, and destroy) for every RESTful route in your application. You can use the +:only+ and +:except+ options to fine-tune this behavior. The +:only+ option specifies that only certain routes should be generated: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :only => [:index, :show] +------------------------------------------------------- + +With this declaration, a +GET+ request to +/photos+ would succeed, but a +POST+ request to +/photos+ (which would ordinarily be routed to the create action) will fail. + +The +:except+ option specifies a route or list of routes that should _not_ be generated: + +[source, ruby] +------------------------------------------------------- +map.resources :photos, :except => :destroy +------------------------------------------------------- + +In this case, all of the normal routes except the route for +destroy+ (a +DELETE+ request to +/photos/_id_+) will be generated. + +In addition to an action or a list of actions, you can also supply the special symbols +:all+ or +:none+ to the +:only+ and +:except+ options. + +TIP: If your application has many RESTful routes, using +:only+ and +:accept+ to generate only the routes that you actually need can cut down on memory use and speed up the routing process. + === Nested Resources It's common to have resources that are logically children of other resources. For example, suppose your application includes these models: @@ -535,17 +561,7 @@ This will enable recognition of (among others) these routes: /photos/3 ==> photo_path(3) ------------------------------------------------------- -With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with - but you _can_ supply more information. All of the nested routes continue to work, just as they would without shallow nesting, but less-deeply nested routes (even direct routes) work as well. So, with the declaration above, all of these routes refer to the same resource: - -------------------------------------------------------- -/publishers/1/magazines/2/photos/3 ==> publisher_magazine_photo_path(1,2,3) -/magazines/2/photos/3 ==> magazine_photo_path(2,3) -/photos/3 ==> photo_path(3) -------------------------------------------------------- - -Shallow nesting gives you the flexibility to use the shorter direct routes when you like, while still preserving the longer nested routes for times when they add code clarity. - -If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options: +With shallow nesting, you need only supply enough information to uniquely identify the resource that you want to work with. If you like, you can combine shallow nesting with the +:has_one+ and +:has_many+ options: [source, ruby] ------------------------------------------------------- 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 4d0e6752bf8476f7aeba7c946054edcc6e1e71e6 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Fri, 14 Nov 2008 13:52:32 +0100 Subject: Link to 2.2.1 gems --- railties/Rakefile | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) (limited to 'railties') diff --git a/railties/Rakefile b/railties/Rakefile index 52357a09c5..1bc59ac0b0 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -358,11 +358,11 @@ spec = Gem::Specification.new do |s| EOF s.add_dependency('rake', '>= 0.8.3') - s.add_dependency('activesupport', '= 2.2.0' + PKG_BUILD) - s.add_dependency('activerecord', '= 2.2.0' + PKG_BUILD) - s.add_dependency('actionpack', '= 2.2.0' + PKG_BUILD) - s.add_dependency('actionmailer', '= 2.2.0' + PKG_BUILD) - s.add_dependency('activeresource', '= 2.2.0' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD) + s.add_dependency('activerecord', '= 2.2.1' + PKG_BUILD) + s.add_dependency('actionpack', '= 2.2.1' + PKG_BUILD) + s.add_dependency('actionmailer', '= 2.2.1' + PKG_BUILD) + s.add_dependency('activeresource', '= 2.2.1' + PKG_BUILD) s.rdoc_options << '--exclude' << '.' s.has_rdoc = false -- cgit v1.2.3 From ad679a43ec288610088d82b3cbd4009646ebde17 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Fri, 14 Nov 2008 20:32:33 +0530 Subject: Update release notes from docrails. --- railties/doc/guides/html/2_2_release_notes.html | 13 ++++++++++++- railties/doc/guides/source/2_2_release_notes.txt | 6 +++++- 2 files changed, 17 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index e79f7ec511..68b8188f7c 100644 --- a/railties/doc/guides/html/2_2_release_notes.html +++ b/railties/doc/guides/html/2_2_release_notes.html @@ -812,6 +812,16 @@ Rails now supports HTTP-only cookies (and uses them for sessions), which help mi render now supports a :js option to render plain vanilla javascript with the right mime type.

    +
  • +

    +Request forgery protection has been tightened up to apply to HTML-formatted content requests only. +

    +
  • +
  • +

    +Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling polymorphic_path([@project, @date, @area]) with a nil date will give you project_area_path. +

    +
  • 7. Action View

    @@ -856,6 +866,7 @@ More information: +

    Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed.

    9. Active Support

    @@ -1094,7 +1105,7 @@ Wrapped Rails.env in StringInquirer so you can do Rails.en
  • -script/generate works without deprecation warnings when RubyGems 1.3.0 is present +To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher.

  • diff --git a/railties/doc/guides/source/2_2_release_notes.txt b/railties/doc/guides/source/2_2_release_notes.txt index f78c179ba1..1e5c21f913 100644 --- a/railties/doc/guides/source/2_2_release_notes.txt +++ b/railties/doc/guides/source/2_2_release_notes.txt @@ -270,6 +270,8 @@ map.resources :products, :except => :destroy * Rails now supports HTTP-only cookies (and uses them for sessions), which help mitigate some cross-site scripting risks in newer browsers. * +redirect_to+ now fully supports URI schemes (so, for example, you can redirect to a svn+ssh: URI). * +render+ now supports a +:js+ option to render plain vanilla javascript with the right mime type. +* Request forgery protection has been tightened up to apply to HTML-formatted content requests only. +* Polymorphic URLs behave more sensibly if a passed parameter is nil. For example, calling +polymorphic_path([@project, @date, @area])+ with a nil date will give you +project_area_path+. == Action View @@ -285,6 +287,8 @@ Action Mailer now supports mailer layouts. You can make your HTML emails as pret * More information: - link:http://ryandaigle.com/articles/2008/9/7/what-s-new-in-edge-rails-mailer-layouts[What's New in Edge Rails: Mailer Layouts] +Action Mailer now offers built-in support for GMail's SMTP servers, by turning on STARTTLS automatically. This requires Ruby 1.8.7 to be installed. + == Active Support Active Support now offers built-in memoization for Rails applications, the +each_with_object+ method, prefix support on delegates, and various other new utility methods. @@ -399,7 +403,7 @@ You can unpack or install a single gem by specifying +GEM=_gem_name_+ on the com * Instructions for setting up a continuous integration server to build Rails itself are included in the Rails source * +rake notes:custom ANNOTATION=MYFLAG+ lets you list out custom annotations. * Wrapped +Rails.env+ in +StringInquirer+ so you can do +Rails.env.development?+ -* +script/generate+ works without deprecation warnings when RubyGems 1.3.0 is present +* To eliminate deprecation warnings and properly handle gem dependencies, Rails now requires rubygems 1.3.1 or higher. == Deprecated -- cgit v1.2.3 From 0cd9b149e2e8af10f835718018cf009ebc4f9fda Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 15 Nov 2008 12:26:37 -0800 Subject: Appropriate test case subclasses to get assert_tag and assert_deprecated --- railties/test/rails_info_controller_test.rb | 2 +- railties/test/secret_key_generation_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/test/rails_info_controller_test.rb b/railties/test/rails_info_controller_test.rb index e1872ebf33..e274e1aa6e 100644 --- a/railties/test/rails_info_controller_test.rb +++ b/railties/test/rails_info_controller_test.rb @@ -25,7 +25,7 @@ ActionController::Routing::Routes.draw do |map| map.connect ':controller/:action/:id' end -class Rails::InfoControllerTest < Test::Unit::TestCase +class Rails::InfoControllerTest < ActionController::TestCase def setup @controller = Rails::InfoController.new @request = ActionController::TestRequest.new diff --git a/railties/test/secret_key_generation_test.rb b/railties/test/secret_key_generation_test.rb index 7269f98ce5..df486c3bbb 100644 --- a/railties/test/secret_key_generation_test.rb +++ b/railties/test/secret_key_generation_test.rb @@ -22,7 +22,7 @@ require 'rails_generator' require 'rails_generator/secret_key_generator' require 'rails_generator/generators/applications/app/app_generator' -class SecretKeyGenerationTest < Test::Unit::TestCase +class SecretKeyGenerationTest < ActiveSupport::TestCase SECRET_KEY_MIN_LENGTH = 128 APP_NAME = "foo" -- cgit v1.2.3 From fcce1f17eaf9993b0210fe8e2a8117b61a1f0f69 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 17 Nov 2008 19:16:31 +0100 Subject: BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH] --- railties/CHANGELOG | 5 +++++ railties/Rakefile | 2 +- railties/doc/guides/source/layouts_and_rendering.txt | 2 +- railties/helpers/application.rb | 15 --------------- railties/helpers/application_controller.rb | 15 +++++++++++++++ .../generators/applications/app/app_generator.rb | 3 ++- 6 files changed, 24 insertions(+), 18 deletions(-) delete mode 100644 railties/helpers/application.rb create mode 100644 railties/helpers/application_controller.rb (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index ae20cb50da..e6b90198ab 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,3 +1,8 @@ +*2.3.0/3.0* + +* BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH] + + *2.2.1 [RC2] (November 14th, 2008)* * Fixed plugin generator so that generated unit tests would subclass ActiveSupport::TestCase, also introduced a helper script to reduce the needed require statements #1137 [Mathias Meyer] diff --git a/railties/Rakefile b/railties/Rakefile index 1bc59ac0b0..c9541b0292 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -184,7 +184,7 @@ task :copy_html_files do end task :copy_application do - cp "helpers/application.rb", "#{PKG_DESTINATION}/app/controllers/application.rb" + cp "helpers/application_controller.rb", "#{PKG_DESTINATION}/app/controllers/application_controller.rb" cp "helpers/application_helper.rb", "#{PKG_DESTINATION}/app/helpers/application_helper.rb" end diff --git a/railties/doc/guides/source/layouts_and_rendering.txt b/railties/doc/guides/source/layouts_and_rendering.txt index 2cba53b94c..8f1fae5007 100644 --- a/railties/doc/guides/source/layouts_and_rendering.txt +++ b/railties/doc/guides/source/layouts_and_rendering.txt @@ -313,7 +313,7 @@ With those declarations, the +inventory+ layout would be used only for the +inde Layouts are shared downwards in the hierarchy, and more specific layouts always override more general ones. For example: -+application.rb+: ++application_controller.rb+: [source, ruby] ------------------------------------------------------- diff --git a/railties/helpers/application.rb b/railties/helpers/application.rb deleted file mode 100644 index 0a3ed822a4..0000000000 --- a/railties/helpers/application.rb +++ /dev/null @@ -1,15 +0,0 @@ -# Filters added to this controller apply to all controllers in the application. -# Likewise, all the methods added will be available for all controllers. - -class ApplicationController < ActionController::Base - helper :all # include all helpers, all the time - - # See ActionController::RequestForgeryProtection for details - # Uncomment the :secret if you're not using the cookie session store - protect_from_forgery # :secret => '<%= app_secret %>' - - # See ActionController::Base for details - # Uncomment this to filter the contents of submitted sensitive data parameters - # from your application log (in this case, all fields with names like "password"). - # filter_parameter_logging :password -end diff --git a/railties/helpers/application_controller.rb b/railties/helpers/application_controller.rb new file mode 100644 index 0000000000..0a3ed822a4 --- /dev/null +++ b/railties/helpers/application_controller.rb @@ -0,0 +1,15 @@ +# Filters added to this controller apply to all controllers in the application. +# Likewise, all the methods added will be available for all controllers. + +class ApplicationController < ActionController::Base + helper :all # include all helpers, all the time + + # See ActionController::RequestForgeryProtection for details + # Uncomment the :secret if you're not using the cookie session store + protect_from_forgery # :secret => '<%= app_secret %>' + + # See ActionController::Base for details + # Uncomment this to filter the contents of submitted sensitive data parameters + # from your application log (in this case, all fields with names like "password"). + # filter_parameter_logging :password +end diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 32c320385d..8c9bc63fc6 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -47,7 +47,8 @@ class AppGenerator < Rails::Generator::Base m.file "README", "README" # Application - m.template "helpers/application.rb", "app/controllers/application.rb", :assigns => { :app_name => @app_name, :app_secret => md5.hexdigest } + m.template "helpers/application_controller.rb", "app/controllers/application_controller.rb", :assigns => { + :app_name => @app_name, :app_secret => md5.hexdigest } m.template "helpers/application_helper.rb", "app/helpers/application_helper.rb" m.template "helpers/test_helper.rb", "test/test_helper.rb" m.template "helpers/performance_test.rb", "test/performance/browsing_test.rb" -- cgit v1.2.3 From e3fcf9b66889caba7852e273de778e0e52c6585c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 17 Nov 2008 10:39:46 -0800 Subject: Use ActiveSupport::TestCase in generated test/test_helper.rb --- railties/helpers/test_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/helpers/test_helper.rb b/railties/helpers/test_helper.rb index 9f1926950f..b9fe2517c8 100644 --- a/railties/helpers/test_helper.rb +++ b/railties/helpers/test_helper.rb @@ -2,7 +2,7 @@ ENV["RAILS_ENV"] = "test" require File.expand_path(File.dirname(__FILE__) + "/../config/environment") require 'test_help' -class Test::Unit::TestCase +class ActiveSupport::TestCase # Transactional fixtures accelerate your tests by wrapping each test method # in a transaction that's rolled back on completion. This ensures that the # test database remains unchanged so your fixtures don't have to be reloaded -- cgit v1.2.3 From 8412200f90c239cbf12bb32b5246d0104306f6c2 Mon Sep 17 00:00:00 2001 From: Carlos Paramio Date: Tue, 4 Nov 2008 20:32:52 +0100 Subject: Change usage of defined? to check the rubygems constant existance by a rescue block on boot.rb for Ruby 1.9 compatibility Signed-off-by: Jeremy Kemper --- railties/environments/boot.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/environments/boot.rb b/railties/environments/boot.rb index 57c256e438..0a516880ca 100644 --- a/railties/environments/boot.rb +++ b/railties/environments/boot.rb @@ -67,7 +67,7 @@ module Rails class << self def rubygems_version - Gem::RubyGemsVersion if defined? Gem::RubyGemsVersion + Gem::RubyGemsVersion rescue nil end def gem_version -- cgit v1.2.3 From 5a4789e86adf73ba3757caa9111c3b5ad481b940 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 17 Nov 2008 15:18:01 -0800 Subject: Explicitly require test/unit so tests autorun --- railties/lib/test_help.rb | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index a7be514cf0..daa5201663 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -4,6 +4,10 @@ require_dependency 'application' # so fixtures are loaded to the right database silence_warnings { RAILS_ENV = "test" } +require 'test/unit' +require 'active_support/test_case' +require 'active_controller/test_case' +require 'action_view/test_case' require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -- cgit v1.2.3 From 8f71d6bcf621389ee8bb23a4a4d2a074906cdbfe Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 18 Nov 2008 08:28:26 +0530 Subject: Fix script/console --- railties/lib/console_with_helpers.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'railties') diff --git a/railties/lib/console_with_helpers.rb b/railties/lib/console_with_helpers.rb index be453a6896..f9e8bf9cbf 100644 --- a/railties/lib/console_with_helpers.rb +++ b/railties/lib/console_with_helpers.rb @@ -16,8 +16,6 @@ def helper(*helper_names) end end -require_dependency 'application' - class << helper include_all_modules_from ActionView end -- cgit v1.2.3 From 3319fa69655744678e9458b4c585958f5d3956b1 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 18 Nov 2008 08:38:01 +0530 Subject: Dont require 'application' when running tests --- railties/lib/test_help.rb | 2 -- 1 file changed, 2 deletions(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index daa5201663..3ccbfebaf6 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -1,5 +1,3 @@ -require_dependency 'application' - # Make double-sure the RAILS_ENV is set to test, # so fixtures are loaded to the right database silence_warnings { RAILS_ENV = "test" } -- cgit v1.2.3 From d22fe41cf87d781ce1af264b37ba3eca762b74c3 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 18 Nov 2008 08:40:38 +0530 Subject: Fix a typo in test helper --- railties/lib/test_help.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/test_help.rb b/railties/lib/test_help.rb index 3ccbfebaf6..b5c92c1790 100644 --- a/railties/lib/test_help.rb +++ b/railties/lib/test_help.rb @@ -4,7 +4,7 @@ silence_warnings { RAILS_ENV = "test" } require 'test/unit' require 'active_support/test_case' -require 'active_controller/test_case' +require 'action_controller/test_case' require 'action_view/test_case' require 'action_controller/integration' require 'action_mailer/test_case' if defined?(ActionMailer) -- cgit v1.2.3 From 3c9beb3dab73013af83b90983f283b76625052b8 Mon Sep 17 00:00:00 2001 From: Eugene Bolshakov Date: Mon, 17 Nov 2008 21:55:56 -0600 Subject: Add helper test generators [#1199 state:resolved] Signed-off-by: Joshua Peek --- .../generators/components/controller/USAGE | 23 +++++++------- .../components/controller/controller_generator.rb | 8 ++++- .../components/controller/templates/helper_test.rb | 4 +++ .../generators/components/helper/USAGE | 24 +++++++++++++++ .../components/helper/helper_generator.rb | 25 +++++++++++++++ .../components/helper/templates/helper.rb | 2 ++ .../components/helper/templates/helper_test.rb | 4 +++ .../generators/components/resource/USAGE | 4 +-- .../components/resource/resource_generator.rb | 2 ++ .../components/resource/templates/helper_test.rb | 4 +++ .../components/scaffold/scaffold_generator.rb | 2 ++ .../components/scaffold/templates/helper_test.rb | 4 +++ railties/lib/tasks/testing.rake | 8 ++--- railties/test/generators/generator_test_helper.rb | 31 ++++++++++++++----- .../generators/rails_controller_generator_test.rb | 32 ++++++++++--------- .../test/generators/rails_helper_generator_test.rb | 36 ++++++++++++++++++++++ .../generators/rails_resource_generator_test.rb | 4 +-- .../generators/rails_scaffold_generator_test.rb | 7 +++-- 18 files changed, 179 insertions(+), 45 deletions(-) create mode 100644 railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb create mode 100644 railties/lib/rails_generator/generators/components/helper/USAGE create mode 100644 railties/lib/rails_generator/generators/components/helper/helper_generator.rb create mode 100644 railties/lib/rails_generator/generators/components/helper/templates/helper.rb create mode 100644 railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb create mode 100644 railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb create mode 100644 railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb create mode 100644 railties/test/generators/rails_helper_generator_test.rb (limited to 'railties') diff --git a/railties/lib/rails_generator/generators/components/controller/USAGE b/railties/lib/rails_generator/generators/components/controller/USAGE index d4fae60c81..362872e84a 100644 --- a/railties/lib/rails_generator/generators/components/controller/USAGE +++ b/railties/lib/rails_generator/generators/components/controller/USAGE @@ -6,24 +6,25 @@ Description: path like 'parent_module/controller_name'. This generates a controller class in app/controllers, view templates in - app/views/controller_name, a helper class in app/helpers, and a functional - test suite in test/functional. + app/views/controller_name, a helper class in app/helpers, a functional + test suite in test/functional and a helper test suite in test/unit/helpers. 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 + Controller: app/controllers/credit_card_controller.rb + Functional Test: test/functional/credit_card_controller_test.rb + Views: app/views/credit_card/debit.html.erb [...] + Helper: app/helpers/credit_card_helper.rb + Helper Test: test/unit/helpers/credit_card_helper_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 - + Controller: app/controllers/admin/credit_card_controller.rb + Functional Test: test/functional/admin/credit_card_controller_test.rb + Views: app/views/admin/credit_card/debit.html.erb [...] + Helper: app/helpers/admin/credit_card_helper.rb + Helper Test: test/unit/helpers/admin/credit_card_helper_test.rb diff --git a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb index 77b2220d57..dc126e8a98 100644 --- a/railties/lib/rails_generator/generators/components/controller/controller_generator.rb +++ b/railties/lib/rails_generator/generators/components/controller/controller_generator.rb @@ -2,13 +2,14 @@ class ControllerGenerator < Rails::Generator::NamedBase def manifest record do |m| # Check for class naming collisions. - m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper" + m.class_collisions "#{class_name}Controller", "#{class_name}ControllerTest", "#{class_name}Helper", "#{class_name}HelperTest" # Controller, helper, views, and test directories. m.directory File.join('app/controllers', class_path) m.directory File.join('app/helpers', class_path) m.directory File.join('app/views', class_path, file_name) m.directory File.join('test/functional', class_path) + m.directory File.join('test/unit/helpers', class_path) # Controller class, functional test, and helper class. m.template 'controller.rb', @@ -26,6 +27,11 @@ class ControllerGenerator < Rails::Generator::NamedBase class_path, "#{file_name}_helper.rb") + m.template 'helper_test.rb', + File.join('test/unit/helpers', + class_path, + "#{file_name}_helper_test.rb") + # View template for each action. actions.each do |action| path = File.join('app/views', class_path, file_name, "#{action}.html.erb") diff --git a/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb new file mode 100644 index 0000000000..591e40900e --- /dev/null +++ b/railties/lib/rails_generator/generators/components/controller/templates/helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class <%= class_name %>HelperTest < ActionView::TestCase +end diff --git a/railties/lib/rails_generator/generators/components/helper/USAGE b/railties/lib/rails_generator/generators/components/helper/USAGE new file mode 100644 index 0000000000..ef27ca617e --- /dev/null +++ b/railties/lib/rails_generator/generators/components/helper/USAGE @@ -0,0 +1,24 @@ +Description: + Stubs out a new helper. Pass the helper name, either + CamelCased or under_scored. + + To create a helper within a module, specify the helper name as a + path like 'parent_module/helper_name'. + + This generates a helper class in app/helpers and a helper test + suite in test/unit/helpers. + +Example: + `./script/generate helper CreditCard` + + Credit card helper. + Helper: app/helpers/credit_card_helper.rb + Test: test/unit/helpers/credit_card_helper_test.rb + +Modules Example: + `./script/generate helper 'admin/credit_card'` + + Credit card admin helper. + Helper: app/helpers/admin/credit_card_helper.rb + Test: test/unit/helpers/admin/credit_card_helper_test.rb + diff --git a/railties/lib/rails_generator/generators/components/helper/helper_generator.rb b/railties/lib/rails_generator/generators/components/helper/helper_generator.rb new file mode 100644 index 0000000000..f7831f7c7a --- /dev/null +++ b/railties/lib/rails_generator/generators/components/helper/helper_generator.rb @@ -0,0 +1,25 @@ +class HelperGenerator < Rails::Generator::NamedBase + def manifest + record do |m| + # Check for class naming collisions. + m.class_collisions class_path, "#{class_name}Helper", "#{class_name}HelperTest" + + # Helper and helper test directories. + m.directory File.join('app/helpers', class_path) + m.directory File.join('test/unit/helpers', class_path) + + # Helper and helper test class. + + m.template 'helper.rb', + File.join('app/helpers', + class_path, + "#{file_name}_helper.rb") + + m.template 'helper_test.rb', + File.join('test/unit/helpers', + class_path, + "#{file_name}_helper_test.rb") + + end + end +end diff --git a/railties/lib/rails_generator/generators/components/helper/templates/helper.rb b/railties/lib/rails_generator/generators/components/helper/templates/helper.rb new file mode 100644 index 0000000000..3fe2ecdc74 --- /dev/null +++ b/railties/lib/rails_generator/generators/components/helper/templates/helper.rb @@ -0,0 +1,2 @@ +module <%= class_name %>Helper +end diff --git a/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb new file mode 100644 index 0000000000..591e40900e --- /dev/null +++ b/railties/lib/rails_generator/generators/components/helper/templates/helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class <%= class_name %>HelperTest < ActionView::TestCase +end diff --git a/railties/lib/rails_generator/generators/components/resource/USAGE b/railties/lib/rails_generator/generators/components/resource/USAGE index 83cc9d7654..e6043f1de1 100644 --- a/railties/lib/rails_generator/generators/components/resource/USAGE +++ b/railties/lib/rails_generator/generators/components/resource/USAGE @@ -11,8 +11,8 @@ Description: You don't have to think up every attribute up front, but it helps to sketch out a few so you can start working with the resource immediately. - This creates a model, controller, tests and fixtures for both, and the - corresponding map.resources declaration in config/routes.rb + This creates a model, controller, helper, tests and fixtures for all of them, + and the corresponding map.resources declaration in config/routes.rb Unlike the scaffold generator, the resource generator does not create views or add any methods to the generated controller. diff --git a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb index ea6dd65bde..4ee2fbff63 100644 --- a/railties/lib/rails_generator/generators/components/resource/resource_generator.rb +++ b/railties/lib/rails_generator/generators/components/resource/resource_generator.rb @@ -40,6 +40,7 @@ class ResourceGenerator < Rails::Generator::NamedBase m.directory(File.join('app/views', controller_class_path, controller_file_name)) m.directory(File.join('test/functional', controller_class_path)) m.directory(File.join('test/unit', class_path)) + m.directory(File.join('test/unit/helpers', class_path)) m.dependency 'model', [name] + @args, :collision => :skip @@ -49,6 +50,7 @@ class ResourceGenerator < Rails::Generator::NamedBase m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb")) m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb")) + m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb")) m.route_resources controller_file_name end diff --git a/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb new file mode 100644 index 0000000000..061f64a5e3 --- /dev/null +++ b/railties/lib/rails_generator/generators/components/resource/templates/helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class <%= controller_class_name %>HelperTest < ActionView::TestCase +end diff --git a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb index ff0381da2a..2a5edeedb6 100644 --- a/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb +++ b/railties/lib/rails_generator/generators/components/scaffold/scaffold_generator.rb @@ -47,6 +47,7 @@ class ScaffoldGenerator < Rails::Generator::NamedBase m.directory(File.join('app/views/layouts', controller_class_path)) m.directory(File.join('test/functional', controller_class_path)) m.directory(File.join('test/unit', class_path)) + m.directory(File.join('test/unit/helpers', class_path)) m.directory(File.join('public/stylesheets', class_path)) for action in scaffold_views @@ -66,6 +67,7 @@ class ScaffoldGenerator < Rails::Generator::NamedBase m.template('functional_test.rb', File.join('test/functional', controller_class_path, "#{controller_file_name}_controller_test.rb")) m.template('helper.rb', File.join('app/helpers', controller_class_path, "#{controller_file_name}_helper.rb")) + m.template('helper_test.rb', File.join('test/unit/helpers', controller_class_path, "#{controller_file_name}_helper_test.rb")) m.route_resources controller_file_name diff --git a/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb b/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb new file mode 100644 index 0000000000..061f64a5e3 --- /dev/null +++ b/railties/lib/rails_generator/generators/components/scaffold/templates/helper_test.rb @@ -0,0 +1,4 @@ +require 'test_helper' + +class <%= controller_class_name %>HelperTest < ActionView::TestCase +end diff --git a/railties/lib/tasks/testing.rake b/railties/lib/tasks/testing.rake index 328bde7442..4242458672 100644 --- a/railties/lib/tasks/testing.rake +++ b/railties/lib/tasks/testing.rake @@ -7,7 +7,7 @@ def recent_tests(source_pattern, test_path, touched_since = 10.minutes.ago) tests = [] source_dir = File.dirname(path).split("/") source_file = File.basename(path, '.rb') - + # Support subdirs in app/models and app/controllers modified_test_path = source_dir.length > 2 ? "#{test_path}/" << source_dir[1..source_dir.length].join('/') : test_path @@ -18,7 +18,7 @@ def recent_tests(source_pattern, test_path, touched_since = 10.minutes.ago) # For modified files in app, run tests in subdirs too. ex. /test/functional/account/*_test.rb test = "#{modified_test_path}/#{File.basename(path, '.rb').sub("_controller","")}" FileList["#{test}/*_test.rb"].each { |f| tests.push f } if File.exist?(test) - + return tests end @@ -63,7 +63,7 @@ namespace :test do t.test_files = touched.uniq end Rake::Task['test:recent'].comment = "Test recent changes" - + Rake::TestTask.new(:uncommitted => "db:test:prepare") do |t| def t.file_list if File.directory?(".svn") @@ -82,7 +82,7 @@ namespace :test do unit_tests.uniq + functional_tests.uniq end - + t.libs << 'test' t.verbose = true end diff --git a/railties/test/generators/generator_test_helper.rb b/railties/test/generators/generator_test_helper.rb index 0901b215e4..01bf1c90bd 100644 --- a/railties/test/generators/generator_test_helper.rb +++ b/railties/test/generators/generator_test_helper.rb @@ -145,6 +145,19 @@ class GeneratorTestCase < Test::Unit::TestCase end end + # Asserts that the given helper test test was generated. + # It takes a name or symbol without the _helper_test part and an optional super class. + # The contents of the class source file is passed to a block. + def assert_generated_helper_test_for(name, parent = "ActionView::TestCase") + path = "test/unit/helpers/#{name.to_s.underscore}_helper_test" + # Have to pass the path without the "test/" part so that class_name_from_path will return a correct result + class_name = class_name_from_path(path.gsub(/^test\//, '')) + + assert_generated_class path,parent,class_name do |body| + yield body if block_given? + end + end + # Asserts that the given unit test was generated. # It takes a name or symbol without the _test part and an optional super class. # The contents of the class source file is passed to a block. @@ -172,19 +185,21 @@ class GeneratorTestCase < Test::Unit::TestCase # Asserts that the given class source file was generated. # It takes a path without the .rb part and an optional super class. # The contents of the class source file is passed to a block. - def assert_generated_class(path, parent = nil) + def assert_generated_class(path, parent = nil, class_name = class_name_from_path(path)) + assert_generated_file("#{path}.rb") do |body| + assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class" + yield body if block_given? + end + end + + def class_name_from_path(path) # FIXME: Sucky way to detect namespaced classes if path.split('/').size > 3 path =~ /\/?(\d+_)?(\w+)\/(\w+)$/ - class_name = "#{$2.camelize}::#{$3.camelize}" + "#{$2.camelize}::#{$3.camelize}" else path =~ /\/?(\d+_)?(\w+)$/ - class_name = $2.camelize - end - - assert_generated_file("#{path}.rb") do |body| - assert_match /class #{class_name}#{parent.nil? ? '':" < #{parent}"}/, body, "the file '#{path}.rb' should be a class" - yield body if block_given? + $2.camelize end end diff --git a/railties/test/generators/rails_controller_generator_test.rb b/railties/test/generators/rails_controller_generator_test.rb index f839ea97e6..43fbe972e2 100644 --- a/railties/test/generators/rails_controller_generator_test.rb +++ b/railties/test/generators/rails_controller_generator_test.rb @@ -11,6 +11,7 @@ class RailsControllerGeneratorTest < GeneratorTestCase assert_generated_controller_for :products assert_generated_functional_test_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products end def test_controller_generates_namespaced_controller @@ -19,24 +20,25 @@ class RailsControllerGeneratorTest < GeneratorTestCase assert_generated_controller_for "admin::products" assert_generated_functional_test_for "admin::products" assert_generated_helper_for "admin::products" + assert_generated_helper_test_for "admin::products" end def test_controller_generates_namespaced_and_not_namespaced_controllers - run_generator('controller', %w(products)) - - # We have to require the generated helper to show the problem because - # the test helpers just check for generated files and contents but - # do not actually load them. But they have to be loaded (as in a real environment) - # to make the second generator run fail - require "#{RAILS_ROOT}/app/helpers/products_helper" - - assert_nothing_raised do - begin - run_generator('controller', %w(admin::products)) - ensure - # cleanup - Object.send(:remove_const, :ProductsHelper) - end + run_generator('controller', %w(products)) + + # We have to require the generated helper to show the problem because + # the test helpers just check for generated files and contents but + # do not actually load them. But they have to be loaded (as in a real environment) + # to make the second generator run fail + require "#{RAILS_ROOT}/app/helpers/products_helper" + + assert_nothing_raised do + begin + run_generator('controller', %w(admin::products)) + ensure + # cleanup + Object.send(:remove_const, :ProductsHelper) end + end end end diff --git a/railties/test/generators/rails_helper_generator_test.rb b/railties/test/generators/rails_helper_generator_test.rb new file mode 100644 index 0000000000..8d05f555e6 --- /dev/null +++ b/railties/test/generators/rails_helper_generator_test.rb @@ -0,0 +1,36 @@ +require File.dirname(__FILE__) + '/generator_test_helper' + +class RailsHelperGeneratorTest < GeneratorTestCase + def test_helper_generates_helper + run_generator('helper', %w(products)) + + assert_generated_helper_for :products + assert_generated_helper_test_for :products + end + + def test_helper_generates_namespaced_helper + run_generator('helper', %w(admin::products)) + + assert_generated_helper_for "admin::products" + assert_generated_helper_test_for "admin::products" + end + + def test_helper_generates_namespaced_and_not_namespaced_helpers + run_generator('helper', %w(products)) + + # We have to require the generated helper to show the problem because + # the test helpers just check for generated files and contents but + # do not actually load them. But they have to be loaded (as in a real environment) + # to make the second generator run fail + require "#{RAILS_ROOT}/app/helpers/products_helper" + + assert_nothing_raised do + begin + run_generator('helper', %w(admin::products)) + ensure + # cleanup + Object.send(:remove_const, :ProductsHelper) + end + end + end +end diff --git a/railties/test/generators/rails_resource_generator_test.rb b/railties/test/generators/rails_resource_generator_test.rb index 45e4850ef5..1f5bd0ef1e 100644 --- a/railties/test/generators/rails_resource_generator_test.rb +++ b/railties/test/generators/rails_resource_generator_test.rb @@ -1,7 +1,6 @@ require 'generators/generator_test_helper' class RailsResourceGeneratorTest < GeneratorTestCase - def test_resource_generates_resources run_generator('resource', %w(Product name:string)) @@ -10,6 +9,7 @@ class RailsResourceGeneratorTest < GeneratorTestCase assert_generated_fixtures_for :products assert_generated_functional_test_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_migration :create_products assert_added_route_for :products end @@ -22,8 +22,8 @@ class RailsResourceGeneratorTest < GeneratorTestCase assert_generated_fixtures_for :products assert_generated_functional_test_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_skipped_migration :create_products assert_added_route_for :products end - end diff --git a/railties/test/generators/rails_scaffold_generator_test.rb b/railties/test/generators/rails_scaffold_generator_test.rb index de6b38dafe..926607f55c 100644 --- a/railties/test/generators/rails_scaffold_generator_test.rb +++ b/railties/test/generators/rails_scaffold_generator_test.rb @@ -2,7 +2,6 @@ require 'generators/generator_test_helper' require 'abstract_unit' class RailsScaffoldGeneratorTest < GeneratorTestCase - def test_scaffolded_names g = Rails::Generator::Base.instance('scaffold', %w(ProductLine)) assert_equal "ProductLines", g.controller_name @@ -43,6 +42,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase assert_generated_unit_test_for :product assert_generated_fixtures_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_stylesheet :scaffold assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" @@ -58,6 +58,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase assert_generated_unit_test_for :product assert_generated_fixtures_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_stylesheet :scaffold assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" assert_skipped_migration :create_products @@ -93,6 +94,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase assert_generated_unit_test_for :product assert_generated_fixtures_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_stylesheet :scaffold assert_generated_views_for :products, "index.html.erb", "new.html.erb", "edit.html.erb", "show.html.erb" @@ -126,6 +128,7 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase assert_generated_unit_test_for :product assert_generated_fixtures_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_stylesheet :scaffold assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" assert_skipped_migration :create_products @@ -140,10 +143,10 @@ class RailsScaffoldGeneratorTest < GeneratorTestCase assert_generated_unit_test_for :products assert_generated_fixtures_for :products assert_generated_helper_for :products + assert_generated_helper_test_for :products assert_generated_stylesheet :scaffold assert_generated_views_for :products, "index.html.erb","new.html.erb","edit.html.erb","show.html.erb" assert_skipped_migration :create_products assert_added_route_for :products end - end -- cgit v1.2.3 From d9b92ee11b33fed5c7a94a91415fa846705f7dd3 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Tue, 18 Nov 2008 14:23:13 +0100 Subject: Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH] --- railties/CHANGELOG | 2 + railties/Rakefile | 3 ++ railties/configs/locales/en.yml | 5 +++ railties/environments/environment.rb | 5 +++ railties/lib/initializer.rb | 31 ++++++++++++++ .../generators/applications/app/app_generator.rb | 4 ++ railties/test/initializer_test.rb | 49 +++++++++++++++++++++- 7 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 railties/configs/locales/en.yml (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index e6b90198ab..2af9946c69 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0/3.0* +* Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH] + * BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH] diff --git a/railties/Rakefile b/railties/Rakefile index c9541b0292..888bebc6dc 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -44,6 +44,7 @@ BASE_DIRS = %w( app config/environments config/initializers + config/locales components db doc @@ -199,6 +200,8 @@ task :copy_configs do cp "configs/initializers/inflections.rb", "#{PKG_DESTINATION}/config/initializers/inflections.rb" cp "configs/initializers/mime_types.rb", "#{PKG_DESTINATION}/config/initializers/mime_types.rb" + cp "configs/locales/en.yml", "#{PKG_DESTINATION}/config/locales/en.yml" + cp "environments/boot.rb", "#{PKG_DESTINATION}/config/boot.rb" cp "environments/environment.rb", "#{PKG_DESTINATION}/config/environment.rb" cp "environments/production.rb", "#{PKG_DESTINATION}/config/environments/production.rb" diff --git a/railties/configs/locales/en.yml b/railties/configs/locales/en.yml new file mode 100644 index 0000000000..f265c068d8 --- /dev/null +++ b/railties/configs/locales/en.yml @@ -0,0 +1,5 @@ +# Sample localization file for English. Add more files in this directory for other locales. +# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points. + +en: + hello: "Hello world" \ No newline at end of file diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index f27ccc6bb8..8fef8ff610 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -45,6 +45,11 @@ Rails::Initializer.run do |config| # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' + # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. + # All files from config/locales/*.rb,yml are added automatically. + # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] + # config.i18n.default_locale = :de + # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index e3a0e3bad1..3e97a17e0e 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -147,7 +147,10 @@ module Rails initialize_dependency_mechanism initialize_whiny_nils initialize_temporary_session_directory + initialize_time_zone + initialize_i18n + initialize_framework_settings initialize_framework_views @@ -504,6 +507,18 @@ Run `rake gems:install` to install the missing gems. end end + # Set the i18n configuration from config.i18n but special-case for the load_path which should be + # appended to what's already set instead of overwritten. + def initialize_i18n + configuration.i18n.each do |setting, value| + if setting == :load_path + I18n.load_path += value + else + I18n.send("#{setting}=", value) + end + end + end + # Initializes framework-specific settings for each of the loaded frameworks # (Configuration#frameworks). The available settings map to the accessors # on each of the corresponding Base classes. @@ -732,6 +747,9 @@ Run `rake gems:install` to install the missing gems. # timezone to :utc. attr_accessor :time_zone + # Accessor for i18n settings. + attr_accessor :i18n + # Create a new Configuration instance, initialized with the default # values. def initialize @@ -755,6 +773,7 @@ Run `rake gems:install` to install the missing gems. self.database_configuration_file = default_database_configuration_file self.routes_configuration_file = default_routes_configuration_file self.gems = default_gems + self.i18n = default_i18n for framework in default_frameworks self.send("#{framework}=", Rails::OrderedOptions.new) @@ -967,6 +986,18 @@ Run `rake gems:install` to install the missing gems. def default_gems [] end + + def default_i18n + i18n = Rails::OrderedOptions.new + i18n.load_path = [] + + if File.exist?(File.join(RAILS_ROOT, 'config', 'locales')) + i18n.load_path << Dir[File.join(RAILS_ROOT, 'config', 'locales', '*.{rb,yml}')] + i18n.load_path.flatten! + end + + i18n + end end end diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 8c9bc63fc6..d68c425871 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -65,6 +65,9 @@ class AppGenerator < Rails::Generator::Base m.template "configs/initializers/mime_types.rb", "config/initializers/mime_types.rb" m.template "configs/initializers/new_rails_defaults.rb", "config/initializers/new_rails_defaults.rb" + # Locale + m.template "configs/locales/en.yml", "config/locales/en.yml" + # Environments m.file "environments/boot.rb", "config/boot.rb" m.template "environments/environment.rb", "config/environment.rb", :assigns => { :freeze => options[:freeze], :app_name => @app_name, :app_secret => secret } @@ -143,6 +146,7 @@ class AppGenerator < Rails::Generator::Base app/views/layouts config/environments config/initializers + config/locales db doc lib diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 5147eeb482..9c045ed66a 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -18,7 +18,6 @@ class ConfigurationMock < Rails::Configuration end class Initializer_load_environment_Test < Test::Unit::TestCase - def test_load_environment_with_constant config = ConfigurationMock.new("#{File.dirname(__FILE__)}/fixtures/environment_with_constant.rb") assert_nil $initialize_test_set_from_env @@ -260,5 +259,51 @@ uses_mocha "Initializer plugin loading tests" do @initializer.load_plugins end end - end + +uses_mocha 'i18n settings' do + class InitializerSetupI18nTests < Test::Unit::TestCase + def test_no_config_locales_dir_present_should_return_empty_load_path + File.stubs(:exist?).returns(false) + assert_equal [], Rails::Configuration.new.i18n.load_path + end + + def test_config_locales_dir_present_should_be_added_to_load_path + File.stubs(:exist?).returns(true) + Dir.stubs(:[]).returns([ "my/test/locale.yml" ]) + assert_equal [ "my/test/locale.yml" ], Rails::Configuration.new.i18n.load_path + end + + def test_config_defaults_should_be_added_with_config_settings + File.stubs(:exist?).returns(true) + Dir.stubs(:[]).returns([ "my/test/locale.yml" ]) + + config = Rails::Configuration.new + config.i18n.load_path << "my/other/locale.yml" + + assert_equal [ "my/test/locale.yml", "my/other/locale.yml" ], config.i18n.load_path + end + + def test_config_defaults_and_settings_should_be_added_to_i18n_defaults + File.stubs(:exist?).returns(true) + Dir.stubs(:[]).returns([ "my/test/locale.yml" ]) + + config = Rails::Configuration.new + config.i18n.load_path << "my/other/locale.yml" + + Rails::Initializer.run(:initialize_i18n, config) + assert_equal [ + "./test/../../activesupport/lib/active_support/locale/en-US.yml", + "./test/../../actionpack/lib/action_view/locale/en-US.yml", + "my/test/locale.yml", + "my/other/locale.yml" ], I18n.load_path + end + + def test_setting_another_default_locale + config = Rails::Configuration.new + config.i18n.default_locale = :de + Rails::Initializer.run(:initialize_i18n, config) + assert_equal :de, I18n.default_locale + end + end +end \ No newline at end of file -- cgit v1.2.3 From 45ba4ec626b79dda8534f13b3eb01524e0734781 Mon Sep 17 00:00:00 2001 From: Matt Jones Date: Mon, 17 Nov 2008 14:03:46 -0500 Subject: add vendor/ back to load paths; catch errors in constant loading Signed-off-by: David Heinemeier Hansson --- railties/lib/initializer.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 3e97a17e0e..16abe62d1b 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -901,6 +901,7 @@ Run `rake gems:install` to install the missing gems. components config lib + vendor ).map { |dir| "#{root_path}/#{dir}" }.select { |dir| File.directory?(dir) } paths.concat builtin_directories -- cgit v1.2.3 From 252ca3e3e7e609a179f7559624811550bde05749 Mon Sep 17 00:00:00 2001 From: Thomas Fuchs Date: Tue, 18 Nov 2008 19:24:22 +0100 Subject: Update Prototype to 1.6.0.3 and update script.aculo.us to 1.8.2 --- railties/html/javascripts/controls.js | 144 +++++++-------- railties/html/javascripts/dragdrop.js | 329 ++++++++++++++++----------------- railties/html/javascripts/effects.js | 338 +++++++++++++++++----------------- 3 files changed, 410 insertions(+), 401 deletions(-) (limited to 'railties') diff --git a/railties/html/javascripts/controls.js b/railties/html/javascripts/controls.js index 5aaf0bb2b7..ca29aefdd1 100644 --- a/railties/html/javascripts/controls.js +++ b/railties/html/javascripts/controls.js @@ -1,22 +1,22 @@ // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) -// (c) 2005-2007 Ivan Krstic (http://blogs.law.harvard.edu/ivan) -// (c) 2005-2007 Jon Tirsen (http://www.tirsen.com) +// (c) 2005-2008 Ivan Krstic (http://blogs.law.harvard.edu/ivan) +// (c) 2005-2008 Jon Tirsen (http://www.tirsen.com) // Contributors: // Richard Livsey // Rahul Bhargava // Rob Wills -// +// // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ -// Autocompleter.Base handles all the autocompletion functionality +// Autocompleter.Base handles all the autocompletion functionality // that's independent of the data source for autocompletion. This // includes drawing the autocompletion menu, observing keyboard // and mouse events, and similar. // -// Specific autocompleters need to provide, at the very least, +// Specific autocompleters need to provide, at the very least, // a getUpdatedChoices function that will be invoked every time -// the text inside the monitored textbox changes. This method +// the text inside the monitored textbox changes. This method // should get the text for which to provide autocompletion by // invoking this.getToken(), NOT by directly accessing // this.element.value. This is to allow incremental tokenized @@ -30,23 +30,23 @@ // will incrementally autocomplete with a comma as the token. // Additionally, ',' in the above example can be replaced with // a token array, e.g. { tokens: [',', '\n'] } which -// enables autocompletion on multiple tokens. This is most -// useful when one of the tokens is \n (a newline), as it +// enables autocompletion on multiple tokens. This is most +// useful when one of the tokens is \n (a newline), as it // allows smart autocompletion after linebreaks. if(typeof Effect == 'undefined') throw("controls.js requires including script.aculo.us' effects.js library"); -var Autocompleter = { } +var Autocompleter = { }; Autocompleter.Base = Class.create({ baseInitialize: function(element, update, options) { - element = $(element) - this.element = element; - this.update = $(update); - this.hasFocus = false; - this.changed = false; - this.active = false; - this.index = 0; + element = $(element); + this.element = element; + this.update = $(update); + this.hasFocus = false; + this.changed = false; + this.active = false; + this.index = 0; this.entryCount = 0; this.oldElementValue = this.element.value; @@ -59,28 +59,28 @@ Autocompleter.Base = Class.create({ this.options.tokens = this.options.tokens || []; this.options.frequency = this.options.frequency || 0.4; this.options.minChars = this.options.minChars || 1; - this.options.onShow = this.options.onShow || - function(element, update){ + this.options.onShow = this.options.onShow || + function(element, update){ if(!update.style.position || update.style.position=='absolute') { update.style.position = 'absolute'; Position.clone(element, update, { - setHeight: false, + setHeight: false, offsetTop: element.offsetHeight }); } Effect.Appear(update,{duration:0.15}); }; - this.options.onHide = this.options.onHide || + this.options.onHide = this.options.onHide || function(element, update){ new Effect.Fade(update,{duration:0.15}) }; - if(typeof(this.options.tokens) == 'string') + if(typeof(this.options.tokens) == 'string') this.options.tokens = new Array(this.options.tokens); // Force carriage returns as token delimiters anyway if (!this.options.tokens.include('\n')) this.options.tokens.push('\n'); this.observer = null; - + this.element.setAttribute('autocomplete','off'); Element.hide(this.update); @@ -91,10 +91,10 @@ Autocompleter.Base = Class.create({ show: function() { if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); - if(!this.iefix && + if(!this.iefix && (Prototype.Browser.IE) && (Element.getStyle(this.update, 'position')=='absolute')) { - new Insertion.After(this.update, + new Insertion.After(this.update, ''); @@ -102,7 +102,7 @@ Autocompleter.Base = Class.create({ } if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); }, - + fixIEOverlapping: function() { Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)}); this.iefix.style.zIndex = 1; @@ -150,15 +150,15 @@ Autocompleter.Base = Class.create({ Event.stop(event); return; } - else - if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || (Prototype.Browser.WebKit > 0 && event.keyCode == 0)) return; this.changed = true; this.hasFocus = true; if(this.observer) clearTimeout(this.observer); - this.observer = + this.observer = setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); }, @@ -170,35 +170,35 @@ Autocompleter.Base = Class.create({ onHover: function(event) { var element = Event.findElement(event, 'LI'); - if(this.index != element.autocompleteIndex) + if(this.index != element.autocompleteIndex) { this.index = element.autocompleteIndex; this.render(); } Event.stop(event); }, - + onClick: function(event) { var element = Event.findElement(event, 'LI'); this.index = element.autocompleteIndex; this.selectEntry(); this.hide(); }, - + onBlur: function(event) { // needed to make click events working setTimeout(this.hide.bind(this), 250); this.hasFocus = false; - this.active = false; - }, - + this.active = false; + }, + render: function() { if(this.entryCount > 0) { for (var i = 0; i < this.entryCount; i++) - this.index==i ? - Element.addClassName(this.getEntry(i),"selected") : + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : Element.removeClassName(this.getEntry(i),"selected"); - if(this.hasFocus) { + if(this.hasFocus) { this.show(); this.active = true; } @@ -207,27 +207,27 @@ Autocompleter.Base = Class.create({ this.hide(); } }, - + markPrevious: function() { - if(this.index > 0) this.index-- + if(this.index > 0) this.index--; else this.index = this.entryCount-1; this.getEntry(this.index).scrollIntoView(true); }, - + markNext: function() { - if(this.index < this.entryCount-1) this.index++ + if(this.index < this.entryCount-1) this.index++; else this.index = 0; this.getEntry(this.index).scrollIntoView(false); }, - + getEntry: function(index) { return this.update.firstChild.childNodes[index]; }, - + getCurrentEntry: function() { return this.getEntry(this.index); }, - + selectEntry: function() { this.active = false; this.updateElement(this.getCurrentEntry()); @@ -244,7 +244,7 @@ Autocompleter.Base = Class.create({ if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); } else value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); - + var bounds = this.getTokenBounds(); if (bounds[0] != -1) { var newValue = this.element.value.substr(0, bounds[0]); @@ -257,7 +257,7 @@ Autocompleter.Base = Class.create({ } this.oldElementValue = this.element.value; this.element.focus(); - + if (this.options.afterUpdateElement) this.options.afterUpdateElement(this.element, selectedElement); }, @@ -269,20 +269,20 @@ Autocompleter.Base = Class.create({ Element.cleanWhitespace(this.update.down()); if(this.update.firstChild && this.update.down().childNodes) { - this.entryCount = + this.entryCount = this.update.down().childNodes.length; for (var i = 0; i < this.entryCount; i++) { var entry = this.getEntry(i); entry.autocompleteIndex = i; this.addObservers(entry); } - } else { + } else { this.entryCount = 0; } this.stopIndicator(); this.index = 0; - + if(this.entryCount==1 && this.options.autoSelect) { this.selectEntry(); this.hide(); @@ -298,7 +298,7 @@ Autocompleter.Base = Class.create({ }, onObserverEvent: function() { - this.changed = false; + this.changed = false; this.tokenBounds = null; if(this.getToken().length>=this.options.minChars) { this.getUpdatedChoices(); @@ -351,16 +351,16 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, { getUpdatedChoices: function() { this.startIndicator(); - - var entry = encodeURIComponent(this.options.paramName) + '=' + + + var entry = encodeURIComponent(this.options.paramName) + '=' + encodeURIComponent(this.getToken()); this.options.parameters = this.options.callback ? this.options.callback(this.element, entry) : entry; - if(this.options.defaultParams) + if(this.options.defaultParams) this.options.parameters += '&' + this.options.defaultParams; - + new Ajax.Request(this.url, this.options); }, @@ -382,7 +382,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, { // - choices - How many autocompletion choices to offer // // - partialSearch - If false, the autocompleter will match entered -// text only at the beginning of strings in the +// text only at the beginning of strings in the // autocomplete array. Defaults to true, which will // match text at the beginning of any *word* in the // strings in the autocomplete array. If you want to @@ -399,7 +399,7 @@ Ajax.Autocompleter = Class.create(Autocompleter.Base, { // - ignoreCase - Whether to ignore case when autocompleting. // Defaults to true. // -// It's possible to pass in a custom function as the 'selector' +// It's possible to pass in a custom function as the 'selector' // option, if you prefer to write your own autocompletion logic. // In that case, the other options above will not apply unless // you support them. @@ -427,20 +427,20 @@ Autocompleter.Local = Class.create(Autocompleter.Base, { var entry = instance.getToken(); var count = 0; - for (var i = 0; i < instance.options.array.length && - ret.length < instance.options.choices ; i++) { + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { var elem = instance.options.array[i]; - var foundPos = instance.options.ignoreCase ? - elem.toLowerCase().indexOf(entry.toLowerCase()) : + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : elem.indexOf(entry); while (foundPos != -1) { - if (foundPos == 0 && elem.length != entry.length) { - ret.push("
  • " + elem.substr(0, entry.length) + "" + + if (foundPos == 0 && elem.length != entry.length) { + ret.push("
  • " + elem.substr(0, entry.length) + "" + elem.substr(entry.length) + "
  • "); break; - } else if (entry.length >= instance.options.partialChars && + } else if (entry.length >= instance.options.partialChars && instance.options.partialSearch && foundPos != -1) { if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { partial.push("
  • " + elem.substr(0, foundPos) + "" + @@ -450,14 +450,14 @@ Autocompleter.Local = Class.create(Autocompleter.Base, { } } - foundPos = instance.options.ignoreCase ? - elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : elem.indexOf(entry, foundPos + 1); } } if (partial.length) - ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)); return "
      " + ret.join('') + "
    "; } }, options || { }); @@ -474,7 +474,7 @@ Field.scrollFreeActivate = function(field) { setTimeout(function() { Field.activate(field); }, 1); -} +}; Ajax.InPlaceEditor = Class.create({ initialize: function(element, url, options) { @@ -604,7 +604,7 @@ Ajax.InPlaceEditor = Class.create({ this.triggerCallback('onEnterHover'); }, getText: function() { - return this.element.innerHTML; + return this.element.innerHTML.unescapeHTML(); }, handleAJAXFailure: function(transport) { this.triggerCallback('onFailure', transport); @@ -780,7 +780,7 @@ Ajax.InPlaceCollectionEditor = Class.create(Ajax.InPlaceEditor, { onSuccess: function(transport) { var js = transport.responseText.strip(); if (!/^\[.*\]$/.test(js)) // TODO: improve sanity check - throw 'Server returned an invalid collection representation.'; + throw('Server returned an invalid collection representation.'); this._collection = eval(js); this.checkForExternalText(); }.bind(this), @@ -937,7 +937,7 @@ Ajax.InPlaceCollectionEditor.DefaultOptions = { loadingCollectionText: 'Loading options...' }; -// Delayed observer, like Form.Element.Observer, +// Delayed observer, like Form.Element.Observer, // but waits for delay after last key input // Ideal for live-search fields @@ -947,7 +947,7 @@ Form.Element.DelayedObserver = Class.create({ this.element = $(element); this.callback = callback; this.timer = null; - this.lastValue = $F(this.element); + this.lastValue = $F(this.element); Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); }, delayedListener: function(event) { @@ -960,4 +960,4 @@ Form.Element.DelayedObserver = Class.create({ this.timer = null; this.callback(this.element, $F(this.element)); } -}); +}); \ No newline at end of file diff --git a/railties/html/javascripts/dragdrop.js b/railties/html/javascripts/dragdrop.js index bf5cfea66c..07229f986f 100644 --- a/railties/html/javascripts/dragdrop.js +++ b/railties/html/javascripts/dragdrop.js @@ -1,6 +1,6 @@ // Copyright (c) 2005-2008 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) -// (c) 2005-2007 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) -// +// (c) 2005-2008 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// // script.aculo.us is freely distributable under the terms of an MIT-style license. // For details, see the script.aculo.us web site: http://script.aculo.us/ @@ -32,7 +32,7 @@ var Droppables = { options._containers.push($(containment)); } } - + if(options.accept) options.accept = [options.accept].flatten(); Element.makePositioned(element); // fix IE @@ -40,34 +40,34 @@ var Droppables = { this.drops.push(options); }, - + findDeepestChild: function(drops) { deepest = drops[0]; - + for (i = 1; i < drops.length; ++i) if (Element.isParent(drops[i].element, deepest.element)) deepest = drops[i]; - + return deepest; }, isContained: function(element, drop) { var containmentNode; if(drop.tree) { - containmentNode = element.treeNode; + containmentNode = element.treeNode; } else { containmentNode = element.parentNode; } return drop._containers.detect(function(c) { return containmentNode == c }); }, - + isAffected: function(point, element, drop) { return ( (drop.element!=element) && ((!drop._containers) || this.isContained(element, drop)) && ((!drop.accept) || - (Element.classNames(element).detect( + (Element.classNames(element).detect( function(v) { return drop.accept.include(v) } ) )) && Position.within(drop.element, point[0], point[1]) ); }, @@ -87,12 +87,12 @@ var Droppables = { show: function(point, element) { if(!this.drops.length) return; var drop, affected = []; - + this.drops.each( function(drop) { if(Droppables.isAffected(point, element, drop)) affected.push(drop); }); - + if(affected.length>0) drop = Droppables.findDeepestChild(affected); @@ -101,7 +101,7 @@ var Droppables = { Position.within(drop.element, point[0], point[1]); if(drop.onHover) drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); - + if (drop != this.last_active) Droppables.activate(drop); } }, @@ -112,8 +112,8 @@ var Droppables = { if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) if (this.last_active.onDrop) { - this.last_active.onDrop(element, this.last_active.element, event); - return true; + this.last_active.onDrop(element, this.last_active.element, event); + return true; } }, @@ -121,25 +121,25 @@ var Droppables = { if(this.last_active) this.deactivate(this.last_active); } -} +}; var Draggables = { drags: [], observers: [], - + register: function(draggable) { if(this.drags.length == 0) { this.eventMouseUp = this.endDrag.bindAsEventListener(this); this.eventMouseMove = this.updateDrag.bindAsEventListener(this); this.eventKeypress = this.keyPress.bindAsEventListener(this); - + Event.observe(document, "mouseup", this.eventMouseUp); Event.observe(document, "mousemove", this.eventMouseMove); Event.observe(document, "keypress", this.eventKeypress); } this.drags.push(draggable); }, - + unregister: function(draggable) { this.drags = this.drags.reject(function(d) { return d==draggable }); if(this.drags.length == 0) { @@ -148,24 +148,24 @@ var Draggables = { Event.stopObserving(document, "keypress", this.eventKeypress); } }, - + activate: function(draggable) { - if(draggable.options.delay) { - this._timeout = setTimeout(function() { - Draggables._timeout = null; - window.focus(); - Draggables.activeDraggable = draggable; - }.bind(this), draggable.options.delay); + if(draggable.options.delay) { + this._timeout = setTimeout(function() { + Draggables._timeout = null; + window.focus(); + Draggables.activeDraggable = draggable; + }.bind(this), draggable.options.delay); } else { window.focus(); // allows keypress events if window isn't currently focused, fails for Safari this.activeDraggable = draggable; } }, - + deactivate: function() { this.activeDraggable = null; }, - + updateDrag: function(event) { if(!this.activeDraggable) return; var pointer = [Event.pointerX(event), Event.pointerY(event)]; @@ -173,36 +173,36 @@ var Draggables = { // the same coordinates, prevent needless redrawing (moz bug?) if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; this._lastPointer = pointer; - + this.activeDraggable.updateDrag(event, pointer); }, - + endDrag: function(event) { - if(this._timeout) { - clearTimeout(this._timeout); - this._timeout = null; + if(this._timeout) { + clearTimeout(this._timeout); + this._timeout = null; } if(!this.activeDraggable) return; this._lastPointer = null; this.activeDraggable.endDrag(event); this.activeDraggable = null; }, - + keyPress: function(event) { if(this.activeDraggable) this.activeDraggable.keyPress(event); }, - + addObserver: function(observer) { this.observers.push(observer); this._cacheObserverCallbacks(); }, - + removeObserver: function(element) { // element instead of observer fixes mem leaks this.observers = this.observers.reject( function(o) { return o.element==element }); this._cacheObserverCallbacks(); }, - + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' if(this[eventName+'Count'] > 0) this.observers.each( function(o) { @@ -210,7 +210,7 @@ var Draggables = { }); if(draggable.options[eventName]) draggable.options[eventName](draggable, event); }, - + _cacheObserverCallbacks: function() { ['onStart','onEnd','onDrag'].each( function(eventName) { Draggables[eventName+'Count'] = Draggables.observers.select( @@ -218,7 +218,7 @@ var Draggables = { ).length; }); } -} +}; /*--------------------------------------------------------------------------*/ @@ -234,12 +234,12 @@ var Draggable = Class.create({ }, endeffect: function(element) { var toOpacity = Object.isNumber(element._opacity) ? element._opacity : 1.0; - new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity, queue: {scope:'_draggable', position:'end'}, - afterFinish: function(){ - Draggable._dragging[element] = false + afterFinish: function(){ + Draggable._dragging[element] = false } - }); + }); }, zindex: 1000, revert: false, @@ -250,57 +250,57 @@ var Draggable = Class.create({ snap: false, // false, or xy or [x,y] or function(x,y){ return [x,y] } delay: 0 }; - + if(!arguments[1] || Object.isUndefined(arguments[1].endeffect)) Object.extend(defaults, { starteffect: function(element) { element._opacity = Element.getOpacity(element); Draggable._dragging[element] = true; - new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); } }); - + var options = Object.extend(defaults, arguments[1] || { }); this.element = $(element); - + if(options.handle && Object.isString(options.handle)) this.handle = this.element.down('.'+options.handle, 0); - + if(!this.handle) this.handle = $(options.handle); if(!this.handle) this.handle = this.element; - + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) { options.scroll = $(options.scroll); this._isScrollChild = Element.childOf(this.element, options.scroll); } - Element.makePositioned(this.element); // fix IE + Element.makePositioned(this.element); // fix IE this.options = options; - this.dragging = false; + this.dragging = false; this.eventMouseDown = this.initDrag.bindAsEventListener(this); Event.observe(this.handle, "mousedown", this.eventMouseDown); - + Draggables.register(this); }, - + destroy: function() { Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); Draggables.unregister(this); }, - + currentDelta: function() { return([ parseInt(Element.getStyle(this.element,'left') || '0'), parseInt(Element.getStyle(this.element,'top') || '0')]); }, - + initDrag: function(event) { if(!Object.isUndefined(Draggable._dragging[this.element]) && Draggable._dragging[this.element]) return; - if(Event.isLeftClick(event)) { + if(Event.isLeftClick(event)) { // abort on form elements, fixes a Firefox issue var src = Event.element(event); if((tag_name = src.tagName.toUpperCase()) && ( @@ -309,34 +309,34 @@ var Draggable = Class.create({ tag_name=='OPTION' || tag_name=='BUTTON' || tag_name=='TEXTAREA')) return; - + var pointer = [Event.pointerX(event), Event.pointerY(event)]; var pos = Position.cumulativeOffset(this.element); this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); - + Draggables.activate(this); Event.stop(event); } }, - + startDrag: function(event) { this.dragging = true; if(!this.delta) this.delta = this.currentDelta(); - + if(this.options.zindex) { this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); this.element.style.zIndex = this.options.zindex; } - + if(this.options.ghosting) { this._clone = this.element.cloneNode(true); - this.element._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); - if (!this.element._originallyAbsolute) + this._originallyAbsolute = (this.element.getStyle('position') == 'absolute'); + if (!this._originallyAbsolute) Position.absolutize(this.element); this.element.parentNode.insertBefore(this._clone, this.element); } - + if(this.options.scroll) { if (this.options.scroll == window) { var where = this._getWindowScroll(this.options.scroll); @@ -347,28 +347,28 @@ var Draggable = Class.create({ this.originalScrollTop = this.options.scroll.scrollTop; } } - + Draggables.notify('onStart', this, event); - + if(this.options.starteffect) this.options.starteffect(this.element); }, - + updateDrag: function(event, pointer) { if(!this.dragging) this.startDrag(event); - + if(!this.options.quiet){ Position.prepare(); Droppables.show(pointer, this.element); } - + Draggables.notify('onDrag', this, event); - + this.draw(pointer); if(this.options.change) this.options.change(this); - + if(this.options.scroll) { this.stopScrolling(); - + var p; if (this.options.scroll == window) { with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } @@ -386,16 +386,16 @@ var Draggable = Class.create({ if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); this.startScrolling(speed); } - + // fix AppleWebKit rendering if(Prototype.Browser.WebKit) window.scrollBy(0,0); - + Event.stop(event); }, - + finishDrag: function(event, success) { this.dragging = false; - + if(this.options.quiet){ Position.prepare(); var pointer = [Event.pointerX(event), Event.pointerY(event)]; @@ -403,24 +403,24 @@ var Draggable = Class.create({ } if(this.options.ghosting) { - if (!this.element._originallyAbsolute) + if (!this._originallyAbsolute) Position.relativize(this.element); - delete this.element._originallyAbsolute; + delete this._originallyAbsolute; Element.remove(this._clone); this._clone = null; } - var dropped = false; - if(success) { - dropped = Droppables.fire(event, this.element); - if (!dropped) dropped = false; + var dropped = false; + if(success) { + dropped = Droppables.fire(event, this.element); + if (!dropped) dropped = false; } if(dropped && this.options.onDropped) this.options.onDropped(this.element); Draggables.notify('onEnd', this, event); var revert = this.options.revert; if(revert && Object.isFunction(revert)) revert = revert(this.element); - + var d = this.currentDelta(); if(revert && this.options.reverteffect) { if (dropped == 0 || revert != 'failure') @@ -433,67 +433,67 @@ var Draggable = Class.create({ if(this.options.zindex) this.element.style.zIndex = this.originalZ; - if(this.options.endeffect) + if(this.options.endeffect) this.options.endeffect(this.element); - + Draggables.deactivate(this); Droppables.reset(); }, - + keyPress: function(event) { if(event.keyCode!=Event.KEY_ESC) return; this.finishDrag(event, false); Event.stop(event); }, - + endDrag: function(event) { if(!this.dragging) return; this.stopScrolling(); this.finishDrag(event, true); Event.stop(event); }, - + draw: function(point) { var pos = Position.cumulativeOffset(this.element); if(this.options.ghosting) { var r = Position.realOffset(this.element); pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY; } - + var d = this.currentDelta(); pos[0] -= d[0]; pos[1] -= d[1]; - + if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) { pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; } - - var p = [0,1].map(function(i){ - return (point[i]-pos[i]-this.offset[i]) + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) }.bind(this)); - + if(this.options.snap) { if(Object.isFunction(this.options.snap)) { p = this.options.snap(p[0],p[1],this); } else { if(Object.isArray(this.options.snap)) { p = p.map( function(v, i) { - return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)) + return (v/this.options.snap[i]).round()*this.options.snap[i] }.bind(this)); } else { p = p.map( function(v) { - return (v/this.options.snap).round()*this.options.snap }.bind(this)) + return (v/this.options.snap).round()*this.options.snap }.bind(this)); } }} - + var style = this.element.style; if((!this.options.constraint) || (this.options.constraint=='horizontal')) style.left = p[0] + "px"; if((!this.options.constraint) || (this.options.constraint=='vertical')) style.top = p[1] + "px"; - + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering }, - + stopScrolling: function() { if(this.scrollInterval) { clearInterval(this.scrollInterval); @@ -501,14 +501,14 @@ var Draggable = Class.create({ Draggables._lastScrollPointer = null; } }, - + startScrolling: function(speed) { if(!(speed[0] || speed[1])) return; this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; this.lastScrolled = new Date(); this.scrollInterval = setInterval(this.scroll.bind(this), 10); }, - + scroll: function() { var current = new Date(); var delta = current - this.lastScrolled; @@ -524,7 +524,7 @@ var Draggable = Class.create({ this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; } - + Position.prepare(); Droppables.show(Draggables._lastPointer, this.element); Draggables.notify('onDrag', this); @@ -538,10 +538,10 @@ var Draggable = Class.create({ Draggables._lastScrollPointer[1] = 0; this.draw(Draggables._lastScrollPointer); } - + if(this.options.change) this.options.change(this); }, - + _getWindowScroll: function(w) { var T, L, W, H; with (w.document) { @@ -560,7 +560,7 @@ var Draggable = Class.create({ H = documentElement.clientHeight; } else { W = body.offsetWidth; - H = body.offsetHeight + H = body.offsetHeight; } } return { top: T, left: L, width: W, height: H }; @@ -577,11 +577,11 @@ var SortableObserver = Class.create({ this.observer = observer; this.lastValue = Sortable.serialize(this.element); }, - + onStart: function() { this.lastValue = Sortable.serialize(this.element); }, - + onEnd: function() { Sortable.unmark(); if(this.lastValue != Sortable.serialize(this.element)) @@ -591,11 +591,11 @@ var SortableObserver = Class.create({ var Sortable = { SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/, - + sortables: { }, - + _findRootElement: function(element) { - while (element.tagName.toUpperCase() != "BODY") { + while (element.tagName.toUpperCase() != "BODY") { if(element.id && Sortable.sortables[element.id]) return element; element = element.parentNode; } @@ -606,22 +606,23 @@ var Sortable = { if(!element) return; return Sortable.sortables[element.id]; }, - + destroy: function(element){ - var s = Sortable.options(element); - + element = $(element); + var s = Sortable.sortables[element.id]; + if(s) { Draggables.removeObserver(s.element); s.droppables.each(function(d){ Droppables.remove(d) }); s.draggables.invoke('destroy'); - + delete Sortable.sortables[s.element.id]; } }, create: function(element) { element = $(element); - var options = Object.extend({ + var options = Object.extend({ element: element, tag: 'li', // assumes li children, override with tag: 'tagname' dropOnEmpty: false, @@ -635,17 +636,17 @@ var Sortable = { delay: 0, hoverclass: null, ghosting: false, - quiet: false, + quiet: false, scroll: false, scrollSensitivity: 20, scrollSpeed: 15, format: this.SERIALIZE_RULE, - - // these take arrays of elements or ids and can be + + // these take arrays of elements or ids and can be // used for better initialization performance elements: false, handles: false, - + onChange: Prototype.emptyFunction, onUpdate: Prototype.emptyFunction }, arguments[1] || { }); @@ -682,24 +683,24 @@ var Sortable = { if(options.zindex) options_for_draggable.zindex = options.zindex; - // build options for the droppables + // build options for the droppables var options_for_droppable = { overlap: options.overlap, containment: options.containment, tree: options.tree, hoverclass: options.hoverclass, onHover: Sortable.onHover - } - + }; + var options_for_tree = { onHover: Sortable.onEmptyHover, overlap: options.overlap, containment: options.containment, hoverclass: options.hoverclass - } + }; // fix for gecko engine - Element.cleanWhitespace(element); + Element.cleanWhitespace(element); options.draggables = []; options.droppables = []; @@ -712,14 +713,14 @@ var Sortable = { (options.elements || this.findElements(element, options) || []).each( function(e,i) { var handle = options.handles ? $(options.handles[i]) : - (options.handle ? $(e).select('.' + options.handle)[0] : e); + (options.handle ? $(e).select('.' + options.handle)[0] : e); options.draggables.push( new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); Droppables.add(e, options_for_droppable); if(options.tree) e.treeNode = element; - options.droppables.push(e); + options.droppables.push(e); }); - + if(options.tree) { (Sortable.findTreeElements(element, options) || []).each( function(e) { Droppables.add(e, options_for_tree); @@ -741,7 +742,7 @@ var Sortable = { return Element.findChildren( element, options.only, options.tree ? true : false, options.tag); }, - + findTreeElements: function(element, options) { return Element.findChildren( element, options.only, options.tree ? true : false, options.treeTag); @@ -758,7 +759,7 @@ var Sortable = { var oldParentNode = element.parentNode; element.style.visibility = "hidden"; // fix gecko rendering dropon.parentNode.insertBefore(element, dropon); - if(dropon.parentNode!=oldParentNode) + if(dropon.parentNode!=oldParentNode) Sortable.options(oldParentNode).onChange(element); Sortable.options(dropon.parentNode).onChange(element); } @@ -769,26 +770,26 @@ var Sortable = { var oldParentNode = element.parentNode; element.style.visibility = "hidden"; // fix gecko rendering dropon.parentNode.insertBefore(element, nextElement); - if(dropon.parentNode!=oldParentNode) + if(dropon.parentNode!=oldParentNode) Sortable.options(oldParentNode).onChange(element); Sortable.options(dropon.parentNode).onChange(element); } } }, - + onEmptyHover: function(element, dropon, overlap) { var oldParentNode = element.parentNode; var droponOptions = Sortable.options(dropon); - + if(!Element.isParent(dropon, element)) { var index; - + var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only}); var child = null; - + if(children) { var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); - + for (index = 0; index < children.length; index += 1) { if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { offset -= Element.offsetSize (children[index], droponOptions.overlap); @@ -801,9 +802,9 @@ var Sortable = { } } } - + dropon.insertBefore(element, child); - + Sortable.options(oldParentNode).onChange(element); droponOptions.onChange(element); } @@ -816,34 +817,34 @@ var Sortable = { mark: function(dropon, position) { // mark on ghosting only var sortable = Sortable.options(dropon.parentNode); - if(sortable && !sortable.ghosting) return; + if(sortable && !sortable.ghosting) return; if(!Sortable._marker) { - Sortable._marker = + Sortable._marker = ($('dropmarker') || Element.extend(document.createElement('DIV'))). hide().addClassName('dropmarker').setStyle({position:'absolute'}); document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); - } + } var offsets = Position.cumulativeOffset(dropon); Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'}); - + if(position=='after') - if(sortable.overlap == 'horizontal') + if(sortable.overlap == 'horizontal') Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'}); else Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'}); - + Sortable._marker.show(); }, - + _tree: function(element, options, parent) { var children = Sortable.findElements(element, options) || []; - + for (var i = 0; i < children.length; ++i) { var match = children[i].id.match(options.format); if (!match) continue; - + var child = { id: encodeURIComponent(match ? match[1] : null), element: element, @@ -851,16 +852,16 @@ var Sortable = { children: [], position: parent.children.length, container: $(children[i]).down(options.treeTag) - } - + }; + /* Get the element containing the children and recurse over it */ if (child.container) - this._tree(child.container, options, child) - + this._tree(child.container, options, child); + parent.children.push (child); } - return parent; + return parent; }, tree: function(element) { @@ -873,15 +874,15 @@ var Sortable = { name: element.id, format: sortableOptions.format }, arguments[1] || { }); - + var root = { id: null, parent: null, children: [], container: element, position: 0 - } - + }; + return Sortable._tree(element, options, root); }, @@ -897,7 +898,7 @@ var Sortable = { sequence: function(element) { element = $(element); var options = Object.extend(this.options(element), arguments[1] || { }); - + return $(this.findElements(element, options) || []).map( function(item) { return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; }); @@ -906,14 +907,14 @@ var Sortable = { setSequence: function(element, new_sequence) { element = $(element); var options = Object.extend(this.options(element), arguments[2] || { }); - + var nodeMap = { }; this.findElements(element, options).each( function(n) { if (n.id.match(options.format)) nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; n.parentNode.removeChild(n); }); - + new_sequence.each(function(ident) { var n = nodeMap[ident]; if (n) { @@ -922,16 +923,16 @@ var Sortable = { } }); }, - + serialize: function(element) { element = $(element); var options = Object.extend(Sortable.options(element), arguments[1] || { }); var name = encodeURIComponent( (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); - + if (options.tree) { return Sortable.tree(element, arguments[1]).children.map( function (item) { - return [name + Sortable._constructIndex(item) + "[id]=" + + return [name + Sortable._constructIndex(item) + "[id]=" + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); }).flatten().join('&'); } else { @@ -940,16 +941,16 @@ var Sortable = { }).join('&'); } } -} +}; // Returns true if child is contained within element Element.isParent = function(child, element) { if (!child.parentNode || child == element) return false; if (child.parentNode == element) return true; return Element.isParent(child.parentNode, element); -} +}; -Element.findChildren = function(element, only, recursive, tagName) { +Element.findChildren = function(element, only, recursive, tagName) { if(!element.hasChildNodes()) return null; tagName = tagName.toUpperCase(); if(only) only = [only].flatten(); @@ -965,8 +966,8 @@ Element.findChildren = function(element, only, recursive, tagName) { }); return (elements.length>0 ? elements.flatten() : []); -} +}; Element.offsetSize = function (element, type) { return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')]; -} +}; \ No newline at end of file diff --git a/railties/html/javascripts/effects.js b/railties/html/javascripts/effects.js index f030b5dbe9..5a639d2dea 100644 --- a/railties/html/javascripts/effects.js +++ b/railties/html/javascripts/effects.js @@ -3,46 +3,46 @@ // Justin Palmer (http://encytemedia.com/) // Mark Pilgrim (http://diveintomark.org/) // Martin Bialasinki -// +// // script.aculo.us is freely distributable under the terms of an MIT-style license. -// For details, see the script.aculo.us web site: http://script.aculo.us/ +// For details, see the script.aculo.us web site: http://script.aculo.us/ -// converts rgb() and #xxx to #xxxxxx format, -// returns self (or first argument) if not convertable -String.prototype.parseColor = function() { +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { var color = '#'; - if (this.slice(0,4) == 'rgb(') { - var cols = this.slice(4,this.length-1).split(','); - var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); - } else { - if (this.slice(0,1) == '#') { - if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); - if (this.length==7) color = this.toLowerCase(); - } - } - return (color.length==7 ? color : (arguments[0] || this)); + if (this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if (this.slice(0,1) == '#') { + if (this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if (this.length==7) color = this.toLowerCase(); + } + } + return (color.length==7 ? color : (arguments[0] || this)); }; /*--------------------------------------------------------------------------*/ -Element.collectTextNodes = function(element) { +Element.collectTextNodes = function(element) { return $A($(element).childNodes).collect( function(node) { - return (node.nodeType==3 ? node.nodeValue : + return (node.nodeType==3 ? node.nodeValue : (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); }).flatten().join(''); }; -Element.collectTextNodesIgnoreClass = function(element, className) { +Element.collectTextNodesIgnoreClass = function(element, className) { return $A($(element).childNodes).collect( function(node) { - return (node.nodeType==3 ? node.nodeValue : - ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? Element.collectTextNodesIgnoreClass(node, className) : '')); }).flatten().join(''); }; Element.setContentZoom = function(element, percent) { - element = $(element); - element.setStyle({fontSize: (percent/100) + 'em'}); + element = $(element); + element.setStyle({fontSize: (percent/100) + 'em'}); if (Prototype.Browser.WebKit) window.scrollBy(0,0); return element; }; @@ -70,28 +70,23 @@ var Effect = { Transitions: { linear: Prototype.K, sinoidal: function(pos) { - return (-Math.cos(pos*Math.PI)/2) + 0.5; + return (-Math.cos(pos*Math.PI)/2) + .5; }, reverse: function(pos) { return 1-pos; }, flicker: function(pos) { - var pos = ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; + var pos = ((-Math.cos(pos*Math.PI)/4) + .75) + Math.random()/4; return pos > 1 ? 1 : pos; }, wobble: function(pos) { - return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; + return (-Math.cos(pos*Math.PI*(9*pos))/2) + .5; }, - pulse: function(pos, pulses) { - pulses = pulses || 5; - return ( - ((pos % (1/pulses)) * pulses).round() == 0 ? - ((pos * pulses * 2) - (pos * pulses * 2).floor()) : - 1 - ((pos * pulses * 2) - (pos * pulses * 2).floor()) - ); + pulse: function(pos, pulses) { + return (-Math.cos((pos*((pulses||5)-.5)*2)*Math.PI)/2) + .5; }, - spring: function(pos) { - return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); + spring: function(pos) { + return 1 - (Math.cos(pos * 4.5 * Math.PI) * Math.exp(-pos * 6)); }, none: function(pos) { return 0; @@ -112,14 +107,14 @@ var Effect = { tagifyText: function(element) { var tagifyStyle = 'position:relative'; if (Prototype.Browser.IE) tagifyStyle += ';zoom:1'; - + element = $(element); $A(element.childNodes).each( function(child) { if (child.nodeType==3) { child.nodeValue.toArray().each( function(character) { element.insertBefore( new Element('span', {style: tagifyStyle}).update( - character == ' ' ? String.fromCharCode(160) : character), + character == ' ' ? String.fromCharCode(160) : character), child); }); Element.remove(child); @@ -128,13 +123,13 @@ var Effect = { }, multiple: function(element, effect) { var elements; - if (((typeof element == 'object') || - Object.isFunction(element)) && + if (((typeof element == 'object') || + Object.isFunction(element)) && (element.length)) elements = element; else elements = $(element).childNodes; - + var options = Object.extend({ speed: 0.1, delay: 0.0 @@ -156,7 +151,7 @@ var Effect = { var options = Object.extend({ queue: { position:'end', scope:(element.id || 'global'), limit: 1 } }, arguments[2] || { }); - Effect[element.visible() ? + Effect[element.visible() ? Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); } }; @@ -168,20 +163,20 @@ Effect.DefaultOptions.transition = Effect.Transitions.sinoidal; Effect.ScopedQueue = Class.create(Enumerable, { initialize: function() { this.effects = []; - this.interval = null; + this.interval = null; }, _each: function(iterator) { this.effects._each(iterator); }, add: function(effect) { var timestamp = new Date().getTime(); - - var position = Object.isString(effect.options.queue) ? + + var position = Object.isString(effect.options.queue) ? effect.options.queue : effect.options.queue.position; - + switch(position) { case 'front': - // move unstarted effects after this effect + // move unstarted effects after this effect this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { e.startOn += effect.finishOn; e.finishOn += effect.finishOn; @@ -195,13 +190,13 @@ Effect.ScopedQueue = Class.create(Enumerable, { timestamp = this.effects.pluck('finishOn').max() || timestamp; break; } - + effect.startOn += timestamp; effect.finishOn += timestamp; if (!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) this.effects.push(effect); - + if (!this.interval) this.interval = setInterval(this.loop.bind(this), 15); }, @@ -214,7 +209,7 @@ Effect.ScopedQueue = Class.create(Enumerable, { }, loop: function() { var timePos = new Date().getTime(); - for(var i=0, len=this.effects.length;i0) { @@ -430,9 +437,9 @@ Effect.Scale = Class.create(Effect.Base, { this.fontSizeType = fontSizeType; } }.bind(this)); - + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; - + this.dims = null; if (this.options.scaleMode=='box') this.dims = [this.element.offsetHeight, this.element.offsetWidth]; @@ -507,17 +514,16 @@ Effect.Highlight = Class.create(Effect.Base, { Effect.ScrollTo = function(element) { var options = arguments[1] || { }, - scrollOffsets = document.viewport.getScrollOffsets(), - elementOffsets = $(element).cumulativeOffset(), - max = (window.height || document.body.scrollHeight) - document.viewport.getHeight(); + scrollOffsets = document.viewport.getScrollOffsets(), + elementOffsets = $(element).cumulativeOffset(); if (options.offset) elementOffsets[1] += options.offset; return new Effect.Tween(null, scrollOffsets.top, - elementOffsets[1] > max ? max : elementOffsets[1], + elementOffsets[1], options, - function(p){ scrollTo(scrollOffsets.left, p.round()) } + function(p){ scrollTo(scrollOffsets.left, p.round()); } ); }; @@ -529,9 +535,9 @@ Effect.Fade = function(element) { var options = Object.extend({ from: element.getOpacity() || 1.0, to: 0.0, - afterFinishInternal: function(effect) { + afterFinishInternal: function(effect) { if (effect.options.to!=0) return; - effect.element.hide().setStyle({opacity: oldOpacity}); + effect.element.hide().setStyle({opacity: oldOpacity}); } }, arguments[1] || { }); return new Effect.Opacity(element,options); @@ -547,15 +553,15 @@ Effect.Appear = function(element) { effect.element.forceRerendering(); }, beforeSetup: function(effect) { - effect.element.setOpacity(effect.options.from).show(); + effect.element.setOpacity(effect.options.from).show(); }}, arguments[1] || { }); return new Effect.Opacity(element,options); }; Effect.Puff = function(element) { element = $(element); - var oldStyle = { - opacity: element.getInlineOpacity(), + var oldStyle = { + opacity: element.getInlineOpacity(), position: element.getStyle('position'), top: element.style.top, left: element.style.left, @@ -563,12 +569,12 @@ Effect.Puff = function(element) { height: element.style.height }; return new Effect.Parallel( - [ new Effect.Scale(element, 200, - { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), - new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], - Object.extend({ duration: 1.0, + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, beforeSetupInternal: function(effect) { - Position.absolutize(effect.effects[0].element) + Position.absolutize(effect.effects[0].element); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().setStyle(oldStyle); } @@ -580,12 +586,12 @@ Effect.BlindUp = function(element) { element = $(element); element.makeClipping(); return new Effect.Scale(element, 0, - Object.extend({ scaleContent: false, - scaleX: false, + Object.extend({ scaleContent: false, + scaleX: false, restoreAfterFinish: true, afterFinishInternal: function(effect) { effect.element.hide().undoClipping(); - } + } }, arguments[1] || { }) ); }; @@ -593,15 +599,15 @@ Effect.BlindUp = function(element) { Effect.BlindDown = function(element) { element = $(element); var elementDimensions = element.getDimensions(); - return new Effect.Scale(element, 100, Object.extend({ - scaleContent: false, + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, scaleX: false, scaleFrom: 0, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, afterSetup: function(effect) { - effect.element.makeClipping().setStyle({height: '0px'}).show(); - }, + effect.element.makeClipping().setStyle({height: '0px'}).show(); + }, afterFinishInternal: function(effect) { effect.element.undoClipping(); } @@ -616,16 +622,16 @@ Effect.SwitchOff = function(element) { from: 0, transition: Effect.Transitions.flicker, afterFinishInternal: function(effect) { - new Effect.Scale(effect.element, 1, { + new Effect.Scale(effect.element, 1, { duration: 0.3, scaleFromCenter: true, scaleX: false, scaleContent: false, restoreAfterFinish: true, - beforeSetup: function(effect) { + beforeSetup: function(effect) { effect.element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity}); } - }) + }); } }, arguments[1] || { })); }; @@ -637,16 +643,16 @@ Effect.DropOut = function(element) { left: element.getStyle('left'), opacity: element.getInlineOpacity() }; return new Effect.Parallel( - [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), new Effect.Opacity(element, { sync: true, to: 0.0 }) ], Object.extend( { duration: 0.5, beforeSetup: function(effect) { - effect.effects[0].element.makePositioned(); + effect.effects[0].element.makePositioned(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle); - } + } }, arguments[1] || { })); }; @@ -674,7 +680,7 @@ Effect.Shake = function(element) { new Effect.Move(effect.element, { x: -distance, y: 0, duration: split, afterFinishInternal: function(effect) { effect.element.undoPositioned().setStyle(oldStyle); - }}) }}) }}) }}) }}) }}); + }}); }}); }}); }}); }}); }}); }; Effect.SlideDown = function(element) { @@ -682,9 +688,9 @@ Effect.SlideDown = function(element) { // SlideDown need to have the content of the element wrapped in a container element with fixed height! var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); - return new Effect.Scale(element, 100, Object.extend({ - scaleContent: false, - scaleX: false, + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, scaleFrom: window.opera ? 0 : 1, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, restoreAfterFinish: true, @@ -692,11 +698,11 @@ Effect.SlideDown = function(element) { effect.element.makePositioned(); effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); - effect.element.makeClipping().setStyle({height: '0px'}).show(); + effect.element.makeClipping().setStyle({height: '0px'}).show(); }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: - (effect.dims[0] - effect.element.clientHeight) + 'px' }); + (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, afterFinishInternal: function(effect) { effect.element.undoClipping().undoPositioned(); @@ -710,8 +716,8 @@ Effect.SlideUp = function(element) { var oldInnerBottom = element.down().getStyle('bottom'); var elementDimensions = element.getDimensions(); return new Effect.Scale(element, window.opera ? 0 : 1, - Object.extend({ scaleContent: false, - scaleX: false, + Object.extend({ scaleContent: false, + scaleX: false, scaleMode: 'box', scaleFrom: 100, scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, @@ -721,7 +727,7 @@ Effect.SlideUp = function(element) { effect.element.down().makePositioned(); if (window.opera) effect.element.setStyle({top: ''}); effect.element.makeClipping().show(); - }, + }, afterUpdateInternal: function(effect) { effect.element.down().setStyle({bottom: (effect.dims[0] - effect.element.clientHeight) + 'px' }); @@ -734,15 +740,15 @@ Effect.SlideUp = function(element) { ); }; -// Bug in opera makes the TD containing this element expand for a instance after finish +// Bug in opera makes the TD containing this element expand for a instance after finish Effect.Squish = function(element) { - return new Effect.Scale(element, window.opera ? 1 : 0, { + return new Effect.Scale(element, window.opera ? 1 : 0, { restoreAfterFinish: true, beforeSetup: function(effect) { - effect.element.makeClipping(); - }, + effect.element.makeClipping(); + }, afterFinishInternal: function(effect) { - effect.element.hide().undoClipping(); + effect.element.hide().undoClipping(); } }); }; @@ -762,13 +768,13 @@ Effect.Grow = function(element) { width: element.style.width, opacity: element.getInlineOpacity() }; - var dims = element.getDimensions(); + var dims = element.getDimensions(); var initialMoveX, initialMoveY; var moveX, moveY; - + switch (options.direction) { case 'top-left': - initialMoveX = initialMoveY = moveX = moveY = 0; + initialMoveX = initialMoveY = moveX = moveY = 0; break; case 'top-right': initialMoveX = dims.width; @@ -793,11 +799,11 @@ Effect.Grow = function(element) { moveY = -dims.height / 2; break; } - + return new Effect.Move(element, { x: initialMoveX, y: initialMoveY, - duration: 0.01, + duration: 0.01, beforeSetup: function(effect) { effect.element.hide().makeClipping().makePositioned(); }, @@ -806,17 +812,17 @@ Effect.Grow = function(element) { [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), new Effect.Scale(effect.element, 100, { - scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) ], Object.extend({ beforeSetup: function(effect) { - effect.effects[0].element.setStyle({height: '0px'}).show(); + effect.effects[0].element.setStyle({height: '0px'}).show(); }, afterFinishInternal: function(effect) { - effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); + effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle); } }, options) - ) + ); } }); }; @@ -838,7 +844,7 @@ Effect.Shrink = function(element) { var dims = element.getDimensions(); var moveX, moveY; - + switch (options.direction) { case 'top-left': moveX = moveY = 0; @@ -855,19 +861,19 @@ Effect.Shrink = function(element) { moveX = dims.width; moveY = dims.height; break; - case 'center': + case 'center': moveX = dims.width / 2; moveY = dims.height / 2; break; } - + return new Effect.Parallel( [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) - ], Object.extend({ + ], Object.extend({ beforeStartInternal: function(effect) { - effect.effects[0].element.makePositioned().makeClipping(); + effect.effects[0].element.makePositioned().makeClipping(); }, afterFinishInternal: function(effect) { effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); } @@ -877,12 +883,14 @@ Effect.Shrink = function(element) { Effect.Pulsate = function(element) { element = $(element); - var options = arguments[1] || { }; - var oldOpacity = element.getInlineOpacity(); - var transition = options.transition || Effect.Transitions.sinoidal; - var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) }; - reverser.bind(transition); - return new Effect.Opacity(element, + var options = arguments[1] || { }, + oldOpacity = element.getInlineOpacity(), + transition = options.transition || Effect.Transitions.linear, + reverser = function(pos){ + return 1 - transition((-Math.cos((pos*(options.pulses||5)*2)*Math.PI)/2) + .5); + }; + + return new Effect.Opacity(element, Object.extend(Object.extend({ duration: 2.0, from: 0, afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } }, options), {transition: reverser})); @@ -896,12 +904,12 @@ Effect.Fold = function(element) { width: element.style.width, height: element.style.height }; element.makeClipping(); - return new Effect.Scale(element, 5, Object.extend({ + return new Effect.Scale(element, 5, Object.extend({ scaleContent: false, scaleX: false, afterFinishInternal: function(effect) { - new Effect.Scale(element, 1, { - scaleContent: false, + new Effect.Scale(element, 1, { + scaleContent: false, scaleY: false, afterFinishInternal: function(effect) { effect.element.hide().undoClipping().setStyle(oldStyle); @@ -916,7 +924,7 @@ Effect.Morph = Class.create(Effect.Base, { var options = Object.extend({ style: { } }, arguments[1] || { }); - + if (!Object.isString(options.style)) this.style = $H(options.style); else { if (options.style.include(':')) @@ -934,18 +942,18 @@ Effect.Morph = Class.create(Effect.Base, { effect.transforms.each(function(transform) { effect.element.style[transform.style] = ''; }); - } + }; } } this.start(options); }, - + setup: function(){ function parseColor(color){ if (!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff'; color = color.parseColor(); return $R(0,2).map(function(i){ - return parseInt( color.slice(i*2+1,i*2+3), 16 ) + return parseInt( color.slice(i*2+1,i*2+3), 16 ); }); } this.transforms = this.style.map(function(pair){ @@ -965,9 +973,9 @@ Effect.Morph = Class.create(Effect.Base, { } var originalValue = this.element.getStyle(property); - return { - style: property.camelize(), - originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), + return { + style: property.camelize(), + originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0), targetValue: unit=='color' ? parseColor(value) : value, unit: unit }; @@ -978,13 +986,13 @@ Effect.Morph = Class.create(Effect.Base, { transform.unit != 'color' && (isNaN(transform.originalValue) || isNaN(transform.targetValue)) ) - ) + ); }); }, update: function(position) { var style = { }, transform, i = this.transforms.length; while(i--) - style[(transform = this.transforms[i]).style] = + style[(transform = this.transforms[i]).style] = transform.unit=='color' ? '#'+ (Math.round(transform.originalValue[0]+ (transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart() + @@ -993,7 +1001,7 @@ Effect.Morph = Class.create(Effect.Base, { (Math.round(transform.originalValue[2]+ (transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart() : (transform.originalValue + - (transform.targetValue - transform.originalValue) * position).toFixed(3) + + (transform.targetValue - transform.originalValue) * position).toFixed(3) + (transform.unit === null ? '' : transform.unit); this.element.setStyle(style, true); } @@ -1030,7 +1038,7 @@ Effect.Transform = Class.create({ }); Element.CSS_PROPERTIES = $w( - 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + + 'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' + 'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' + 'borderRightColor borderRightStyle borderRightWidth borderSpacing ' + 'borderTopColor borderTopStyle borderTopWidth bottom clip color ' + @@ -1039,7 +1047,7 @@ Element.CSS_PROPERTIES = $w( 'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' + 'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' + 'right textIndent top width wordSpacing zIndex'); - + Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/; String.__parseStyleElement = document.createElement('div'); @@ -1051,11 +1059,11 @@ String.prototype.parseStyle = function(){ String.__parseStyleElement.innerHTML = '
    '; style = String.__parseStyleElement.childNodes[0].style; } - + Element.CSS_PROPERTIES.each(function(property){ - if (style[property]) styleRules.set(property, style[property]); + if (style[property]) styleRules.set(property, style[property]); }); - + if (Prototype.Browser.IE && this.include('opacity')) styleRules.set('opacity', this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1]); @@ -1074,14 +1082,14 @@ if (document.defaultView && document.defaultView.getComputedStyle) { Element.getStyles = function(element) { element = $(element); var css = element.currentStyle, styles; - styles = Element.CSS_PROPERTIES.inject({ }, function(hash, property) { - hash.set(property, css[property]); - return hash; + styles = Element.CSS_PROPERTIES.inject({ }, function(results, property) { + results[property] = css[property]; + return results; }); - if (!styles.opacity) styles.set('opacity', element.getOpacity()); + if (!styles.opacity) styles.opacity = element.getOpacity(); return styles; }; -}; +} Effect.Methods = { morph: function(element, style) { @@ -1090,7 +1098,7 @@ Effect.Methods = { return element; }, visualEffect: function(element, effect, options) { - element = $(element) + element = $(element); var s = effect.dasherize().camelize(), klass = s.charAt(0).toUpperCase() + s.substring(1); new Effect[klass](element, options); return element; @@ -1104,17 +1112,17 @@ Effect.Methods = { $w('fade appear grow shrink fold blindUp blindDown slideUp slideDown '+ 'pulsate shake puff squish switchOff dropOut').each( - function(effect) { + function(effect) { Effect.Methods[effect] = function(element, options){ element = $(element); Effect[effect.charAt(0).toUpperCase() + effect.substring(1)](element, options); return element; - } + }; } ); -$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( +$w('getInlineOpacity forceRerendering setContentZoom collectTextNodes collectTextNodesIgnoreClass getStyles').each( function(f) { Effect.Methods[f] = Element[f]; } ); -Element.addMethods(Effect.Methods); +Element.addMethods(Effect.Methods); \ No newline at end of file -- cgit v1.2.3 From 53eba2f21831b8111233d3eae676a88f9f4a9a44 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 19 Nov 2008 12:31:34 +0100 Subject: The docs in environment.rb are not going to be rendered so it doesnt make sense to mark them up --- railties/environments/environment.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 8fef8ff610..2187174bd5 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -22,7 +22,7 @@ Rails::Initializer.run do |config| # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. - # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (_sqlite3_) + # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (_sqlite3_) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" -- cgit v1.2.3 From 0c9f677e7861ef2aae36d91811d72794e4709f58 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 19 Nov 2008 12:36:53 +0100 Subject: Another piece of markup removed from environment.rb --- railties/environments/environment.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 2187174bd5..5cb201401b 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -22,7 +22,7 @@ Rails::Initializer.run do |config| # Specify gems that this application depends on. # They can then be installed with "rake gems:install" on new installations. - # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (_sqlite3_) + # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" -- cgit v1.2.3 From 51a19ae2bf33e66b23ff5c91bf584b2efa9e669f Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 19 Nov 2008 14:12:38 +0100 Subject: Assume that the next version is going to be 2.3 for now --- railties/CHANGELOG | 2 +- railties/Rakefile | 10 +++++----- railties/lib/rails/version.rb | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 2af9946c69..52ddc5c464 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,4 +1,4 @@ -*2.3.0/3.0* +*2.3.0 [Edge]* * Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH] diff --git a/railties/Rakefile b/railties/Rakefile index 888bebc6dc..8c8bec0d27 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -361,11 +361,11 @@ spec = Gem::Specification.new do |s| EOF s.add_dependency('rake', '>= 0.8.3') - s.add_dependency('activesupport', '= 2.2.1' + PKG_BUILD) - s.add_dependency('activerecord', '= 2.2.1' + PKG_BUILD) - s.add_dependency('actionpack', '= 2.2.1' + PKG_BUILD) - s.add_dependency('actionmailer', '= 2.2.1' + PKG_BUILD) - s.add_dependency('activeresource', '= 2.2.1' + PKG_BUILD) + s.add_dependency('activesupport', '= 2.3.0' + PKG_BUILD) + s.add_dependency('activerecord', '= 2.3.0' + PKG_BUILD) + s.add_dependency('actionpack', '= 2.3.0' + PKG_BUILD) + s.add_dependency('actionmailer', '= 2.3.0' + PKG_BUILD) + s.add_dependency('activeresource', '= 2.3.0' + PKG_BUILD) s.rdoc_options << '--exclude' << '.' s.has_rdoc = false diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb index bd835fba26..9bb4b2a96d 100644 --- a/railties/lib/rails/version.rb +++ b/railties/lib/rails/version.rb @@ -1,8 +1,8 @@ module Rails module VERSION #:nodoc: MAJOR = 2 - MINOR = 2 - TINY = 1 + MINOR = 3 + TINY = 0 STRING = [MAJOR, MINOR, TINY].join('.') end -- cgit v1.2.3 From baa8ee5eb1056d07c6623c37a57818317cd5bcc4 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Tue, 4 Nov 2008 19:33:39 +0900 Subject: Require active_support/secure_random for Ruby 1.9. [#1326 state:committed] Signed-off-by: Jeremy Kemper --- .../lib/rails_generator/generators/applications/app/app_generator.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'railties') diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index d68c425871..347ce6352c 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -1,5 +1,6 @@ require 'rbconfig' require 'digest/md5' +require 'active_support/secure_random' class AppGenerator < Rails::Generator::Base DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'], -- cgit v1.2.3 From 549388c244a87562030268689fdfc051c680ec0d Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 19 Nov 2008 12:22:06 -0800 Subject: Reflect default locale change from en-US to en --- railties/test/initializer_test.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'railties') diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 9c045ed66a..e09fd3d34e 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -293,8 +293,8 @@ uses_mocha 'i18n settings' do Rails::Initializer.run(:initialize_i18n, config) assert_equal [ - "./test/../../activesupport/lib/active_support/locale/en-US.yml", - "./test/../../actionpack/lib/action_view/locale/en-US.yml", + File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"), + File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"), "my/test/locale.yml", "my/other/locale.yml" ], I18n.load_path end @@ -306,4 +306,4 @@ uses_mocha 'i18n settings' do assert_equal :de, I18n.default_locale end end -end \ No newline at end of file +end -- cgit v1.2.3 From b7a5ffd08342da133c4fbf0c15a895c1608fbdbb Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Thu, 20 Nov 2008 13:46:56 -0800 Subject: Update changelog to reflect move from Test::Unit::TestCase to ActiveSupport::TestCase --- railties/CHANGELOG | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 52ddc5c464..a93052298b 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper] + * Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH] * BACKWARDS INCOMPATIBLE: Renamed application.rb to application_controller.rb and removed all the special casing that was in place to support the former. You must do this rename in your own application when you upgrade to this version [DHH] -- cgit v1.2.3 From f42c77f927eb49b00e84d355e07de48723d03fcb Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sat, 22 Nov 2008 18:06:08 +0100 Subject: Added ActiveSupport::BacktraceCleaner and Rails::BacktraceCleaner for cutting down on backtrace noise (inspired by the Thoughtbot Quiet Backtrace plugin) [DHH] --- railties/CHANGELOG | 2 ++ railties/Rakefile | 6 ++-- .../configs/initializers/backtrace_silencers.rb | 7 +++++ railties/lib/initializer.rb | 8 +++++ railties/lib/rails/backtrace_cleaner.rb | 34 ++++++++++++++++++++++ .../generators/applications/app/app_generator.rb | 7 +++-- 6 files changed, 59 insertions(+), 5 deletions(-) create mode 100644 railties/configs/initializers/backtrace_silencers.rb create mode 100644 railties/lib/rails/backtrace_cleaner.rb (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index a93052298b..6a644ca63a 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [DHH] + * Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper] * Added config.i18n settings gatherer to config/environment, auto-loading of all locales in config/locales/*.rb,yml, and config/locales/en.yml as a sample locale [DHH] diff --git a/railties/Rakefile b/railties/Rakefile index 8c8bec0d27..cbfa14e887 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -197,8 +197,10 @@ task :copy_configs do cp "configs/routes.rb", "#{PKG_DESTINATION}/config/routes.rb" - cp "configs/initializers/inflections.rb", "#{PKG_DESTINATION}/config/initializers/inflections.rb" - cp "configs/initializers/mime_types.rb", "#{PKG_DESTINATION}/config/initializers/mime_types.rb" + cp "configs/initializers/backtrace_silencers.rb", "#{PKG_DESTINATION}/config/initializers/backtrace_silencers.rb" + cp "configs/initializers/inflections.rb", "#{PKG_DESTINATION}/config/initializers/inflections.rb" + cp "configs/initializers/mime_types.rb", "#{PKG_DESTINATION}/config/initializers/mime_types.rb" + cp "configs/initializers/new_rails_defaults.rb", "#{PKG_DESTINATION}/config/initializers/new_rails_defaults.rb" cp "configs/locales/en.yml", "#{PKG_DESTINATION}/config/locales/en.yml" diff --git a/railties/configs/initializers/backtrace_silencers.rb b/railties/configs/initializers/backtrace_silencers.rb new file mode 100644 index 0000000000..c2169ed01c --- /dev/null +++ b/railties/configs/initializers/backtrace_silencers.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. +# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } + +# You can also remove all the silencers if you're trying do debug a problem that might steem from framework code. +# Rails.backtrace_cleaner.remove_silencers! \ No newline at end of file diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 16abe62d1b..fcf6ea3feb 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -39,6 +39,14 @@ module Rails nil end end + + def backtrace_cleaner + @@backtrace_cleaner ||= begin + # Relies on ActiveSupport, so we have to lazy load to postpone definition until AS has been loaded + require 'rails/backtrace_cleaner' + Rails::BacktraceCleaner.new + end + end def root if defined?(RAILS_ROOT) diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb new file mode 100644 index 0000000000..ffc5ef42aa --- /dev/null +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -0,0 +1,34 @@ +module Rails + class BacktraceCleaner < ActiveSupport::BacktraceCleaner + ERB_METHOD_SIG = /:in `_run_erb_.*/ + + VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails ) + MONGREL_DIRS = %w( lib/mongrel bin/mongrel ) + RAILS_NOISE = %w( script/server ) + RUBY_NOISE = %w( rubygems/custom_require benchmark.rb ) + + ALL_NOISE = VENDOR_DIRS + MONGREL_DIRS + RAILS_NOISE + RUBY_NOISE + + + def initialize + super + add_filter { |line| line.sub(RAILS_ROOT, '') } + add_filter { |line| line.sub(ERB_METHOD_SIG, '') } + add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } } + end + end + + + # For installing the BacktraceCleaner in the test/unit + module BacktraceFilterForTestUnit #:nodoc: + def self.included(klass) + klass.send :alias_method_chain, :filter_backtrace, :cleaning + end + + def filter_backtrace_with_cleaning(backtrace) + backtrace = filter_backtrace_without_cleaning(backtrace) + backtrace = backtrace.first.split("\n") if backtrace.size == 1 + Rails.backtrace_cleaner.clean(backtrace) + end + end +end \ No newline at end of file diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 347ce6352c..e52dcadd4d 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -62,9 +62,10 @@ class AppGenerator < Rails::Generator::Base m.template "configs/routes.rb", "config/routes.rb" # Initializers - m.template "configs/initializers/inflections.rb", "config/initializers/inflections.rb" - m.template "configs/initializers/mime_types.rb", "config/initializers/mime_types.rb" - m.template "configs/initializers/new_rails_defaults.rb", "config/initializers/new_rails_defaults.rb" + m.template "configs/initializers/backtrace_silencers.rb", "config/initializers/backtrace_silencers.rb" + m.template "configs/initializers/inflections.rb", "config/initializers/inflections.rb" + m.template "configs/initializers/mime_types.rb", "config/initializers/mime_types.rb" + m.template "configs/initializers/new_rails_defaults.rb", "config/initializers/new_rails_defaults.rb" # Locale m.template "configs/locales/en.yml", "config/locales/en.yml" -- cgit v1.2.3 From 2144c0f8ff9bdd3dceb085ddb1c4b8711ef329a4 Mon Sep 17 00:00:00 2001 From: Cyril Mougel Date: Sat, 22 Nov 2008 13:32:36 -0600 Subject: Add flush by ensure in script/runner because no flush in production mode [#803 state:resolved] Signed-off-by: Joshua Peek --- railties/lib/commands/runner.rb | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) (limited to 'railties') diff --git a/railties/lib/commands/runner.rb b/railties/lib/commands/runner.rb index 14159c3893..2411c3d270 100644 --- a/railties/lib/commands/runner.rb +++ b/railties/lib/commands/runner.rb @@ -38,11 +38,15 @@ RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) require RAILS_ROOT + '/config/environment' -if code_or_file.nil? - $stderr.puts "Run '#{$0} -h' for help." - exit 1 -elsif File.exist?(code_or_file) - eval(File.read(code_or_file), nil, code_or_file) -else - eval(code_or_file) +begin + if code_or_file.nil? + $stderr.puts "Run '#{$0} -h' for help." + exit 1 + elsif File.exist?(code_or_file) + eval(File.read(code_or_file), nil, code_or_file) + else + eval(code_or_file) + end +ensure + RAILS_DEFAULT_LOGGER.flush if RAILS_DEFAULT_LOGGER end -- cgit v1.2.3 From 0ecf2f6bdb7423516a18f45a65e1301cf8cd9c7d Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 22 Nov 2008 14:00:58 -0600 Subject: Kill dead "new_mongrel" handler --- railties/lib/commands/server.rb | 4 +- railties/lib/commands/servers/new_mongrel.rb | 16 -- railties/lib/rails/mongrel_server/commands.rb | 342 -------------------------- railties/lib/rails/mongrel_server/handler.rb | 55 ----- 4 files changed, 2 insertions(+), 415 deletions(-) delete mode 100644 railties/lib/commands/servers/new_mongrel.rb delete mode 100644 railties/lib/rails/mongrel_server/commands.rb delete mode 100644 railties/lib/rails/mongrel_server/handler.rb (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index 15f417b5be..54628d8bb1 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -20,7 +20,7 @@ rescue Exception end server = case ARGV.first - when "lighttpd", "mongrel", "new_mongrel", "webrick", "thin" + when "lighttpd", "mongrel", "webrick", "thin" ARGV.shift else if defined?(Mongrel) @@ -39,7 +39,7 @@ case server puts "=> Booting WEBrick..." when "lighttpd" puts "=> Booting lighttpd (use 'script/server webrick' to force WEBrick)" - when "mongrel", "new_mongrel" + when "mongrel" puts "=> Booting Mongrel (use 'script/server webrick' to force WEBrick)" when "thin" puts "=> Booting Thin (use 'script/server webrick' to force WEBrick)" diff --git a/railties/lib/commands/servers/new_mongrel.rb b/railties/lib/commands/servers/new_mongrel.rb deleted file mode 100644 index 174dbf8a37..0000000000 --- a/railties/lib/commands/servers/new_mongrel.rb +++ /dev/null @@ -1,16 +0,0 @@ -unless defined?(Mongrel) - abort "PROBLEM: Mongrel is not available on your system (or not in your path)" -end - -require 'rails/mongrel_server/commands' - -GemPlugin::Manager.instance.load "rails::mongrel" => GemPlugin::INCLUDE, "rails" => GemPlugin::EXCLUDE - -case ARGV[0] ||= 'start' -when 'start', 'stop', 'restart' - ARGV[0] = "rails::mongrelserver::#{ARGV[0]}" -end - -if not Mongrel::Command::Registry.instance.run ARGV - exit 1 -end diff --git a/railties/lib/rails/mongrel_server/commands.rb b/railties/lib/rails/mongrel_server/commands.rb deleted file mode 100644 index d29b18712f..0000000000 --- a/railties/lib/rails/mongrel_server/commands.rb +++ /dev/null @@ -1,342 +0,0 @@ -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby. -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -require 'optparse' -require 'yaml' -require 'etc' - -require 'mongrel' -require 'rails/mongrel_server/handler' - -module Rails - module MongrelServer - def self.send_signal(signal, pid_file) - pid = open(pid_file).read.to_i - print "Sending #{signal} to Mongrel at PID #{pid}..." - begin - Process.kill(signal, pid) - rescue Errno::ESRCH - puts "Process does not exist. Not running." - end - - puts "Done." - end - - class RailsConfigurator < Mongrel::Configurator - def setup_mime_types - mime = {} - - if defaults[:mime_map] - Mongrel.log("Loading additional MIME types from #{defaults[:mime_map]}") - mime = load_mime_map(defaults[:mime_map], mime) - end - - mime.each {|k,v| Mongrel::DirHandler::add_mime_type(k,v) } - end - - def mount_rails(prefix) - ENV['RAILS_ENV'] = defaults[:environment] - ::RAILS_ENV.replace(defaults[:environment]) if defined?(::RAILS_ENV) - - env_location = "#{defaults[:cwd]}/config/environment" - require env_location - - ActionController::Base.relative_url_root = defaults[:prefix] - uri prefix, :handler => Rails::MongrelServer::RailsHandler.new - end - end - - class Start < GemPlugin::Plugin "/commands" - include Mongrel::Command::Base - - def configure - options [ - ["-e", "--environment ENV", "Rails environment to run as", :@environment, ENV['RAILS_ENV'] || "development"], - ["-d", "--daemonize", "Run daemonized in the background", :@daemon, false], - ['-p', '--port PORT', "Which port to bind to", :@port, 3000], - ['-a', '--address ADDR', "Address to bind to", :@address, "0.0.0.0"], - ['-l', '--log FILE', "Where to write log messages", :@log_file, "log/mongrel.log"], - ['-P', '--pid FILE', "Where to write the PID", :@pid_file, "tmp/pids/mongrel.pid"], - ['-n', '--num-procs INT', "Number of processors active before clients denied", :@num_procs, 1024], - ['-o', '--timeout TIME', "Time to wait (in seconds) before killing a stalled thread", :@timeout, 60], - ['-t', '--throttle TIME', "Time to pause (in hundredths of a second) between accepting clients", :@throttle, 0], - ['-m', '--mime PATH', "A YAML file that lists additional MIME types", :@mime_map, nil], - ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, RAILS_ROOT], - ['-r', '--root PATH', "Set the document root (default 'public')", :@docroot, "public"], - ['-B', '--debug', "Enable debugging mode", :@debug, false], - ['-C', '--config PATH', "Use a config file", :@config_file, nil], - ['-S', '--script PATH', "Load the given file as an extra config script", :@config_script, nil], - ['-G', '--generate PATH', "Generate a config file for use with -C", :@generate, nil], - ['', '--user USER', "User to run as", :@user, nil], - ['', '--group GROUP', "Group to run as", :@group, nil], - ['', '--prefix PATH', "URL prefix for Rails app", :@prefix, nil], - - ['-b', '--binding ADDR', "Address to bind to (deprecated, use -a)", :@address, "0.0.0.0"], - ['-u', '--debugger', "Enable debugging mode (deprecated, use -B)", :@debug, false] - ] - end - - def validate - if @config_file - valid_exists?(@config_file, "Config file not there: #@config_file") - return false unless @valid - @config_file = File.expand_path(@config_file) - load_config - return false unless @valid - end - - @cwd = File.expand_path(@cwd) - valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd" - - # Change there to start, then we'll have to come back after daemonize - Dir.chdir(@cwd) - - valid?(@prefix[0] == ?/ && @prefix[-1] != ?/, "Prefix must begin with / and not end in /") if @prefix - valid_dir? File.dirname(@log_file), "Path to log file not valid: #@log_file" - valid_dir? File.dirname(@pid_file), "Path to pid file not valid: #@pid_file" - valid_dir? @docroot, "Path to docroot not valid: #@docroot" - valid_exists? @mime_map, "MIME mapping file does not exist: #@mime_map" if @mime_map - valid_exists? @config_file, "Config file not there: #@config_file" if @config_file - valid_dir? File.dirname(@generate), "Problem accessing directory to #@generate" if @generate - valid_user? @user if @user - valid_group? @group if @group - - return @valid - end - - def run - if @generate - @generate = File.expand_path(@generate) - Mongrel.log(:error, "** Writing config to \"#@generate\".") - open(@generate, "w") {|f| f.write(settings.to_yaml) } - Mongrel.log(:error, "** Finished. Run \"mongrel_rails start -C #@generate\" to use the config file.") - exit 0 - end - - config = RailsConfigurator.new(settings) do - defaults[:log] = $stdout if defaults[:environment] == 'development' - - Mongrel.log("=> Rails #{Rails.version} application starting on http://#{defaults[:host]}:#{defaults[:port]}") - - unless defaults[:daemon] - Mongrel.log("=> Call with -d to detach") - Mongrel.log("=> Ctrl-C to shutdown server") - start_debugger if defaults[:debug] - end - - if defaults[:daemon] - if File.exist? defaults[:pid_file] - Mongrel.log(:error, "!!! PID file #{defaults[:pid_file]} already exists. Mongrel could be running already. Check your #{defaults[:log_file]} for errors.") - Mongrel.log(:error, "!!! Exiting with error. You must stop mongrel and clear the .pid before I'll attempt a start.") - exit 1 - end - - daemonize - - Mongrel.log("Daemonized, any open files are closed. Look at #{defaults[:pid_file]} and #{defaults[:log_file]} for info.") - Mongrel.log("Settings loaded from #{@config_file} (they override command line).") if @config_file - end - - Mongrel.log("Starting Mongrel listening at #{defaults[:host]}:#{defaults[:port]}, further information can be found in log/mongrel-#{defaults[:host]}-#{defaults[:port]}.log") - - listener do - prefix = defaults[:prefix] || '/' - - if defaults[:debug] - Mongrel.log("Installing debugging prefixed filters. Look in log/mongrel_debug for the files.") - debug(prefix) - end - - setup_mime_types - dir_handler = Mongrel::DirHandler.new(defaults[:docroot], false) - dir_handler.passthrough_missing_files = true - - unless defaults[:environment] == 'production' - Mongrel.log("Mounting DirHandler at #{prefix}...") - uri prefix, :handler => dir_handler - end - - - Mongrel.log("Starting Rails with #{defaults[:environment]} environment...") - Mongrel.log("Mounting Rails at #{prefix}...") - mount_rails(prefix) - Mongrel.log("Rails loaded.") - - - Mongrel.log("Loading any Rails specific GemPlugins" ) - load_plugins - - if defaults[:config_script] - Mongrel.log("Loading #{defaults[:config_script]} external config script") - run_config(defaults[:config_script]) - end - - setup_signals - end - end - - config.run - Mongrel.log("Mongrel #{Mongrel::Const::MONGREL_VERSION} available at #{@address}:#{@port}") - - if config.defaults[:daemon] - config.write_pid_file - else - Mongrel.log("Use CTRL-C to stop.") - tail "log/#{config.defaults[:environment]}.log" - end - - config.join - - if config.needs_restart - unless RUBY_PLATFORM =~ /djgpp|(cyg|ms|bcc)win|mingw/ - cmd = "ruby #{__FILE__} start #{original_args.join(' ')}" - Mongrel.log("Restarting with arguments: #{cmd}") - config.stop(false, true) - config.remove_pid_file - - if config.defaults[:daemon] - system cmd - else - Mongrel.log(:error, "Can't restart unless in daemon mode.") - exit 1 - end - else - Mongrel.log("Win32 does not support restarts. Exiting.") - end - end - end - - def load_config - settings = {} - begin - settings = YAML.load_file(@config_file) - ensure - Mongrel.log(:error, "** Loading settings from #{@config_file} (they override command line).") unless @daemon || settings[:daemon] - end - - settings[:includes] ||= ["mongrel"] - - # Config file settings will override command line settings - settings.each do |key, value| - key = key.to_s - if config_keys.include?(key) - key = 'address' if key == 'host' - self.instance_variable_set("@#{key}", value) - else - failure "Unknown configuration setting: #{key}" - @valid = false - end - end - end - - def config_keys - @config_keys ||= - %w(address host port cwd log_file pid_file environment docroot mime_map daemon debug includes config_script num_processors timeout throttle user group prefix) - end - - def settings - config_keys.inject({}) do |hash, key| - value = self.instance_variable_get("@#{key}") - key = 'host' if key == 'address' - hash[key.to_sym] ||= value - hash - end - end - - def start_debugger - require_library_or_gem 'ruby-debug' - Debugger.start - Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) - Mongrel.log("=> Debugger enabled") - rescue Exception - Mongrel.log(:error, "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'") - exit - end - - def tail(log_file) - cursor = File.size(log_file) - last_checked = Time.now - tail_thread = Thread.new do - File.open(log_file, 'r') do |f| - loop do - f.seek cursor - if f.mtime > last_checked - last_checked = f.mtime - contents = f.read - cursor += contents.length - print contents - end - sleep 1 - end - end - end - tail_thread - end - end - - class Stop < GemPlugin::Plugin "/commands" - include Mongrel::Command::Base - - def configure - options [ - ['-c', '--chdir PATH', "Change to dir before starting (will be expanded).", :@cwd, "."], - ['-f', '--force', "Force the shutdown (kill -9).", :@force, false], - ['-w', '--wait SECONDS', "Wait SECONDS before forcing shutdown", :@wait, "0"], - ['-P', '--pid FILE', "Where the PID file is located.", :@pid_file, "log/mongrel.pid"] - ] - end - - def validate - @cwd = File.expand_path(@cwd) - valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd" - - Dir.chdir @cwd - - valid_exists? @pid_file, "PID file #@pid_file does not exist. Not running?" - return @valid - end - - def run - if @force - @wait.to_i.times do |waiting| - exit(0) if not File.exist? @pid_file - sleep 1 - end - - Mongrel::send_signal("KILL", @pid_file) if File.exist? @pid_file - else - Mongrel::send_signal("TERM", @pid_file) - end - end - end - - - class Restart < GemPlugin::Plugin "/commands" - include Mongrel::Command::Base - - def configure - options [ - ['-c', '--chdir PATH', "Change to dir before starting (will be expanded)", :@cwd, '.'], - ['-P', '--pid FILE', "Where the PID file is located", :@pid_file, "log/mongrel.pid"] - ] - end - - def validate - @cwd = File.expand_path(@cwd) - valid_dir? @cwd, "Invalid path to change to during daemon mode: #@cwd" - - Dir.chdir @cwd - - valid_exists? @pid_file, "PID file #@pid_file does not exist. Not running?" - return @valid - end - - def run - MongrelServer::send_signal("USR2", @pid_file) - end - end - end -end diff --git a/railties/lib/rails/mongrel_server/handler.rb b/railties/lib/rails/mongrel_server/handler.rb deleted file mode 100644 index a19eca7259..0000000000 --- a/railties/lib/rails/mongrel_server/handler.rb +++ /dev/null @@ -1,55 +0,0 @@ -# Copyright (c) 2005 Zed A. Shaw -# You can redistribute it and/or modify it under the same terms as Ruby. -# -# Additional work donated by contributors. See http://mongrel.rubyforge.org/attributions.html -# for more information. - -require 'mongrel' -require 'cgi' -require 'action_controller/dispatcher' - - -module Rails - module MongrelServer - # Implements a handler that can run Rails and serve files out of the - # Rails application's public directory. This lets you run your Rails - # application with Mongrel during development and testing, then use it - # also in production behind a server that's better at serving the - # static files. - # - # The RailsHandler takes a mime_map parameter which is a simple suffix=mimetype - # mapping that it should add to the list of valid mime types. - # - # It also supports page caching directly and will try to resolve a request - # in the following order: - # - # * If the requested exact PATH_INFO exists as a file then serve it. - # * If it exists at PATH_INFO+".html" exists then serve that. - # * Finally, construct a Mongrel::CGIWrapper and run Dispatcher.dispatch to have Rails go. - # - # This means that if you are using page caching it will actually work with Mongrel - # and you should see a decent speed boost (but not as fast as if you use a static - # server like Apache or Litespeed). - class RailsHandler < Mongrel::HttpHandler - # Construct a Mongrel::CGIWrapper and dispatch. - def process(request, response) - return if response.socket.closed? - - cgi = Mongrel::CGIWrapper.new(request, response) - cgi.handler = self - # We don't want the output to be really final until we're out of the lock - cgi.default_really_final = false - - ActionController::Dispatcher.dispatch(cgi, ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS, response.body) - - # This finalizes the output using the proper HttpResponse way - cgi.out("text/html",true) {""} - rescue Errno::EPIPE - response.socket.close - rescue Object => rails_error - STDERR.puts "#{Time.now.httpdate}: Error dispatching #{rails_error.inspect}" - STDERR.puts rails_error.backtrace.join("\n") - end - end - end -end -- cgit v1.2.3 From 40c6a8b9701f4e137799cecfc72c64aca7b4004b Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 22 Nov 2008 14:10:50 -0600 Subject: Drop lighttpd support from script/server --- railties/lib/commands/server.rb | 6 +- railties/lib/commands/servers/lighttpd.rb | 94 ------------------------------- 2 files changed, 1 insertion(+), 99 deletions(-) delete mode 100644 railties/lib/commands/servers/lighttpd.rb (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index 54628d8bb1..1d33d7afba 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -20,15 +20,13 @@ rescue Exception end server = case ARGV.first - when "lighttpd", "mongrel", "webrick", "thin" + when "mongrel", "webrick", "thin" ARGV.shift else if defined?(Mongrel) "mongrel" elsif defined?(Thin) "thin" - elsif RUBY_PLATFORM !~ /(:?mswin|mingw)/ && !silence_stderr { `lighttpd -version` }.blank? && defined?(FCGI) - "lighttpd" else "webrick" end @@ -37,8 +35,6 @@ end case server when "webrick" puts "=> Booting WEBrick..." - when "lighttpd" - puts "=> Booting lighttpd (use 'script/server webrick' to force WEBrick)" when "mongrel" puts "=> Booting Mongrel (use 'script/server webrick' to force WEBrick)" when "thin" diff --git a/railties/lib/commands/servers/lighttpd.rb b/railties/lib/commands/servers/lighttpd.rb deleted file mode 100644 index c9d13e86f3..0000000000 --- a/railties/lib/commands/servers/lighttpd.rb +++ /dev/null @@ -1,94 +0,0 @@ -require 'rbconfig' -require 'commands/servers/base' - -unless RUBY_PLATFORM !~ /mswin/ && !silence_stderr { `lighttpd -version` }.blank? - puts "PROBLEM: Lighttpd is not available on your system (or not in your path)" - exit 1 -end - -unless defined?(FCGI) - puts "PROBLEM: Lighttpd requires that the FCGI Ruby bindings are installed on the system" - exit 1 -end - -require 'initializer' -configuration = Rails::Initializer.run(:initialize_logger).configuration -default_config_file = config_file = Pathname.new("#{RAILS_ROOT}/config/lighttpd.conf").cleanpath - -require 'optparse' - -detach = false -command_line_port = nil - -ARGV.options do |opt| - opt.on("-p", "--port=port", "Changes the server.port number in the config/lighttpd.conf") { |port| command_line_port = port } - opt.on('-c', "--config=#{config_file}", 'Specify a different lighttpd config file.') { |path| config_file = path } - opt.on('-h', '--help', 'Show this message.') { puts opt; exit 0 } - opt.on('-d', '-d', 'Call with -d to detach') { detach = true; puts "=> Configuration in config/lighttpd.conf" } - opt.parse! -end - -unless File.exist?(config_file) - if config_file != default_config_file - puts "=> #{config_file} not found." - exit 1 - end - - require 'fileutils' - - source = File.expand_path(File.join(File.dirname(__FILE__), - "..", "..", "..", "configs", "lighttpd.conf")) - puts "=> #{config_file} not found, copying from #{source}" - - FileUtils.cp(source, config_file) -end - -# open the config/lighttpd.conf file and add the current user defined port setting to it -if command_line_port - File.open(config_file, 'r+') do |config| - lines = config.readlines - - lines.each do |line| - line.gsub!(/^\s*server.port\s*=\s*(\d+)/, "server.port = #{command_line_port}") - end - - config.rewind - config.print(lines) - config.truncate(config.pos) - end -end - -config = IO.read(config_file) -default_port, default_ip = 3000, '0.0.0.0' -port = config.scan(/^\s*server.port\s*=\s*(\d+)/).first rescue default_port -ip = config.scan(/^\s*server.bind\s*=\s*"([^"]+)"/).first rescue default_ip -puts "=> Rails #{Rails.version} application starting on http://#{ip || default_ip}:#{port || default_port}" - -tail_thread = nil - -if !detach - puts "=> Call with -d to detach" - puts "=> Ctrl-C to shutdown server (see config/lighttpd.conf for options)" - detach = false - tail_thread = tail(configuration.log_path) -end - -trap(:INT) { exit } - -begin - `rake tmp:sockets:clear` # Needed if lighttpd crashes or otherwise leaves FCGI sockets around - `lighttpd #{!detach ? "-D " : ""}-f #{config_file}` -ensure - unless detach - tail_thread.kill if tail_thread - puts 'Exiting' - - # Ensure FCGI processes are reaped - silence_stream(STDOUT) do - ARGV.replace ['-a', 'kill'] - require 'commands/process/reaper' - end - - `rake tmp:sockets:clear` # Remove sockets on clean shutdown - end -end -- cgit v1.2.3 From 4b36f76e7a997fb03a6cccb08b8272ddccde5a3e Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 22 Nov 2008 14:13:23 -0600 Subject: missed lighttpd config --- railties/configs/lighttpd.conf | 54 ------------------------------------------ 1 file changed, 54 deletions(-) delete mode 100644 railties/configs/lighttpd.conf (limited to 'railties') diff --git a/railties/configs/lighttpd.conf b/railties/configs/lighttpd.conf deleted file mode 100644 index ed68d714bb..0000000000 --- a/railties/configs/lighttpd.conf +++ /dev/null @@ -1,54 +0,0 @@ -# Default configuration file for the lighttpd web server -# Start using ./script/server lighttpd - -server.bind = "0.0.0.0" -server.port = 3000 - -server.modules = ( "mod_rewrite", "mod_accesslog", "mod_fastcgi", "mod_compress", "mod_expire" ) - -server.error-handler-404 = "/dispatch.fcgi" -server.pid-file = CWD + "/tmp/pids/lighttpd.pid" -server.document-root = CWD + "/public/" - -server.errorlog = CWD + "/log/lighttpd.error.log" -accesslog.filename = CWD + "/log/lighttpd.access.log" - -url.rewrite = ( "^/$" => "index.html", "^([^.]+)$" => "$1.html" ) - -compress.filetype = ( "text/plain", "text/html", "text/css", "text/javascript" ) -compress.cache-dir = CWD + "/tmp/cache" - -expire.url = ( "/favicon.ico" => "access 3 days", - "/images/" => "access 3 days", - "/stylesheets/" => "access 3 days", - "/javascripts/" => "access 3 days" ) - - -# Change *-procs to 2 if you need to use Upload Progress or other tasks that -# *need* to execute a second request while the first is still pending. -fastcgi.server = ( ".fcgi" => ( "localhost" => ( - "min-procs" => 1, - "max-procs" => 1, - "socket" => CWD + "/tmp/sockets/fcgi.socket", - "bin-path" => CWD + "/public/dispatch.fcgi", - "bin-environment" => ( "RAILS_ENV" => "development" ) -) ) ) - -mimetype.assign = ( - ".css" => "text/css", - ".gif" => "image/gif", - ".htm" => "text/html", - ".html" => "text/html", - ".jpeg" => "image/jpeg", - ".jpg" => "image/jpeg", - ".js" => "text/javascript", - ".png" => "image/png", - ".swf" => "application/x-shockwave-flash", - ".txt" => "text/plain" -) - -# Making sure file uploads above 64k always work when using IE or Safari -# For more information, see http://trac.lighttpd.net/trac/ticket/360 -$HTTP["useragent"] =~ "^(.*MSIE.*)|(.*AppleWebKit.*)$" { - server.max-keep-alive-requests = 0 -} -- cgit v1.2.3 From 708f4c3ae6a41a46ab36a05ea4e126392b81511b Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sat, 22 Nov 2008 14:48:32 -0600 Subject: Switch script/server to use rack processor --- railties/lib/commands/server.rb | 124 +++++++++++++++++++++++-------- railties/lib/commands/servers/base.rb | 31 -------- railties/lib/commands/servers/mongrel.rb | 69 ----------------- railties/lib/commands/servers/thin.rb | 25 ------- railties/lib/commands/servers/webrick.rb | 66 ---------------- 5 files changed, 95 insertions(+), 220 deletions(-) delete mode 100644 railties/lib/commands/servers/base.rb delete mode 100644 railties/lib/commands/servers/mongrel.rb delete mode 100644 railties/lib/commands/servers/thin.rb delete mode 100644 railties/lib/commands/servers/webrick.rb (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index 1d33d7afba..f9a444e208 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -1,45 +1,111 @@ require 'active_support' require 'fileutils' +require 'action_controller/vendor/rack' +require 'optparse' +# TODO: Push Thin adapter upstream so we don't need worry about requiring it begin - require_library_or_gem 'fcgi' + require_library_or_gem 'thin' rescue Exception - # FCGI not available + # Thin not available end -begin - require_library_or_gem 'mongrel' -rescue Exception - # Mongrel not available +options = { + :Port => 3000, + :Host => "0.0.0.0", + :environment => (ENV['RAILS_ENV'] || "development").dup, + :config => RAILS_ROOT + "/config.ru", + :detach => false, + :debugger => false +} + +ARGV.clone.options do |opts| + opts.on("-p", "--port=port", Integer, + "Runs Rails on the specified port.", "Default: 3000") { |v| options[:Port] = v } + opts.on("-b", "--binding=ip", String, + "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| options[:Host] = v } + opts.on("-c", "--config=file", String, + "Use custom rackup configuration file") { |v| options[:config] = v } + opts.on("-d", "--daemon", "Make server run as a Daemon.") { options[:detach] = true } + opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { options[:debugger] = true } + opts.on("-e", "--environment=name", String, + "Specifies the environment to run this server under (test/development/production).", + "Default: development") { |v| options[:environment] = v } + + opts.separator "" + + opts.on("-h", "--help", "Show this help message.") { puts opts; exit } + + opts.parse! end -begin - require_library_or_gem 'thin' -rescue Exception - # Thin not available +server = Rack::Handler.get(ARGV.first) rescue nil +unless server + begin + server = Rack::Handler::Mongrel + rescue LoadError => e + server = Rack::Handler::WEBrick + end end -server = case ARGV.first - when "mongrel", "webrick", "thin" - ARGV.shift - else - if defined?(Mongrel) - "mongrel" - elsif defined?(Thin) - "thin" - else - "webrick" +puts "=> Booting #{ActiveSupport::Inflector.demodulize(server)}" +puts "=> Rails #{Rails.version} application starting on http://#{options[:Host]}:#{options[:Port]}" + +%w(cache pids sessions sockets).each do |dir_to_make| + FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make)) +end + +if options[:detach] + Process.daemon + pid = "#{RAILS_ROOT}/tmp/pids/server.pid" + File.open(pid, 'w'){ |f| f.write(Process.pid) } + at_exit { File.delete(pid) if File.exist?(pid) } +end + +ENV["RAILS_ENV"] = options[:environment] +RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) +require RAILS_ROOT + "/config/environment" + +if File.exist?(options[:config]) + config = options[:config] + if config =~ /\.ru$/ + cfgfile = File.read(config) + if cfgfile[/^#\\(.*)/] + opts.parse!($1.split(/\s+/)) end + app = eval("Rack::Builder.new {( " + cfgfile + "\n )}.to_app", nil, config) + else + require config + app = Object.const_get(File.basename(config, '.rb').capitalize) + end +else + app = Rack::Builder.new { + use Rails::Rack::Logger + use Rails::Rack::Static + run ActionController::Dispatcher.new + }.to_app end -case server - when "webrick" - puts "=> Booting WEBrick..." - when "mongrel" - puts "=> Booting Mongrel (use 'script/server webrick' to force WEBrick)" - when "thin" - puts "=> Booting Thin (use 'script/server webrick' to force WEBrick)" +if options[:debugger] + begin + require_library_or_gem 'ruby-debug' + Debugger.start + Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) + puts "=> Debugger enabled" + rescue Exception + puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'" + exit + end end -%w(cache pids sessions sockets).each { |dir_to_make| FileUtils.mkdir_p(File.join(RAILS_ROOT, 'tmp', dir_to_make)) } -require "commands/servers/#{server}" +puts "=> Call with -d to detach" + +trap(:INT) { exit } + +puts "=> Ctrl-C to shutdown server" + +begin + server.run(app, options.merge(:AccessLog => [])) +ensure + puts 'Exiting' +end diff --git a/railties/lib/commands/servers/base.rb b/railties/lib/commands/servers/base.rb deleted file mode 100644 index 23be169a8d..0000000000 --- a/railties/lib/commands/servers/base.rb +++ /dev/null @@ -1,31 +0,0 @@ -def tail(log_file) - cursor = File.size(log_file) - last_checked = Time.now - tail_thread = Thread.new do - File.open(log_file, 'r') do |f| - loop do - f.seek cursor - if f.mtime > last_checked - last_checked = f.mtime - contents = f.read - cursor += contents.length - print contents - end - sleep 1 - end - end - end - tail_thread -end - -def start_debugger - begin - require_library_or_gem 'ruby-debug' - Debugger.start - Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) - puts "=> Debugger enabled" - rescue Exception - puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'" - exit - end -end \ No newline at end of file diff --git a/railties/lib/commands/servers/mongrel.rb b/railties/lib/commands/servers/mongrel.rb deleted file mode 100644 index 7bb110f63a..0000000000 --- a/railties/lib/commands/servers/mongrel.rb +++ /dev/null @@ -1,69 +0,0 @@ -require 'rbconfig' -require 'commands/servers/base' - -unless defined?(Mongrel) - puts "PROBLEM: Mongrel is not available on your system (or not in your path)" - exit 1 -end - -require 'optparse' - -OPTIONS = { - :port => 3000, - :ip => "0.0.0.0", - :environment => (ENV['RAILS_ENV'] || "development").dup, - :detach => false, - :debugger => false -} - -ARGV.clone.options do |opts| - opts.on("-p", "--port=port", Integer, "Runs Rails on the specified port.", "Default: 3000") { |v| OPTIONS[:port] = v } - opts.on("-b", "--binding=ip", String, "Binds Rails to the specified ip.", "Default: 0.0.0.0") { |v| OPTIONS[:ip] = v } - opts.on("-d", "--daemon", "Make server run as a Daemon.") { OPTIONS[:detach] = true } - opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { OPTIONS[:debugger] = true } - opts.on("-e", "--environment=name", String, - "Specifies the environment to run this server under (test/development/production).", - "Default: development") { |v| OPTIONS[:environment] = v } - - opts.separator "" - - opts.on("-h", "--help", "Show this help message.") { puts opts; exit } - - opts.parse! -end - -puts "=> Rails #{Rails.version} application starting on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" - -parameters = [ - "start", - "-p", OPTIONS[:port].to_s, - "-a", OPTIONS[:ip].to_s, - "-e", OPTIONS[:environment], - "-P", "#{RAILS_ROOT}/tmp/pids/mongrel.pid" -] - -if OPTIONS[:detach] - `mongrel_rails #{parameters.join(" ")} -d` -else - ENV["RAILS_ENV"] = OPTIONS[:environment] - RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV) - - start_debugger if OPTIONS[:debugger] - - puts "=> Call with -d to detach" - puts "=> Ctrl-C to shutdown server" - - log = Pathname.new("#{File.expand_path(RAILS_ROOT)}/log/#{RAILS_ENV}.log").cleanpath - open(log, (File::WRONLY | File::APPEND | File::CREAT)) unless File.exist? log - tail_thread = tail(log) - - trap(:INT) { exit } - - begin - silence_warnings { ARGV = parameters } - load("mongrel_rails") - ensure - tail_thread.kill if tail_thread - puts 'Exiting' - end -end \ No newline at end of file diff --git a/railties/lib/commands/servers/thin.rb b/railties/lib/commands/servers/thin.rb deleted file mode 100644 index 833469cab1..0000000000 --- a/railties/lib/commands/servers/thin.rb +++ /dev/null @@ -1,25 +0,0 @@ -require 'rbconfig' -require 'commands/servers/base' -require 'thin' - - -options = ARGV.clone -options.insert(0,'start') unless Thin::Runner.commands.include?(options[0]) - -thin = Thin::Runner.new(options) - -puts "=> Rails #{Rails.version} application starting on http://#{thin.options[:address]}:#{thin.options[:port]}" -puts "=> Ctrl-C to shutdown server" - -log = Pathname.new("#{File.expand_path(RAILS_ROOT)}/log/#{RAILS_ENV}.log").cleanpath -open(log, (File::WRONLY | File::APPEND | File::CREAT)) unless File.exist? log -tail_thread = tail(log) -trap(:INT) { exit } - -begin - thin.run! -ensure - tail_thread.kill if tail_thread - puts 'Exiting' -end - diff --git a/railties/lib/commands/servers/webrick.rb b/railties/lib/commands/servers/webrick.rb deleted file mode 100644 index 18c8897cc8..0000000000 --- a/railties/lib/commands/servers/webrick.rb +++ /dev/null @@ -1,66 +0,0 @@ -require 'webrick' -require 'optparse' -require 'commands/servers/base' - -OPTIONS = { - :port => 3000, - :ip => "0.0.0.0", - :environment => (ENV['RAILS_ENV'] || "development").dup, - :server_root => File.expand_path(RAILS_ROOT + "/public/"), - :server_type => WEBrick::SimpleServer, - :charset => "UTF-8", - :mime_types => WEBrick::HTTPUtils::DefaultMimeTypes, - :debugger => false - -} - -ARGV.options do |opts| - script_name = File.basename($0) - opts.banner = "Usage: ruby #{script_name} [options]" - - opts.separator "" - - opts.on("-p", "--port=port", Integer, - "Runs Rails on the specified port.", - "Default: 3000") { |v| OPTIONS[:port] = v } - opts.on("-b", "--binding=ip", String, - "Binds Rails to the specified ip.", - "Default: 0.0.0.0") { |v| OPTIONS[:ip] = v } - opts.on("-e", "--environment=name", String, - "Specifies the environment to run this server under (test/development/production).", - "Default: development") { |v| OPTIONS[:environment] = v } - opts.on("-m", "--mime-types=filename", String, - "Specifies an Apache style mime.types configuration file to be used for mime types", - "Default: none") { |mime_types_file| OPTIONS[:mime_types] = WEBrick::HTTPUtils::load_mime_types(mime_types_file) } - - opts.on("-d", "--daemon", - "Make Rails run as a Daemon (only works if fork is available -- meaning on *nix)." - ) { OPTIONS[:server_type] = WEBrick::Daemon } - - opts.on("-u", "--debugger", "Enable ruby-debugging for the server.") { OPTIONS[:debugger] = true } - - opts.on("-c", "--charset=charset", String, - "Set default charset for output.", - "Default: UTF-8") { |v| OPTIONS[:charset] = v } - - opts.separator "" - - opts.on("-h", "--help", - "Show this help message.") { puts opts; exit } - - opts.parse! -end - -start_debugger if OPTIONS[:debugger] - -ENV["RAILS_ENV"] = OPTIONS[:environment] -RAILS_ENV.replace(OPTIONS[:environment]) if defined?(RAILS_ENV) - -require RAILS_ROOT + "/config/environment" -require 'webrick_server' - -OPTIONS['working_directory'] = File.expand_path(RAILS_ROOT) - -puts "=> Rails #{Rails.version} application started on http://#{OPTIONS[:ip]}:#{OPTIONS[:port]}" -puts "=> Ctrl-C to shutdown server; call with --help for options" if OPTIONS[:server_type] == WEBrick::SimpleServer -DispatchServlet.dispatch(OPTIONS) -- cgit v1.2.3 From 9e08a3bb1d47f79b6953056e72eee58e86d83ead Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 23 Nov 2008 13:39:30 +0100 Subject: Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it [#1439 state:committed] (kastner) --- railties/CHANGELOG | 2 ++ railties/lib/tasks/framework.rake | 12 +++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 6a644ca63a..fcbf0c5ce6 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner] + * Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [DHH] * Switch from Test::Unit::TestCase to ActiveSupport::TestCase. [Jeremy Kemper] diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index 5d1f8cf945..4cf174b15b 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -78,7 +78,7 @@ namespace :rails do end desc "Update both configs, scripts and public/javascripts from Rails" - task :update => [ "update:scripts", "update:javascripts", "update:configs" ] + task :update => [ "update:scripts", "update:javascripts", "update:configs", "update:application_controller" ] namespace :update do desc "Add new scripts to the application script/ directory" @@ -114,5 +114,15 @@ namespace :rails do require 'railties_path' FileUtils.cp(RAILTIES_PATH + '/environments/boot.rb', RAILS_ROOT + '/config/boot.rb') end + + desc "Rename application.rb to application_controller.rb" + task :application_controller do + old_style = RAILS_ROOT + '/app/controllers/application.rb' + new_style = RAILS_ROOT + '/app/controllers/application_controller.rb' + if File.exists?(old_style) && !File.exists?(new_style) + FileUtils.mv(old_style, new_style) + puts "#{old_style} has been renamed to #{new_style}, update your SCM as necessary" + end + end end end -- cgit v1.2.3 From c4a0143854e6fecae5e1820f4f054e33547e866f Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Fri, 21 Nov 2008 11:08:39 +0100 Subject: Update the generated controller to not include the deprecated :secret option to protect_from_forgery --- railties/helpers/application_controller.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/helpers/application_controller.rb b/railties/helpers/application_controller.rb index 0a3ed822a4..ef33aa8353 100644 --- a/railties/helpers/application_controller.rb +++ b/railties/helpers/application_controller.rb @@ -5,8 +5,7 @@ class ApplicationController < ActionController::Base helper :all # include all helpers, all the time # See ActionController::RequestForgeryProtection for details - # Uncomment the :secret if you're not using the cookie session store - protect_from_forgery # :secret => '<%= app_secret %>' + protect_from_forgery # See ActionController::Base for details # Uncomment this to filter the contents of submitted sensitive data parameters -- cgit v1.2.3 From d75a2345015046e08f8191748f0e246e1b9f9703 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Sun, 23 Nov 2008 15:15:05 -0600 Subject: simplify console with helpers --- railties/lib/console_with_helpers.rb | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) (limited to 'railties') diff --git a/railties/lib/console_with_helpers.rb b/railties/lib/console_with_helpers.rb index f9e8bf9cbf..039db667c4 100644 --- a/railties/lib/console_with_helpers.rb +++ b/railties/lib/console_with_helpers.rb @@ -1,24 +1,5 @@ -class Module - def include_all_modules_from(parent_module) - parent_module.constants.each do |const| - mod = parent_module.const_get(const) - if mod.class == Module - send(:include, mod) - include_all_modules_from(mod) - end - end - end -end - -def helper(*helper_names) - returning @helper_proxy ||= Object.new do |helper| - helper_names.each { |h| helper.extend "#{h}_helper".classify.constantize } - end -end - -class << helper - include_all_modules_from ActionView +def helper + @helper ||= ApplicationController.helpers end @controller = ApplicationController.new -helper :application rescue nil -- cgit v1.2.3 From e931012287df0bca83cae04d95c2e0835ae08758 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sun, 23 Nov 2008 14:48:36 -0800 Subject: Require Mocha >= 0.9.3 which includes a MiniTest adapter --- railties/test/abstract_unit.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) (limited to 'railties') diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index e1ce32da65..516ab8523e 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -3,18 +3,15 @@ $:.unshift File.dirname(__FILE__) + "/../../actionpack/lib" $:.unshift File.dirname(__FILE__) + "/../lib" $:.unshift File.dirname(__FILE__) + "/../builtin/rails_info" +require 'rubygems' require 'test/unit' +gem 'mocha', '>= 0.9.3' +require 'mocha' require 'stringio' require 'active_support' -# Wrap tests that use Mocha and skip if unavailable. def uses_mocha(test_name) - require 'rubygems' - gem 'mocha', '>= 0.5.5' - require 'mocha' yield -rescue LoadError - $stderr.puts "Skipping #{test_name} tests. `gem install mocha` and try again." end if defined?(RAILS_ROOT) -- cgit v1.2.3 From 8b14686892f278cc73c84bd7c13cabef2ccfeb96 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 24 Nov 2008 11:05:49 +0100 Subject: Updated docs to stop talking exclusively about lighttpd and clarify a few other things --- railties/README | 25 ++++++------------------- 1 file changed, 6 insertions(+), 19 deletions(-) (limited to 'railties') diff --git a/railties/README b/railties/README index 2af0fb1133..37ec8ea211 100644 --- a/railties/README +++ b/railties/README @@ -36,32 +36,19 @@ link:files/vendor/rails/actionpack/README.html. == Web Servers -By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise -Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server, -Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures -that you can always get up and running quickly. +By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails +with a variety of other web servers. Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is suitable for development and deployment of Rails applications. If you have Ruby Gems installed, getting up and running with mongrel is as easy as: gem install mongrel. More info at: http://mongrel.rubyforge.org -If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than -Mongrel and WEBrick and also suited for production use, but requires additional -installation and currently only works well on OS X/Unix (Windows users are encouraged -to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from -http://www.lighttpd.net. +Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or +Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use +FCGI or proxy to a pack of Mongrels/Thin/Ebb servers. -And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby -web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not -for production. - -But of course its also possible to run Rails on any platform that supports FCGI. -Apache, LiteSpeed, IIS are just a few. For more information on FCGI, -please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI - - -== Apache .htaccess example +== Apache .htaccess example for FCGI/CGI # General Apache options AddHandler fastcgi-script .fcgi -- cgit v1.2.3 From eea5dc3a34328267407f2cb861e14d9d1f5d7c02 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 24 Nov 2008 11:09:06 +0100 Subject: Removed the old .htaccess as it is no longer used --- railties/configs/apache.conf | 40 ---------------------------------------- 1 file changed, 40 deletions(-) delete mode 100644 railties/configs/apache.conf (limited to 'railties') diff --git a/railties/configs/apache.conf b/railties/configs/apache.conf deleted file mode 100644 index d9d211c058..0000000000 --- a/railties/configs/apache.conf +++ /dev/null @@ -1,40 +0,0 @@ -# General Apache options -AddHandler fastcgi-script .fcgi -AddHandler cgi-script .cgi -Options +FollowSymLinks +ExecCGI - -# If you don't want Rails to look in certain directories, -# use the following rewrite rules so that Apache won't rewrite certain requests -# -# Example: -# RewriteCond %{REQUEST_URI} ^/notrails.* -# RewriteRule .* - [L] - -# Redirect all requests not available on the filesystem to Rails -# By default the cgi dispatcher is used which is very slow -# -# For better performance replace the dispatcher with the fastcgi one -# -# Example: -# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L] -RewriteEngine On - -# If your Rails application is accessed via an Alias directive, -# then you MUST also set the RewriteBase in this htaccess file. -# -# Example: -# Alias /myrailsapp /path/to/myrailsapp/public -# RewriteBase /myrailsapp - -RewriteRule ^$ index.html [QSA] -RewriteRule ^([^.]+)$ $1.html [QSA] -RewriteCond %{REQUEST_FILENAME} !-f -RewriteRule ^(.*)$ dispatch.cgi [QSA,L] - -# In case Rails experiences terminal errors -# Instead of displaying this message you can supply a file here which will be rendered instead -# -# Example: -# ErrorDocument 500 /500.html - -ErrorDocument 500 "

    Application error

    Rails application failed to start properly" -- cgit v1.2.3 From 1f48c09094610cbf26ec1e93d9bf978b2ae86fa8 Mon Sep 17 00:00:00 2001 From: Manfred Stienstra Date: Mon, 24 Nov 2008 11:25:28 +0100 Subject: Accept a prefix argument to filter_backtrace_with_cleaning [#1456 state:committed] Add a prefix argument to filter_backtrace_with_cleaning so it has the same arity as test/unit's filter_backtrace. Signed-off-by: David Heinemeier Hansson --- railties/lib/rails/backtrace_cleaner.rb | 10 ++++------ railties/test/abstract_unit.rb | 3 ++- railties/test/backtrace_cleaner_test.rb | 28 ++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 7 deletions(-) create mode 100644 railties/test/backtrace_cleaner_test.rb (limited to 'railties') diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index ffc5ef42aa..88df0ebbda 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -1,14 +1,13 @@ module Rails class BacktraceCleaner < ActiveSupport::BacktraceCleaner ERB_METHOD_SIG = /:in `_run_erb_.*/ - + VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails ) MONGREL_DIRS = %w( lib/mongrel bin/mongrel ) RAILS_NOISE = %w( script/server ) RUBY_NOISE = %w( rubygems/custom_require benchmark.rb ) ALL_NOISE = VENDOR_DIRS + MONGREL_DIRS + RAILS_NOISE + RUBY_NOISE - def initialize super @@ -18,15 +17,14 @@ module Rails end end - # For installing the BacktraceCleaner in the test/unit module BacktraceFilterForTestUnit #:nodoc: def self.included(klass) klass.send :alias_method_chain, :filter_backtrace, :cleaning end - - def filter_backtrace_with_cleaning(backtrace) - backtrace = filter_backtrace_without_cleaning(backtrace) + + def filter_backtrace_with_cleaning(backtrace, prefix=nil) + backtrace = filter_backtrace_without_cleaning(backtrace, prefix) backtrace = backtrace.first.split("\n") if backtrace.size == 1 Rails.backtrace_cleaner.clean(backtrace) end diff --git a/railties/test/abstract_unit.rb b/railties/test/abstract_unit.rb index 516ab8523e..b6edc03391 100644 --- a/railties/test/abstract_unit.rb +++ b/railties/test/abstract_unit.rb @@ -9,6 +9,7 @@ gem 'mocha', '>= 0.9.3' require 'mocha' require 'stringio' require 'active_support' +require 'active_support/test_case' def uses_mocha(test_name) yield @@ -18,4 +19,4 @@ if defined?(RAILS_ROOT) RAILS_ROOT.replace File.dirname(__FILE__) else RAILS_ROOT = File.dirname(__FILE__) -end +end \ No newline at end of file diff --git a/railties/test/backtrace_cleaner_test.rb b/railties/test/backtrace_cleaner_test.rb new file mode 100644 index 0000000000..5955fd2856 --- /dev/null +++ b/railties/test/backtrace_cleaner_test.rb @@ -0,0 +1,28 @@ +require 'abstract_unit' + +require 'initializer' +require 'rails/backtrace_cleaner' + +class TestWithBacktrace + include Test::Unit::Util::BacktraceFilter + include Rails::BacktraceFilterForTestUnit +end + +class BacktraceCleanerFilterTest < ActiveSupport::TestCase + def setup + @test = TestWithBacktrace.new + @backtrace = [ './test/rails/benchmark_test.rb', './test/rails/dependencies.rb', '/opt/local/lib/ruby/kernel.rb' ] + end + + test "test with backtrace should use the rails backtrace cleaner to clean" do + Rails.stubs(:backtrace_cleaner).returns(stub(:clean)) + Rails.backtrace_cleaner.expects(:clean).with(@backtrace, nil) + @test.filter_backtrace(@backtrace) + end + + test "filter backtrace should have the same arity as Test::Unit::Util::BacktraceFilter" do + assert_nothing_raised do + @test.filter_backtrace(@backtrace, '/opt/local/lib') + end + end +end \ No newline at end of file -- cgit v1.2.3 From 42b4407e35e8634370fb95dc6786d4fd0c0e6afa Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 24 Nov 2008 15:43:47 +0100 Subject: Strip out the ./ part of the test path so the backtrace align perfectly --- railties/lib/rails/backtrace_cleaner.rb | 1 + 1 file changed, 1 insertion(+) (limited to 'railties') diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index 88df0ebbda..82537d962f 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -13,6 +13,7 @@ module Rails super add_filter { |line| line.sub(RAILS_ROOT, '') } add_filter { |line| line.sub(ERB_METHOD_SIG, '') } + add_filter { |line| line.sub('./', '/') } # for tests add_silencer { |line| ALL_NOISE.any? { |dir| line.include?(dir) } } end end -- cgit v1.2.3 From 5ffd1e0c02e605158efc08f3cbb6aebb79978553 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 24 Nov 2008 09:58:52 -0600 Subject: Ensure integration test is load in script/console [#1452 state:resolved] --- railties/lib/console_app.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/console_app.rb b/railties/lib/console_app.rb index 88e7962b43..96bf3117c8 100644 --- a/railties/lib/console_app.rb +++ b/railties/lib/console_app.rb @@ -1,4 +1,5 @@ -require 'action_controller/integration' +require 'active_support/test_case' +require 'action_controller' # work around the at_exit hook in test/unit, which kills IRB Test::Unit.run = true if Test::Unit.respond_to?(:run=) -- cgit v1.2.3 From 5b5730cc6e9194fb5f67fe79d2c7849e200ba6ed Mon Sep 17 00:00:00 2001 From: Yaroslav Markin Date: Mon, 24 Nov 2008 19:22:04 +0100 Subject: Don't generate public/dispatch.cgi/fcgi/rb files by default. Signed-off-by: Pratik Naik --- railties/CHANGELOG | 2 ++ .../generators/applications/app/app_generator.rb | 14 ++++++++++---- 2 files changed, 12 insertions(+), 4 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index fcbf0c5ce6..bf185d1bda 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* "rails " will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatches" option if you need them. [Yaroslav Markin, Pratik Naik] + * Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner] * Added Rails.backtrace_cleaner as an accessor for the Rails::BacktraceCleaner instance used by the framework to cut down on backtrace noise and config/initializers/backtrace_silencers.rb to add your own (or turn them all off) [DHH] diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index e52dcadd4d..892dba20b0 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -10,7 +10,7 @@ class AppGenerator < Rails::Generator::Base DEFAULT_DATABASE = 'sqlite3' default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE), - :shebang => DEFAULT_SHEBANG, :freeze => false + :shebang => DEFAULT_SHEBANG, :with_dispatches => false, :freeze => false mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.." def initialize(runtime_args, runtime_options = {}) @@ -83,9 +83,11 @@ class AppGenerator < Rails::Generator::Base end # Dispatches - m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options - m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options - m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options + if options[:with_dispatches] + m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options + m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options + m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options + end # HTML files %w(404 422 500 index).each do |file| @@ -129,6 +131,10 @@ class AppGenerator < Rails::Generator::Base "Preconfigure for selected database (options: #{DATABASES.join('/')}).", "Default: #{DEFAULT_DATABASE}") { |v| options[:db] = v } + opt.on("-D", "--with-dispatches", + "Add CGI/FastCGI/mod_ruby dispatches code to generated application skeleton", + "Default: false") { |v| options[:with_dispatches] = v } + opt.on("-f", "--freeze", "Freeze Rails in vendor/rails from the gems generating the skeleton", "Default: false") { |v| options[:freeze] = v } -- cgit v1.2.3 From b7568e77d79cba9202b961cbe2a822b8b6b34bb0 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 24 Nov 2008 19:35:09 +0100 Subject: Fix typo in 5b5730cc6e9194fb5f67fe79d2c7849e200ba6ed --- railties/CHANGELOG | 2 +- .../rails_generator/generators/applications/app/app_generator.rb | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index bf185d1bda..1dba7a009e 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,6 +1,6 @@ *2.3.0 [Edge]* -* "rails " will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatches" option if you need them. [Yaroslav Markin, Pratik Naik] +* "rails " will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik] * Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner] diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 892dba20b0..32383d2bbd 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -10,7 +10,7 @@ class AppGenerator < Rails::Generator::Base DEFAULT_DATABASE = 'sqlite3' default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE), - :shebang => DEFAULT_SHEBANG, :with_dispatches => false, :freeze => false + :shebang => DEFAULT_SHEBANG, :with_dispatchers => false, :freeze => false mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.." def initialize(runtime_args, runtime_options = {}) @@ -83,7 +83,7 @@ class AppGenerator < Rails::Generator::Base end # Dispatches - if options[:with_dispatches] + if options[:with_dispatchers] m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options @@ -131,9 +131,9 @@ class AppGenerator < Rails::Generator::Base "Preconfigure for selected database (options: #{DATABASES.join('/')}).", "Default: #{DEFAULT_DATABASE}") { |v| options[:db] = v } - opt.on("-D", "--with-dispatches", + opt.on("-D", "--with-dispatchers", "Add CGI/FastCGI/mod_ruby dispatches code to generated application skeleton", - "Default: false") { |v| options[:with_dispatches] = v } + "Default: false") { |v| options[:with_dispatchers] = v } opt.on("-f", "--freeze", "Freeze Rails in vendor/rails from the gems generating the skeleton", -- cgit v1.2.3 From 1cbdd53bd383e7d1dc34cad50c22ff5a330bbf91 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Mon, 24 Nov 2008 19:50:09 +0100 Subject: Add a rake task to generate dispatchers : rake rails:generate_dispatchers --- railties/CHANGELOG | 2 ++ railties/lib/tasks/framework.rake | 8 ++++++++ 2 files changed, 10 insertions(+) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 1dba7a009e..a586940f22 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik] + * "rails " will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik] * Added rake rails:update:application_controller to renamed application.rb to application_controller.rb -- included in rake rails:update so upgrading to 2.3 will automatically trigger it #1439 [kastner] diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index 4cf174b15b..df080e94ac 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -124,5 +124,13 @@ namespace :rails do puts "#{old_style} has been renamed to #{new_style}, update your SCM as necessary" end end + + desc "Generate dispatcher files in RAILS_ROOT/public" + task :generate_dispatchers do + require 'railties_path' + FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.fcgi', RAILS_ROOT + '/public/dispatch.fcgi') + FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.rb') + FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.cgi') + end end end -- cgit v1.2.3 From d01f75b1f091c37d14ece70cbe5f52f20f25d64c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 18:10:23 -0800 Subject: Initializer#env relies on StringInquirer autoload. Style fixes. --- railties/lib/initializer.rb | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index fcf6ea3feb..82b7b604ae 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -57,10 +57,7 @@ module Rails end def env - @_env ||= begin - require 'active_support/string_inquirer' - ActiveSupport::StringInquirer.new(RAILS_ENV) - end + @_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV) end def cache @@ -263,7 +260,7 @@ module Rails def require_frameworks configuration.frameworks.each { |framework| require(framework.to_s) } rescue LoadError => e - # re-raise because Mongrel would swallow it + # Re-raise as RuntimeError because Mongrel would swallow LoadError. raise e.to_s end @@ -869,10 +866,10 @@ Run `rake gems:install` to install the missing gems. def framework_paths paths = %w(railties railties/lib activesupport/lib) - paths << 'actionpack/lib' if frameworks.include? :action_controller or frameworks.include? :action_view + paths << 'actionpack/lib' if frameworks.include?(:action_controller) || frameworks.include?(:action_view) [:active_record, :action_mailer, :active_resource, :action_web_service].each do |framework| - paths << "#{framework.to_s.gsub('_', '')}/lib" if frameworks.include? framework + paths << "#{framework.to_s.gsub('_', '')}/lib" if frameworks.include?(framework) end paths.map { |dir| "#{framework_root_path}/#{dir}" }.select { |dir| File.directory?(dir) } -- cgit v1.2.3 From 104f3a57768602289299b3be0fab5b1ed21d7653 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 18:43:04 -0800 Subject: Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. --- railties/CHANGELOG | 2 ++ railties/lib/initializer.rb | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index a586940f22..41aedaeb1e 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper] + * Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik] * "rails " will not generate public/dispatch.cgi/fcgi/rb files by default now. Please use "--with-dispatchers" option if you need them. [Yaroslav Markin, Pratik Naik] diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 82b7b604ae..0f74f9ff88 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -136,6 +136,7 @@ module Rails add_gem_load_paths require_frameworks + preload_frameworks set_autoload_paths add_plugin_load_paths load_environment @@ -264,6 +265,19 @@ module Rails raise e.to_s end + # Preload all frameworks specified by the Configuration#frameworks. + # Used by Passenger to ensure everything's loaded before forking and + # to avoid autoload race conditions in JRuby. + def preload_frameworks + if configuration.preload_frameworks + configuration.frameworks.each do |framework| + # String#classify and #constantize aren't available yet. + toplevel = Object.const_get(framework.to_s.gsub(/(?:^|_)(.)/) { $1.upcase }) + toplevel.load_all! + end + end + end + # Add the load paths used by support functions such as the info controller def add_support_load_paths end @@ -602,6 +616,9 @@ Run `rake gems:install` to install the missing gems. # A stub for setting options on ActiveSupport. attr_accessor :active_support + # Whether to preload all frameworks at startup. + attr_accessor :preload_frameworks + # Whether or not classes should be cached (set to false if you want # application classes to be reloaded on each request) attr_accessor :cache_classes @@ -768,6 +785,7 @@ Run `rake gems:install` to install the missing gems. self.log_level = default_log_level self.view_path = default_view_path self.controller_paths = default_controller_paths + self.preload_frameworks = default_preload_frameworks self.cache_classes = default_cache_classes self.dependency_loading = default_dependency_loading self.whiny_nils = default_whiny_nils @@ -810,6 +828,7 @@ Run `rake gems:install` to install the missing gems. # multiple database connections. Also disables automatic dependency loading # after boot def threadsafe! + self.preload_frameworks = true self.cache_classes = true self.dependency_loading = false self.action_controller.allow_concurrency = true @@ -955,6 +974,10 @@ Run `rake gems:install` to install the missing gems. true end + def default_preload_frameworks + false + end + def default_cache_classes true end -- cgit v1.2.3 From a5870d43e3aac4ae02a650d0112b305c6a3d9114 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 18:47:42 -0800 Subject: Rename Rails::Info.components to frameworks --- railties/builtin/rails_info/rails/info.rb | 16 ++++++++-------- railties/test/rails_info_test.rb | 10 +++++----- 2 files changed, 13 insertions(+), 13 deletions(-) (limited to 'railties') diff --git a/railties/builtin/rails_info/rails/info.rb b/railties/builtin/rails_info/rails/info.rb index 4cbd2cca4a..7b6f09ac69 100644 --- a/railties/builtin/rails_info/rails/info.rb +++ b/railties/builtin/rails_info/rails/info.rb @@ -20,13 +20,13 @@ module Rails rescue Exception end - def components + def frameworks %w( active_record action_pack active_resource action_mailer active_support ) end - def component_version(component) - require "#{component}/version" - "#{component.classify}::VERSION::STRING".constantize + def framework_version(framework) + require "#{framework}/version" + "#{framework.classify}::VERSION::STRING".constantize end def edge_rails_revision(info = git_info) @@ -90,11 +90,11 @@ module Rails Rails::VERSION::STRING end - # Versions of each Rails component (Active Record, Action Pack, + # Versions of each Rails framework (Active Record, Action Pack, # Active Resource, Action Mailer, and Active Support). - components.each do |component| - property "#{component.titlecase} version" do - component_version(component) + frameworks.each do |framework| + property "#{framework.titlecase} version" do + framework_version(framework) end end diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 3e91e2f2ee..9befd44a58 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -61,14 +61,14 @@ EOS assert_property 'Goodbye', 'World' end - def test_component_version + def test_framework_version assert_property 'Active Support version', ActiveSupport::VERSION::STRING end - def test_components_exist - Rails::Info.components.each do |component| - dir = File.dirname(__FILE__) + "/../../" + component.gsub('_', '') - assert File.directory?(dir), "#{component.classify} does not exist" + def test_frameworks_exist + Rails::Info.frameworks.each do |framework| + dir = File.dirname(__FILE__) + "/../../" + framework.gsub('_', '') + assert File.directory?(dir), "#{framework.classify} does not exist" end end -- cgit v1.2.3 From 36dcfcf126b7e7ba33ebe0d7148c9023e7494464 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 18:48:00 -0800 Subject: Really remove components. --- railties/Rakefile | 1 - railties/lib/initializer.rb | 6 +----- railties/lib/tasks/statistics.rake | 1 - 3 files changed, 1 insertion(+), 7 deletions(-) (limited to 'railties') diff --git a/railties/Rakefile b/railties/Rakefile index cbfa14e887..bf70219aa8 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -45,7 +45,6 @@ BASE_DIRS = %w( config/environments config/initializers config/locales - components db doc log diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 0f74f9ff88..038288dc88 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -624,7 +624,7 @@ Run `rake gems:install` to install the missing gems. attr_accessor :cache_classes # The list of paths that should be searched for controllers. (Defaults - # to app/controllers and components.) + # to app/controllers.) attr_accessor :controller_paths # The path to the database configuration file to use. (Defaults to @@ -912,9 +912,6 @@ Run `rake gems:install` to install the missing gems. # Add the app's controller directory paths.concat(Dir["#{root_path}/app/controllers/"]) - # Then components subdirectories. - paths.concat(Dir["#{root_path}/components/[_a-z]*"]) - # Followed by the standard includes. paths.concat %w( app @@ -922,7 +919,6 @@ Run `rake gems:install` to install the missing gems. app/controllers app/helpers app/services - components config lib vendor diff --git a/railties/lib/tasks/statistics.rake b/railties/lib/tasks/statistics.rake index dbd0773194..5ab27a0f62 100644 --- a/railties/lib/tasks/statistics.rake +++ b/railties/lib/tasks/statistics.rake @@ -4,7 +4,6 @@ STATS_DIRECTORIES = [ %w(Models app/models), %w(Libraries lib/), %w(APIs app/apis), - %w(Components components), %w(Integration\ tests test/integration), %w(Functional\ tests test/functional), %w(Unit\ tests test/unit) -- cgit v1.2.3 From d40bc307f9cc5836a3eb22e0cbdb612eaaf2bc04 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 21:47:09 -0800 Subject: Explicitly require action_view to bring in its i18n load path --- railties/test/initializer_test.rb | 3 +++ 1 file changed, 3 insertions(+) (limited to 'railties') diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index e09fd3d34e..82c8abc290 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -291,6 +291,9 @@ uses_mocha 'i18n settings' do config = Rails::Configuration.new config.i18n.load_path << "my/other/locale.yml" + # To bring in AV's i18n load path. + require 'action_view' + Rails::Initializer.run(:initialize_i18n, config) assert_equal [ File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"), -- cgit v1.2.3 From cb4968171020bf3bb8f713cd69fe035ee5a3d608 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 21:47:26 -0800 Subject: Skip fcgi dispatcher tests if fcgi lib isn't available --- railties/test/fcgi_dispatcher_test.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'railties') diff --git a/railties/test/fcgi_dispatcher_test.rb b/railties/test/fcgi_dispatcher_test.rb index 64d054d45c..cc054c24aa 100644 --- a/railties/test/fcgi_dispatcher_test.rb +++ b/railties/test/fcgi_dispatcher_test.rb @@ -1,7 +1,6 @@ require 'abstract_unit' -uses_mocha 'fcgi dispatcher tests' do - +begin require 'fcgi_handler' module ActionController; module Routing; module Routes; end end end @@ -296,4 +295,6 @@ class RailsFCGIHandlerPeriodicGCTest < Test::Unit::TestCase end end -end # uses_mocha +rescue LoadError => e + raise unless e.message =~ /fcgi/ +end -- cgit v1.2.3 From ce50ca1baf29f2edc829011ffc247e68ebd995c3 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Mon, 24 Nov 2008 22:39:11 -0800 Subject: Explicitly require AS::Deprecation for the SecretKeyGenerator. Bring in ActiveSupport::TestCase for its tests. --- railties/lib/rails_generator/secret_key_generator.rb | 2 ++ railties/test/secret_key_generation_test.rb | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/rails_generator/secret_key_generator.rb b/railties/lib/rails_generator/secret_key_generator.rb index 553811d35d..7dd495a2f5 100644 --- a/railties/lib/rails_generator/secret_key_generator.rb +++ b/railties/lib/rails_generator/secret_key_generator.rb @@ -1,3 +1,5 @@ +require 'active_support/deprecation' + module Rails # A class for creating random secret keys. This class will do its best to create a # random secret key that's as secure as possible, using whatever methods are diff --git a/railties/test/secret_key_generation_test.rb b/railties/test/secret_key_generation_test.rb index df486c3bbb..2c7c3d5dfe 100644 --- a/railties/test/secret_key_generation_test.rb +++ b/railties/test/secret_key_generation_test.rb @@ -1,4 +1,4 @@ -require 'test/unit' +require 'abstract_unit' # Must set before requiring generator libs. if defined?(RAILS_ROOT) -- cgit v1.2.3 From e126e1aac07d353e10fe9871fc3fc3f040cc8911 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 25 Nov 2008 13:26:38 -0600 Subject: don't try to require vendored rack in script/server --- railties/lib/commands/server.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index f9a444e208..f61c48567f 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -1,6 +1,7 @@ require 'active_support' +require 'action_controller' + require 'fileutils' -require 'action_controller/vendor/rack' require 'optparse' # TODO: Push Thin adapter upstream so we don't need worry about requiring it -- cgit v1.2.3 From c80fe1093deeb57eee8df11d3c4120158634cb81 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Tue, 25 Nov 2008 14:48:09 -0600 Subject: Move debugger into middleware --- railties/lib/commands/server.rb | 13 +------------ railties/lib/rails/rack.rb | 1 + railties/lib/rails/rack/debugger.rb | 21 +++++++++++++++++++++ 3 files changed, 23 insertions(+), 12 deletions(-) create mode 100644 railties/lib/rails/rack/debugger.rb (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index f61c48567f..a4bb52592f 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -83,22 +83,11 @@ else app = Rack::Builder.new { use Rails::Rack::Logger use Rails::Rack::Static + use Rails::Rack::Debugger if options[:debugger] run ActionController::Dispatcher.new }.to_app end -if options[:debugger] - begin - require_library_or_gem 'ruby-debug' - Debugger.start - Debugger.settings[:autoeval] = true if Debugger.respond_to?(:settings) - puts "=> Debugger enabled" - rescue Exception - puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'" - exit - end -end - puts "=> Call with -d to detach" trap(:INT) { exit } diff --git a/railties/lib/rails/rack.rb b/railties/lib/rails/rack.rb index b4f32c2d95..90535674e9 100644 --- a/railties/lib/rails/rack.rb +++ b/railties/lib/rails/rack.rb @@ -1,5 +1,6 @@ module Rails module Rack + autoload :Debugger, "rails/rack/debugger" autoload :Logger, "rails/rack/logger" autoload :Static, "rails/rack/static" end diff --git a/railties/lib/rails/rack/debugger.rb b/railties/lib/rails/rack/debugger.rb new file mode 100644 index 0000000000..aa2711c616 --- /dev/null +++ b/railties/lib/rails/rack/debugger.rb @@ -0,0 +1,21 @@ +module Rails + module Rack + class Debugger + def initialize(app) + @app = app + + require_library_or_gem 'ruby-debug' + ::Debugger.start + ::Debugger.settings[:autoeval] = true if ::Debugger.respond_to?(:settings) + puts "=> Debugger enabled" + rescue Exception + puts "You need to install ruby-debug to run the server in debugging mode. With gems, use 'gem install ruby-debug'" + exit + end + + def call(env) + @app.call(env) + end + end + end +end -- cgit v1.2.3 From 63d8f56774dcb1ea601928c3eb6c119d359fae10 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 26 Nov 2008 14:41:20 +0100 Subject: Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH] --- railties/CHANGELOG | 2 ++ railties/lib/rails/plugin.rb | 25 ++++++++++++++++++++++--- railties/lib/rails/plugin/loader.rb | 10 +++++++--- railties/test/initializer_test.rb | 8 ++++---- railties/test/plugin_loader_test.rb | 25 +++++++++++++++++++------ 5 files changed, 54 insertions(+), 16 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 41aedaeb1e..6cd57e295b 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH] + * Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper] * Add a rake task to generate dispatchers : rake rails:generate_dispatchers [Pratik] diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 4d983843af..3b9e7dec2d 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -28,13 +28,17 @@ module Rails end def valid? - File.directory?(directory) && (has_lib_directory? || has_init_file?) + File.directory?(directory) && (has_app_directory? || has_lib_directory? || has_init_file?) end # Returns a list of paths this plugin wishes to make available in $LOAD_PATH. def load_paths report_nonexistant_or_empty_plugin! unless valid? - has_lib_directory? ? [lib_path] : [] + + returning [] do |load_paths| + load_paths << lib_path if has_lib_directory? + load_paths << app_paths if has_app_directory? + end.flatten end # Evaluates a plugin's init.rb file. @@ -68,7 +72,16 @@ module Rails def report_nonexistant_or_empty_plugin! raise LoadError, "Can not find the plugin named: #{name}" - end + end + + + def app_paths + [ + File.join(directory, 'app', 'models'), + File.join(directory, 'app', 'controllers'), + File.join(directory, 'app', 'helpers') + ] + end def lib_path File.join(directory, 'lib') @@ -86,6 +99,11 @@ module Rails File.file?(gem_init_path) ? gem_init_path : classic_init_path end + + def has_app_directory? + File.directory?(File.join(directory, 'app')) + end + def has_lib_directory? File.directory?(lib_path) end @@ -94,6 +112,7 @@ module Rails File.file?(init_path) end + def evaluate_init_rb(initializer) if has_init_file? silence_warnings do diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb index 948d497007..8d7eac53c5 100644 --- a/railties/lib/rails/plugin/loader.rb +++ b/railties/lib/rails/plugin/loader.rb @@ -33,6 +33,7 @@ module Rails plugin.load(initializer) register_plugin_as_loaded(plugin) end + ensure_all_registered_plugins_are_loaded! end @@ -45,12 +46,15 @@ module Rails plugins.each do |plugin| plugin.load_paths.each do |path| $LOAD_PATH.insert(application_lib_index + 1, path) - ActiveSupport::Dependencies.load_paths << path + + ActiveSupport::Dependencies.load_paths << path + unless Rails.configuration.reload_plugins? ActiveSupport::Dependencies.load_once_paths << path end end end + $LOAD_PATH.uniq! end @@ -59,9 +63,9 @@ module Rails # The locate_plugins method uses each class in config.plugin_locators to # find the set of all plugins available to this Rails application. def locate_plugins - configuration.plugin_locators.map { |locator| + configuration.plugin_locators.map do |locator| locator.new(initializer).plugins - }.flatten + end.flatten # TODO: sorting based on config.plugins end diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 82c8abc290..88c267b58e 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -209,7 +209,7 @@ uses_mocha "Initializer plugin loading tests" do def test_all_plugins_are_loaded_when_registered_plugin_list_is_untouched failure_tip = "It's likely someone has added a new plugin fixture without updating this list" load_plugins! - assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_when_all_is_used @@ -217,7 +217,7 @@ uses_mocha "Initializer plugin loading tests" do only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @initializer.loaded_plugins, failure_tip end def test_all_plugins_loaded_after_all @@ -225,7 +225,7 @@ uses_mocha "Initializer plugin loading tests" do only_load_the_following_plugins! plugin_names load_plugins! failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - assert_plugins [:stubby, :a, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip + assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @initializer.loaded_plugins, failure_tip end def test_plugin_names_may_be_strings @@ -299,7 +299,7 @@ uses_mocha 'i18n settings' do File.expand_path("./test/../../activesupport/lib/active_support/locale/en.yml"), File.expand_path("./test/../../actionpack/lib/action_view/locale/en.yml"), "my/test/locale.yml", - "my/other/locale.yml" ], I18n.load_path + "my/other/locale.yml" ], I18n.load_path.collect { |path| path =~ /^\./ ? File.expand_path(path) : path } end def test_setting_another_default_locale diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb index f429bae15c..0d3aec5fd6 100644 --- a/railties/test/plugin_loader_test.rb +++ b/railties/test/plugin_loader_test.rb @@ -48,16 +48,16 @@ uses_mocha "Plugin Loader Tests" do end def test_should_find_all_availble_plugins_and_return_as_all_plugins - assert_plugins [:stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip + assert_plugins [ :engine, :stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip end def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched - assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil @configuration.plugins = nil - assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end def test_should_return_specific_plugins_named_in_config_plugins_array_if_set @@ -74,17 +74,17 @@ uses_mocha "Plugin Loader Tests" do def test_should_load_all_plugins_in_natural_order_when_all_is_used only_load_the_following_plugins! [:all] - assert_plugins [:a, :acts_as_chunky_bacon, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip end def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip end def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] - assert_plugins [:stubby, :a, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip + assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip end def test_should_accept_plugin_names_given_as_strings @@ -112,6 +112,19 @@ uses_mocha "Plugin Loader Tests" do assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end + + def test_should_add_engine_load_paths_to_Dependencies_load_paths + only_load_the_following_plugins! [:engine] + + @loader.add_plugin_load_paths + + %w( models controllers helpers ).each do |app_part| + assert ActiveSupport::Dependencies.load_paths.include?( + File.join(plugin_fixture_path('engines/engine'), 'app', app_part) + ), "Couldn't find #{app_part} in load path" + end + end + def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] -- cgit v1.2.3 From 4999d52e08a02ebba344f6c318f0af4b5b18f0e5 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 26 Nov 2008 20:03:25 +0100 Subject: Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH] --- railties/CHANGELOG | 2 ++ railties/lib/initializer.rb | 9 +++++++-- railties/lib/rails/plugin.rb | 23 ++++++++++++++++++++-- railties/lib/rails/plugin/loader.rb | 17 +++++++++++++++- .../engine/app/controllers/engine_controller.rb | 2 ++ .../engines/engine/app/models/engine_model.rb | 2 ++ .../plugins/engines/engine/config/routes.rb | 3 +++ .../test/fixtures/plugins/engines/engine/init.rb | 3 +++ railties/test/initializer_test.rb | 1 + railties/test/plugin_locator_test.rb | 2 +- 10 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb create mode 100644 railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb create mode 100644 railties/test/fixtures/plugins/engines/engine/config/routes.rb create mode 100644 railties/test/fixtures/plugins/engines/engine/init.rb (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 6cd57e295b..5324a7c73b 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH] + * Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH] * Add config.preload_frameworks to load all frameworks at startup. Default to false so Rails autoloads itself as it's used. Turn this on for Passenger and JRuby. Also turned on by config.threadsafe! [Jeremy Kemper] diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 038288dc88..b0abf3379c 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -486,8 +486,13 @@ Run `rake gems:install` to install the missing gems. # loading module used to lazily load controllers (Configuration#controller_paths). def initialize_routing return unless configuration.frameworks.include?(:action_controller) - ActionController::Routing.controller_paths = configuration.controller_paths - ActionController::Routing::Routes.configuration_file = configuration.routes_configuration_file + + ActionController::Routing.controller_paths = configuration.controller_paths + plugin_loader.controller_paths + + ([ configuration.routes_configuration_file ] + plugin_loader.routing_files).each do |routing_file| + ActionController::Routing::Routes.add_configuration_file(routing_file) + end + ActionController::Routing::Routes.reload end diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 3b9e7dec2d..2b1e877e2b 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -40,7 +40,7 @@ module Rails load_paths << app_paths if has_app_directory? end.flatten end - + # Evaluates a plugin's init.rb file. def load(initializer) return if loaded? @@ -60,7 +60,26 @@ module Rails def about @about ||= load_about_information end + + # Engines are plugins with an app/ directory. + def engine? + has_app_directory? + end + # Returns true if the engine ships with a routing file + def routed? + File.exist?(routing_file) + end + + def controller_path + File.join(directory, 'app', 'controllers') + end + + def routing_file + File.join(directory, 'config', 'routes.rb') + end + + private def load_about_information about_yml_path = File.join(@directory, "about.yml") @@ -82,7 +101,7 @@ module Rails File.join(directory, 'app', 'helpers') ] end - + def lib_path File.join(directory, 'lib') end diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb index 8d7eac53c5..ba3f67d1d0 100644 --- a/railties/lib/rails/plugin/loader.rb +++ b/railties/lib/rails/plugin/loader.rb @@ -22,6 +22,11 @@ module Rails @plugins ||= all_plugins.select { |plugin| should_load?(plugin) }.sort { |p1, p2| order_plugins(p1, p2) } end + # Returns the plugins that are in engine-form (have an app/ directory) + def engines + @engines ||= plugins.select(&:engine?) + end + # Returns all the plugins that could be found by the current locators. def all_plugins @all_plugins ||= locate_plugins @@ -56,7 +61,17 @@ module Rails end $LOAD_PATH.uniq! - end + end + + # Returns an array of all the controller paths found inside engine-type plugins. + def controller_paths + engines.collect(&:controller_path) + end + + def routing_files + engines.select(&:routed?).collect(&:routing_file) + end + protected diff --git a/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb new file mode 100644 index 0000000000..f08373de40 --- /dev/null +++ b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb @@ -0,0 +1,2 @@ +class EngineController < ActionController::Base +end \ No newline at end of file diff --git a/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb b/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb new file mode 100644 index 0000000000..e265712185 --- /dev/null +++ b/railties/test/fixtures/plugins/engines/engine/app/models/engine_model.rb @@ -0,0 +1,2 @@ +class EngineModel +end \ No newline at end of file diff --git a/railties/test/fixtures/plugins/engines/engine/config/routes.rb b/railties/test/fixtures/plugins/engines/engine/config/routes.rb new file mode 100644 index 0000000000..cca8d1b146 --- /dev/null +++ b/railties/test/fixtures/plugins/engines/engine/config/routes.rb @@ -0,0 +1,3 @@ +ActionController::Routing::Routes.draw do |map| + map.connect '/engine', :controller => "engine" +end diff --git a/railties/test/fixtures/plugins/engines/engine/init.rb b/railties/test/fixtures/plugins/engines/engine/init.rb new file mode 100644 index 0000000000..f4b00c0fa4 --- /dev/null +++ b/railties/test/fixtures/plugins/engines/engine/init.rb @@ -0,0 +1,3 @@ +# My app/models dir must be in the load path. +require 'engine_model' +raise 'missing model from my app/models dir' unless defined?(EngineModel) diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 88c267b58e..2104412c54 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -252,6 +252,7 @@ uses_mocha "Initializer plugin loading tests" do assert $LOAD_PATH.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) end + private def load_plugins! diff --git a/railties/test/plugin_locator_test.rb b/railties/test/plugin_locator_test.rb index 363fa27f15..5a8c651e5a 100644 --- a/railties/test/plugin_locator_test.rb +++ b/railties/test/plugin_locator_test.rb @@ -47,7 +47,7 @@ uses_mocha "Plugin Locator Tests" do end def test_should_return_all_plugins_found_under_the_set_plugin_paths - assert_equal ["a", "acts_as_chunky_bacon", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort + assert_equal ["a", "acts_as_chunky_bacon", "engine", "gemlike", "plugin_with_no_lib_dir", "stubby"].sort, @locator.plugins.map(&:name).sort end def test_should_find_plugins_only_under_the_plugin_paths_set_in_configuration -- cgit v1.2.3 From 3cc9d1c5ad1639283b43ee2b6099cb4f3b19bf23 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Wed, 26 Nov 2008 20:30:21 +0100 Subject: Let all plugins not just engines have a config/routes.rb file --- railties/lib/rails/plugin/loader.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb index ba3f67d1d0..f08d9b74e2 100644 --- a/railties/lib/rails/plugin/loader.rb +++ b/railties/lib/rails/plugin/loader.rb @@ -68,8 +68,9 @@ module Rails engines.collect(&:controller_path) end + # Returns an array of routing.rb files from all the plugins that include config/routes.rb def routing_files - engines.select(&:routed?).collect(&:routing_file) + plugins.select(&:routed?).collect(&:routing_file) end -- cgit v1.2.3 From 4d910b033379727e5e7355590c50c72fc75e56db Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Wed, 26 Nov 2008 20:54:47 -0600 Subject: Super lazy load view paths in development mode (no indexing or caching at all). Switch layout finders to use view path api to take advantage of cache. --- railties/lib/initializer.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index b0abf3379c..f282cff2de 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -372,9 +372,10 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) - ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes - ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) - ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + if configuration.cache_classes + ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + end end end -- cgit v1.2.3 From f2ee056873b84f8917e72d87181e1a9f5f653342 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 27 Nov 2008 18:59:24 +0100 Subject: Added view path support for engines [DHH] --- railties/CHANGELOG | 2 + railties/lib/initializer.rb | 8 +- railties/lib/rails/plugin.rb | 11 +- railties/lib/rails/plugin/loader.rb | 34 ++- .../engine/app/controllers/engine_controller.rb | 2 +- railties/test/plugin_loader_test.rb | 228 +++++++++++---------- 6 files changed, 152 insertions(+), 133 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 5324a7c73b..250822db7e 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Added view path support for engines [DHH] + * Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH] * Added app/[models|controllers|helpers] to the load path for plugins that has an app directory (go engines ;)) [DHH] diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index b0abf3379c..0c06d1bf21 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -487,12 +487,8 @@ Run `rake gems:install` to install the missing gems. def initialize_routing return unless configuration.frameworks.include?(:action_controller) - ActionController::Routing.controller_paths = configuration.controller_paths + plugin_loader.controller_paths - - ([ configuration.routes_configuration_file ] + plugin_loader.routing_files).each do |routing_file| - ActionController::Routing::Routes.add_configuration_file(routing_file) - end - + ActionController::Routing.controller_paths += configuration.controller_paths + ActionController::Routing::Routes.add_configuration_file(configuration.routes_configuration_file) ActionController::Routing::Routes.reload end diff --git a/railties/lib/rails/plugin.rb b/railties/lib/rails/plugin.rb index 2b1e877e2b..4901abe808 100644 --- a/railties/lib/rails/plugin.rb +++ b/railties/lib/rails/plugin.rb @@ -71,6 +71,11 @@ module Rails File.exist?(routing_file) end + + def view_path + File.join(directory, 'app', 'views') + end + def controller_path File.join(directory, 'app', 'controllers') end @@ -95,11 +100,7 @@ module Rails def app_paths - [ - File.join(directory, 'app', 'models'), - File.join(directory, 'app', 'controllers'), - File.join(directory, 'app', 'helpers') - ] + [ File.join(directory, 'app', 'models'), File.join(directory, 'app', 'helpers'), controller_path ] end def lib_path diff --git a/railties/lib/rails/plugin/loader.rb b/railties/lib/rails/plugin/loader.rb index f08d9b74e2..be81bdf4fa 100644 --- a/railties/lib/rails/plugin/loader.rb +++ b/railties/lib/rails/plugin/loader.rb @@ -39,6 +39,8 @@ module Rails register_plugin_as_loaded(plugin) end + configure_engines + ensure_all_registered_plugins_are_loaded! end @@ -63,19 +65,31 @@ module Rails $LOAD_PATH.uniq! end - # Returns an array of all the controller paths found inside engine-type plugins. - def controller_paths - engines.collect(&:controller_path) - end - - # Returns an array of routing.rb files from all the plugins that include config/routes.rb - def routing_files - plugins.select(&:routed?).collect(&:routing_file) - end - protected + def configure_engines + if engines.any? + add_engine_routing_configurations + add_engine_controller_paths + add_engine_view_paths + end + end + def add_engine_routing_configurations + engines.select(&:routed?).collect(&:routing_file).each do |routing_file| + ActionController::Routing::Routes.add_configuration_file(routing_file) + end + end + + def add_engine_controller_paths + ActionController::Routing.controller_paths += engines.collect(&:controller_path) + end + + def add_engine_view_paths + # reverse it such that the last engine can overwrite view paths from the first, like with routes + ActionController::Base.view_paths += ActionView::PathSet.new(engines.collect(&:view_path).reverse) + end + # The locate_plugins method uses each class in config.plugin_locators to # find the set of all plugins available to this Rails application. def locate_plugins diff --git a/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb index f08373de40..323ee1c4dc 100644 --- a/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb +++ b/railties/test/fixtures/plugins/engines/engine/app/controllers/engine_controller.rb @@ -1,2 +1,2 @@ -class EngineController < ActionController::Base +class EngineController end \ No newline at end of file diff --git a/railties/test/plugin_loader_test.rb b/railties/test/plugin_loader_test.rb index 0d3aec5fd6..23b81ddbf6 100644 --- a/railties/test/plugin_loader_test.rb +++ b/railties/test/plugin_loader_test.rb @@ -1,5 +1,8 @@ require 'plugin_test_helper' +$:.unshift File.dirname(__FILE__) + "/../../actionpack/lib" +require 'action_controller' + # Mocks out the configuration module Rails def self.configuration @@ -7,149 +10,152 @@ module Rails end end -uses_mocha "Plugin Loader Tests" do - - class TestPluginLoader < Test::Unit::TestCase - ORIGINAL_LOAD_PATH = $LOAD_PATH.dup - - def setup - reset_load_path! +class TestPluginLoader < Test::Unit::TestCase + ORIGINAL_LOAD_PATH = $LOAD_PATH.dup - @configuration = Rails::Configuration.new - @configuration.plugin_paths << plugin_fixture_root_path - @initializer = Rails::Initializer.new(@configuration) - @valid_plugin_path = plugin_fixture_path('default/stubby') - @empty_plugin_path = plugin_fixture_path('default/empty') + def setup + reset_load_path! - @failure_tip = "It's likely someone has added a new plugin fixture without updating this list" + @configuration = Rails::Configuration.new + @configuration.plugin_paths << plugin_fixture_root_path + @initializer = Rails::Initializer.new(@configuration) + @valid_plugin_path = plugin_fixture_path('default/stubby') + @empty_plugin_path = plugin_fixture_path('default/empty') - @loader = Rails::Plugin::Loader.new(@initializer) - end + @failure_tip = "It's likely someone has added a new plugin fixture without updating this list" - def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_for_its_plugins_result - locator_1 = stub(:plugins => [:a, :b, :c]) - locator_2 = stub(:plugins => [:d, :e, :f]) - locator_class_1 = stub(:new => locator_1) - locator_class_2 = stub(:new => locator_2) - @configuration.plugin_locators = [locator_class_1, locator_class_2] - assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins) - end + @loader = Rails::Plugin::Loader.new(@initializer) + end - def test_should_memoize_the_result_of_locate_plugins_as_all_plugins - plugin_list = [:a, :b, :c] - @loader.expects(:locate_plugins).once.returns(plugin_list) - assert_equal plugin_list, @loader.all_plugins - assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again - end + def test_should_locate_plugins_by_asking_each_locator_specifed_in_configuration_for_its_plugins_result + locator_1 = stub(:plugins => [:a, :b, :c]) + locator_2 = stub(:plugins => [:d, :e, :f]) + locator_class_1 = stub(:new => locator_1) + locator_class_2 = stub(:new => locator_2) + @configuration.plugin_locators = [locator_class_1, locator_class_2] + assert_equal [:a, :b, :c, :d, :e, :f], @loader.send(:locate_plugins) + end - def test_should_return_empty_array_if_configuration_plugins_is_empty - @configuration.plugins = [] - assert_equal [], @loader.plugins - end + def test_should_memoize_the_result_of_locate_plugins_as_all_plugins + plugin_list = [:a, :b, :c] + @loader.expects(:locate_plugins).once.returns(plugin_list) + assert_equal plugin_list, @loader.all_plugins + assert_equal plugin_list, @loader.all_plugins # ensuring that locate_plugins isn't called again + end - def test_should_find_all_availble_plugins_and_return_as_all_plugins - assert_plugins [ :engine, :stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip - end + def test_should_return_empty_array_if_configuration_plugins_is_empty + @configuration.plugins = [] + assert_equal [], @loader.plugins + end - def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched - assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip - end + def test_should_find_all_availble_plugins_and_return_as_all_plugins + assert_plugins [ :engine, :stubby, :plugin_with_no_lib_dir, :gemlike, :acts_as_chunky_bacon, :a], @loader.all_plugins.reverse, @failure_tip + end - def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil - @configuration.plugins = nil - assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip - end + def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_untouched + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + end - def test_should_return_specific_plugins_named_in_config_plugins_array_if_set - plugin_names = [:acts_as_chunky_bacon, :stubby] - only_load_the_following_plugins! plugin_names - assert_plugins plugin_names, @loader.plugins - end + def test_should_return_all_plugins_as_plugins_when_registered_plugin_list_is_nil + @configuration.plugins = nil + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + end - def test_should_respect_the_order_of_plugins_given_in_configuration - plugin_names = [:stubby, :acts_as_chunky_bacon] - only_load_the_following_plugins! plugin_names - assert_plugins plugin_names, @loader.plugins - end + def test_should_return_specific_plugins_named_in_config_plugins_array_if_set + plugin_names = [:acts_as_chunky_bacon, :stubby] + only_load_the_following_plugins! plugin_names + assert_plugins plugin_names, @loader.plugins + end - def test_should_load_all_plugins_in_natural_order_when_all_is_used - only_load_the_following_plugins! [:all] - assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip - end + def test_should_respect_the_order_of_plugins_given_in_configuration + plugin_names = [:stubby, :acts_as_chunky_bacon] + only_load_the_following_plugins! plugin_names + assert_plugins plugin_names, @loader.plugins + end - def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip - end + def test_should_load_all_plugins_in_natural_order_when_all_is_used + only_load_the_following_plugins! [:all] + assert_plugins [:a, :acts_as_chunky_bacon, :engine, :gemlike, :plugin_with_no_lib_dir, :stubby], @loader.plugins, @failure_tip + end - def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all - only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] - assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip - end + def test_should_load_specified_plugins_in_order_and_then_all_remaining_plugins_when_all_is_used + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon, :all] + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :engine, :gemlike, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + end - def test_should_accept_plugin_names_given_as_strings - only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] - assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip - end + def test_should_be_able_to_specify_loading_of_plugins_loaded_after_all + only_load_the_following_plugins! [:stubby, :all, :acts_as_chunky_bacon] + assert_plugins [:stubby, :a, :engine, :gemlike, :plugin_with_no_lib_dir, :acts_as_chunky_bacon], @loader.plugins, @failure_tip + end - def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] - stubbed_application_lib_index_in_LOAD_PATHS = 4 - @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS) + def test_should_accept_plugin_names_given_as_strings + only_load_the_following_plugins! ['stubby', 'acts_as_chunky_bacon', :a, :plugin_with_no_lib_dir] + assert_plugins [:stubby, :acts_as_chunky_bacon, :a, :plugin_with_no_lib_dir], @loader.plugins, @failure_tip + end - @loader.add_plugin_load_paths + def test_should_add_plugin_load_paths_to_global_LOAD_PATH_array + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + stubbed_application_lib_index_in_LOAD_PATHS = 4 + @loader.stubs(:application_lib_index).returns(stubbed_application_lib_index_in_LOAD_PATHS) - assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS - end + @loader.add_plugin_load_paths - def test_should_add_plugin_load_paths_to_Dependencies_load_paths - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/stubby'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS + assert $LOAD_PATH.index(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) >= stubbed_application_lib_index_in_LOAD_PATHS + end - @loader.add_plugin_load_paths + def test_should_add_plugin_load_paths_to_Dependencies_load_paths + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] - assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) - end + @loader.add_plugin_load_paths + assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) + assert ActiveSupport::Dependencies.load_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) + end - def test_should_add_engine_load_paths_to_Dependencies_load_paths - only_load_the_following_plugins! [:engine] + def test_should_add_engine_load_paths_to_Dependencies_load_paths + only_load_the_following_plugins! [:engine] - @loader.add_plugin_load_paths + @loader.add_plugin_load_paths - %w( models controllers helpers ).each do |app_part| - assert ActiveSupport::Dependencies.load_paths.include?( - File.join(plugin_fixture_path('engines/engine'), 'app', app_part) - ), "Couldn't find #{app_part} in load path" - end + %w( models controllers helpers ).each do |app_part| + assert ActiveSupport::Dependencies.load_paths.include?( + File.join(plugin_fixture_path('engines/engine'), 'app', app_part) + ), "Couldn't find #{app_part} in load path" end + end + + def test_engine_controllers_should_have_their_view_path_set_when_loaded + only_load_the_following_plugins!([ :engine ]) - def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths - only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] - - @loader.add_plugin_load_paths + @loader.send :add_engine_view_paths + + assert_equal [ File.join(plugin_fixture_path('engines/engine'), 'app', 'views') ], ActionController::Base.view_paths + end - assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) - assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) - end + def test_should_add_plugin_load_paths_to_Dependencies_load_once_paths + only_load_the_following_plugins! [:stubby, :acts_as_chunky_bacon] - def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array - plugin_load_paths = ["a", "b"] - plugin = stub(:load_paths => plugin_load_paths) - @loader.stubs(:plugins).returns([plugin]) + @loader.add_plugin_load_paths - @loader.add_plugin_load_paths + assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/stubby'), 'lib')) + assert ActiveSupport::Dependencies.load_once_paths.include?(File.join(plugin_fixture_path('default/acts/acts_as_chunky_bacon'), 'lib')) + end - plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) } - end + def test_should_add_all_load_paths_from_a_plugin_to_LOAD_PATH_array + plugin_load_paths = ["a", "b"] + plugin = stub(:load_paths => plugin_load_paths) + @loader.stubs(:plugins).returns([plugin]) - private + @loader.add_plugin_load_paths - def reset_load_path! - $LOAD_PATH.clear - ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } - end + plugin_load_paths.each { |path| assert $LOAD_PATH.include?(path) } end -end + + private + def reset_load_path! + $LOAD_PATH.clear + ORIGINAL_LOAD_PATH.each { |path| $LOAD_PATH << path } + end +end \ No newline at end of file -- cgit v1.2.3 From 5fa0457542b0ff541d0a80ff8c3561eec8e35959 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 27 Nov 2008 21:04:24 +0100 Subject: Revert "Super lazy load view paths in development mode (no indexing or caching at all). Switch layout finders to use view path api to take advantage of cache." as it killed dev mode reloading. This reverts commit 4d910b033379727e5e7355590c50c72fc75e56db. --- railties/lib/initializer.rb | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index a69898e2c5..0c06d1bf21 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -372,10 +372,9 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) - if configuration.cache_classes - ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) - ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) - end + ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes + ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) end end -- cgit v1.2.3 From 9fc23745f1511d8d97433828d9ca87970994d138 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Fri, 28 Nov 2008 11:18:28 -0600 Subject: Reinstate "Super lazy load view paths in development mode (no indexing or caching at all). Switch layout finders to use view path api to take advantage of cache." as it killed dev mode reloading." --- railties/lib/initializer.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 0c06d1bf21..a69898e2c5 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -372,9 +372,10 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) - ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes - ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) - ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + if configuration.cache_classes + ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) + end end end -- cgit v1.2.3 From 34905673a3018edeff71aafeceb64e487304d31d Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Thu, 27 Nov 2008 21:04:24 +0100 Subject: Revert "Super lazy load view paths in development mode (no indexing or caching at all). Switch layout finders to use view path api to take advantage of cache." as it killed dev mode reloading. This reverts commit 4d910b033379727e5e7355590c50c72fc75e56db. --- railties/lib/initializer.rb | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index a69898e2c5..0c06d1bf21 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -372,10 +372,9 @@ Run `rake gems:install` to install the missing gems. def load_view_paths if configuration.frameworks.include?(:action_view) - if configuration.cache_classes - ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) - ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) - end + ActionView::PathSet::Path.eager_load_templates! if configuration.cache_classes + ActionController::Base.view_paths.load if configuration.frameworks.include?(:action_controller) + ActionMailer::Base.template_root.load if configuration.frameworks.include?(:action_mailer) end end -- cgit v1.2.3 From 1e8f9634f65e1076deba3e20cca3d032ec12e026 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sat, 29 Nov 2008 10:45:52 +0100 Subject: Include Rack in the server noise --- railties/lib/rails/backtrace_cleaner.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/lib/rails/backtrace_cleaner.rb b/railties/lib/rails/backtrace_cleaner.rb index 82537d962f..d8626aaf14 100644 --- a/railties/lib/rails/backtrace_cleaner.rb +++ b/railties/lib/rails/backtrace_cleaner.rb @@ -3,11 +3,11 @@ module Rails ERB_METHOD_SIG = /:in `_run_erb_.*/ VENDOR_DIRS = %w( vendor/plugins vendor/gems vendor/rails ) - MONGREL_DIRS = %w( lib/mongrel bin/mongrel ) + SERVER_DIRS = %w( lib/mongrel bin/mongrel lib/rack ) RAILS_NOISE = %w( script/server ) RUBY_NOISE = %w( rubygems/custom_require benchmark.rb ) - ALL_NOISE = VENDOR_DIRS + MONGREL_DIRS + RAILS_NOISE + RUBY_NOISE + ALL_NOISE = VENDOR_DIRS + SERVER_DIRS + RAILS_NOISE + RUBY_NOISE def initialize super -- cgit v1.2.3 From fdfcdf467387c4db3d79c1f46eadbb55a88ef814 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sat, 29 Nov 2008 10:57:36 +0100 Subject: Enhanced Rails.root to take parameters that'll be join with the root, like Rails.root('app', 'controllers') => File.join(Rails.root, 'app', 'controllers') [#1482 state:committed] (Damian Janowski) --- railties/CHANGELOG | 2 ++ railties/lib/initializer.rb | 8 ++------ railties/test/initializer_test.rb | 10 ++++++++++ 3 files changed, 14 insertions(+), 6 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 250822db7e..ad8ba43c17 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Enhanced Rails.root to take parameters that'll be join with the root, like Rails.root('app', 'controllers') => File.join(Rails.root, 'app', 'controllers') #1482 [Damian Janowski] + * Added view path support for engines [DHH] * Added that config/routes.rb files in engine plugins are automatically loaded (and reloaded when they change in dev mode) [DHH] diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 0c06d1bf21..5baaf81403 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -48,12 +48,8 @@ module Rails end end - def root - if defined?(RAILS_ROOT) - RAILS_ROOT - else - nil - end + def root(*args) + File.join(RAILS_ROOT, *args.compact) if defined?(RAILS_ROOT) end def env diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 2104412c54..33c81bc5ad 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -311,3 +311,13 @@ uses_mocha 'i18n settings' do end end end + +class RailsRootTest < Test::Unit::TestCase + def test_rails_dot_root_equals_rails_root + assert_equal RAILS_ROOT, Rails.root + end + + def test_rails_dot_root_accepts_arguments_for_file_dot_join + assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root('app', 'controllers') + end +end \ No newline at end of file -- cgit v1.2.3 From cfb2126726f34baedfab971785ad7ff19a7f54ce Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Sat, 29 Nov 2008 20:06:49 -0800 Subject: Load app initializers by path relative to Rails.root --- railties/lib/initializer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index 8e8bcf21fe..b645ac3da2 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -564,7 +564,7 @@ Run `rake gems:install` to install the missing gems. def load_application_initializers if gems_dependencies_loaded Dir["#{configuration.root_path}/config/initializers/**/*.rb"].sort.each do |initializer| - load(initializer) + load initializer.sub(/^#{Regexp.escape(configuration.root_path)}\//, '') end end end -- cgit v1.2.3 From 5c26b2e47bba39055c138c36eaf5e43ee7fe0ffb Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 14:44:56 -0600 Subject: Its no longer common to run Rails in environments where you cant set the environment to be the production one. Dont need a notice telling about the ENV var that prominently any more --- railties/environments/environment.rb | 4 ---- 1 file changed, 4 deletions(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 5cb201401b..1d27df2372 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -1,9 +1,5 @@ # Be sure to restart your server when you modify this file -# Uncomment below to force Rails into production mode when -# you don't control web/app server and can't set it the proper way -# ENV['RAILS_ENV'] ||= 'production' - # Specifies gem version of Rails to use when vendor/rails is not present <%= '# ' if freeze %>RAILS_GEM_VERSION = '<%= Rails::VERSION::STRING %>' unless defined? RAILS_GEM_VERSION -- cgit v1.2.3 From 0eac9daa0a333ede2252203a67f86638f0e811c8 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 14:46:11 -0600 Subject: Rails::Configuration never had more details. Stop lying about it --- railties/environments/environment.rb | 1 - 1 file changed, 1 deletion(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 1d27df2372..49c6a5c888 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -10,7 +10,6 @@ Rails::Initializer.run do |config| # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. - # See Rails::Configuration for more options. # Skip frameworks you're not going to use. To use Rails without a database # you must remove the Active Record framework. -- cgit v1.2.3 From 201b64b4e1fd007c8da1374da4196f24e2661f21 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 14:53:22 -0600 Subject: Cleanup other examples and wording --- railties/environments/environment.rb | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 49c6a5c888..b1a0604abf 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -11,20 +11,17 @@ Rails::Initializer.run do |config| # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. - # Skip frameworks you're not going to use. To use Rails without a database + # Skip frameworks you're not going to use. To use Rails without a database, # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] - # Specify gems that this application depends on. - # They can then be installed with "rake gems:install" on new installations. - # You have to specify the :lib option for libraries, where the Gem name (sqlite3-ruby) differs from the file itself (sqlite3) + # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" # config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net" # config.gem "sqlite3-ruby", :lib => "sqlite3" # config.gem "aws-s3", :lib => "aws/s3" - # Only load the plugins named here, in the order given. By default, all plugins - # in vendor/plugins are loaded in alphabetical order. + # Only load the plugins named here, in the order given (default is alphabetical). # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] @@ -40,9 +37,9 @@ Rails::Initializer.run do |config| # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. config.time_zone = 'UTC' - # The internationalization framework can be changed to have another default locale (standard is :en) or more load paths. + # The internationalization framework can be changed to have another default locale (default is :en) or more load paths. # All files from config/locales/*.rb,yml are added automatically. - # config.i18n.load_path << Dir[File.join(RAILS_ROOT, 'my', 'locales', '*.{rb,yml}')] + # config.i18n.load_path << Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de # Your secret key for verifying cookie session data integrity. @@ -65,6 +62,5 @@ Rails::Initializer.run do |config| # config.active_record.schema_format = :sql # Activate observers that should always be running - # Please note that observers generated using script/generate observer need to have an _observer suffix # config.active_record.observers = :cacher, :garbage_collector, :forum_observer end -- cgit v1.2.3 From 471f0240189fcdd2067621d51427dc09565fdc6a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 14:58:42 -0600 Subject: Me loves me some whitespace --- railties/lib/initializer.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index b645ac3da2..ef0c335478 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -513,10 +513,15 @@ Run `rake gems:install` to install the missing gems. def initialize_time_zone if configuration.time_zone zone_default = Time.__send__(:get_zone, configuration.time_zone) + unless zone_default - raise %{Value assigned to config.time_zone not recognized. Run "rake -D time" for a list of tasks for finding appropriate time zone names.} + raise \ + 'Value assigned to config.time_zone not recognized.' + + 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.' end + Time.zone_default = zone_default + if configuration.frameworks.include?(:active_record) ActiveRecord::Base.time_zone_aware_attributes = true ActiveRecord::Base.default_timezone = :utc -- cgit v1.2.3 From 6358e6c1078cfdbdee627a4fbde1e2b0c597af35 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:06:55 -0600 Subject: More organization based on priority --- railties/environments/environment.rb | 14 +++++--------- railties/environments/production.rb | 17 ++++++++++------- 2 files changed, 15 insertions(+), 16 deletions(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index b1a0604abf..66f71e5d9b 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -11,9 +11,8 @@ Rails::Initializer.run do |config| # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. - # Skip frameworks you're not going to use. To use Rails without a database, - # you must remove the Active Record framework. - # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] + # Add additional load paths for your own custom dirs + # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" @@ -25,12 +24,9 @@ Rails::Initializer.run do |config| # :all can be used as a placeholder for all plugins not explicitly named # config.plugins = [ :exception_notification, :ssl_requirement, :all ] - # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{RAILS_ROOT}/extras ) - - # Force all environments to use the same logger level - # (by default production uses :info, the others :debug) - # config.log_level = :debug + # Skip frameworks you're not going to use. To use Rails without a database, + # you must remove the Active Record framework. + # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] # Make Time.zone default to the specified zone, and make Active Record store time values # in the database in UTC, and return them converted to the specified local zone. diff --git a/railties/environments/production.rb b/railties/environments/production.rb index ec5b7bc865..1fc9f6b923 100644 --- a/railties/environments/production.rb +++ b/railties/environments/production.rb @@ -4,21 +4,24 @@ # Code is not reloaded between requests config.cache_classes = true -# Enable threaded mode -# config.threadsafe! - -# Use a different logger for distributed setups -# config.logger = SyslogLogger.new - # Full error reports are disabled and caching is turned on config.action_controller.consider_all_requests_local = false config.action_controller.perform_caching = true +# See everything in the log (default is :info) +# config.log_level = :debug + +# Use a different logger for distributed setups +# config.logger = SyslogLogger.new + # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and javascripts from an asset server -# config.action_controller.asset_host = "http://assets.example.com" +# config.action_controller.asset_host = "http://assets.example.com" # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false + +# Enable threaded mode +# config.threadsafe! \ No newline at end of file -- cgit v1.2.3 From 73213f4ca7e0db8d617abfdbbc79e6d31ccb5cc7 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:18:46 -0600 Subject: Say it briefly --- railties/helpers/application_controller.rb | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'railties') diff --git a/railties/helpers/application_controller.rb b/railties/helpers/application_controller.rb index ef33aa8353..6635a3f487 100644 --- a/railties/helpers/application_controller.rb +++ b/railties/helpers/application_controller.rb @@ -3,12 +3,8 @@ class ApplicationController < ActionController::Base helper :all # include all helpers, all the time + protect_from_forgery # See ActionController::RequestForgeryProtection for details - # See ActionController::RequestForgeryProtection for details - protect_from_forgery - - # See ActionController::Base for details - # Uncomment this to filter the contents of submitted sensitive data parameters - # from your application log (in this case, all fields with names like "password"). + # Scrub sensitive parameters from your log # filter_parameter_logging :password end -- cgit v1.2.3 From c5f461d7b0b8f5ee0021c78a80525c0594864c68 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:52:50 -0600 Subject: Cleanup the app generator --- .../generators/applications/app/app_generator.rb | 338 ++++++++++++--------- 1 file changed, 196 insertions(+), 142 deletions(-) (limited to 'railties') diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 32383d2bbd..5435b2aeb3 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -3,115 +3,37 @@ require 'digest/md5' require 'active_support/secure_random' class AppGenerator < Rails::Generator::Base - DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'], - Config::CONFIG['ruby_install_name']) + DEFAULT_SHEBANG = File.join(Config::CONFIG['bindir'], Config::CONFIG['ruby_install_name']) - DATABASES = %w(mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db) + DATABASES = %w( mysql oracle postgresql sqlite2 sqlite3 frontbase ibm_db ) DEFAULT_DATABASE = 'sqlite3' + mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.." default_options :db => (ENV["RAILS_DEFAULT_DATABASE"] || DEFAULT_DATABASE), :shebang => DEFAULT_SHEBANG, :with_dispatchers => false, :freeze => false - mandatory_options :source => "#{File.dirname(__FILE__)}/../../../../.." + def initialize(runtime_args, runtime_options = {}) super + usage if args.empty? usage("Databases supported for preconfiguration are: #{DATABASES.join(", ")}") if (options[:db] && !DATABASES.include?(options[:db])) + @destination_root = args.shift @app_name = File.basename(File.expand_path(@destination_root)) end def manifest - # Use /usr/bin/env if no special shebang was specified - script_options = { :chmod => 0755, :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] } - dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] } - - # duplicate CGI::Session#generate_unique_id - md5 = Digest::MD5.new - now = Time.now - md5 << now.to_s - md5 << String(now.usec) - md5 << String(rand(0)) - md5 << String($$) - md5 << @app_name - - # Do our best to generate a secure secret key for CookieStore - secret = ActiveSupport::SecureRandom.hex(64) - record do |m| - # Root directory and all subdirectories. - m.directory '' - BASEDIRS.each { |path| m.directory path } - - # Root - m.file "fresh_rakefile", "Rakefile" - m.file "README", "README" - - # Application - m.template "helpers/application_controller.rb", "app/controllers/application_controller.rb", :assigns => { - :app_name => @app_name, :app_secret => md5.hexdigest } - m.template "helpers/application_helper.rb", "app/helpers/application_helper.rb" - m.template "helpers/test_helper.rb", "test/test_helper.rb" - m.template "helpers/performance_test.rb", "test/performance/browsing_test.rb" - - # database.yml and routes.rb - m.template "configs/databases/#{options[:db]}.yml", "config/database.yml", :assigns => { - :app_name => @app_name, - :socket => options[:db] == "mysql" ? mysql_socket_location : nil - } - m.template "configs/routes.rb", "config/routes.rb" - - # Initializers - m.template "configs/initializers/backtrace_silencers.rb", "config/initializers/backtrace_silencers.rb" - m.template "configs/initializers/inflections.rb", "config/initializers/inflections.rb" - m.template "configs/initializers/mime_types.rb", "config/initializers/mime_types.rb" - m.template "configs/initializers/new_rails_defaults.rb", "config/initializers/new_rails_defaults.rb" - - # Locale - m.template "configs/locales/en.yml", "config/locales/en.yml" - - # Environments - m.file "environments/boot.rb", "config/boot.rb" - m.template "environments/environment.rb", "config/environment.rb", :assigns => { :freeze => options[:freeze], :app_name => @app_name, :app_secret => secret } - m.file "environments/production.rb", "config/environments/production.rb" - m.file "environments/development.rb", "config/environments/development.rb" - m.file "environments/test.rb", "config/environments/test.rb" - - # Scripts - %w( about console dbconsole destroy generate performance/benchmarker performance/profiler performance/request process/reaper process/spawner process/inspector runner server plugin ).each do |file| - m.file "bin/#{file}", "script/#{file}", script_options - end - - # Dispatches - if options[:with_dispatchers] - m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options - m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options - m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options - end - - # HTML files - %w(404 422 500 index).each do |file| - m.template "html/#{file}.html", "public/#{file}.html" - end - - m.template "html/favicon.ico", "public/favicon.ico" - m.template "html/robots.txt", "public/robots.txt" - m.file "html/images/rails.png", "public/images/rails.png" - - # Javascripts - m.file "html/javascripts/prototype.js", "public/javascripts/prototype.js" - m.file "html/javascripts/effects.js", "public/javascripts/effects.js" - m.file "html/javascripts/dragdrop.js", "public/javascripts/dragdrop.js" - m.file "html/javascripts/controls.js", "public/javascripts/controls.js" - m.file "html/javascripts/application.js", "public/javascripts/application.js" - - # Docs - m.file "doc/README_FOR_APP", "doc/README_FOR_APP" - - # Logs - %w(server production development test).each { |file| - m.file "configs/empty.log", "log/#{file}.log", :chmod => 0666 - } + create_directories(m) + create_root_files(m) + create_app_files(m) + create_config_files(m) + create_script_files(m) + create_test_files(m) + create_public_files(m) + create_documentation_file(m) + create_log_files(m) end end @@ -140,53 +62,185 @@ class AppGenerator < Rails::Generator::Base "Default: false") { |v| options[:freeze] = v } end + + private + def create_directories(m) + m.directory '' + + # Intermediate directories are automatically created so don't sweat their absence here. + %w( + app/controllers + app/helpers + app/models + app/views/layouts + config/environments + config/initializers + config/locales + db + doc + lib + lib/tasks + log + public/images + public/javascripts + public/stylesheets + script/performance + script/process + test/fixtures + test/functional + test/integration + test/performance + test/unit + vendor + vendor/plugins + tmp/sessions + tmp/sockets + tmp/cache + tmp/pids + ).each { |path| m.directory(path) } + end + + def create_root_files(m) + m.file "fresh_rakefile", "Rakefile" + m.file "README", "README" + end + + def create_app_files(m) + m.file "helpers/application_controller.rb", "app/controllers/application_controller.rb" + m.file "helpers/application_helper.rb", "app/helpers/application_helper.rb" + end + + def create_config_files(m) + create_database_configuration_file(m) + create_routes_file(m) + create_locale_file(m) + create_initializer_files(m) + create_environment_files(m) + end + + def create_documentation_file(m) + m.file "doc/README_FOR_APP", "doc/README_FOR_APP" + end + + def create_log_files(m) + %w( server production development test ).each do |file| + m.file "configs/empty.log", "log/#{file}.log", :chmod => 0666 + end + end + + def create_public_files(m) + create_dispatch_files(m) + create_error_files(m) + create_welcome_file(m) + create_browser_convention_files(m) + create_rails_image(m) + create_javascript_files(m) + end + + def create_script_files(m) + %w( + about console dbconsole destroy generate performance/benchmarker performance/profiler + performance/request process/reaper process/spawner process/inspector runner server plugin + ).each do |file| + m.file "bin/#{file}", "script/#{file}", { + :chmod => 0755, + :shebang => options[:shebang] == DEFAULT_SHEBANG ? nil : options[:shebang] + } + end + end + + def create_test_files(m) + m.file "helpers/test_helper.rb", "test/test_helper.rb" + m.file "helpers/performance_test.rb", "test/performance/browsing_test.rb" + end + + + def create_database_configuration_file(m) + m.template "configs/databases/#{options[:db]}.yml", "config/database.yml", :assigns => { + :app_name => @app_name, + :socket => options[:db] == "mysql" ? mysql_socket_location : nil } + end + + def create_routes_file(m) + m.file "configs/routes.rb", "config/routes.rb" + end + + def create_initializer_files(m) + %w( + backtrace_silencers + inflections + mime_types + new_rails_defaults + ).each do |initializer| + m.file "configs/initializers/#{initializer}.rb", "config/initializers/#{initializer}.rb" + end + + m.template "configs/initializers/session_store.rb", "config/initializers/session_store.rb", + :assigns => { :app_name => @app_name, :app_secret => ActiveSupport::SecureRandom.hex(64) } + end + + def create_locale_file(m) + m.file "configs/locales/en.yml", "config/locales/en.yml" + end + + def create_environment_files(m) + m.template "environments/environment.rb", "config/environment.rb", + :assigns => { :freeze => options[:freeze] } + + m.file "environments/boot.rb", "config/boot.rb" + m.file "environments/production.rb", "config/environments/production.rb" + m.file "environments/development.rb", "config/environments/development.rb" + m.file "environments/test.rb", "config/environments/test.rb" + end + + + def create_dispatch_files(m) + if options[:with_dispatchers] + dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] } + + m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options + m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options + m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options + end + end + + def create_error_files(m) + %w( 404 422 500 ).each do |file| + m.file "html/#{file}.html", "public/#{file}.html" + end + end + + def create_welcome_file(m) + m.file 'html/index.html', 'public/index.html' + end + + def create_browser_convention_files(m) + m.file "html/favicon.ico", "public/favicon.ico" + m.file "html/robots.txt", "public/robots.txt" + end + + def create_rails_image(m) + m.file "html/images/rails.png", "public/images/rails.png" + end + + def create_javascript_files(m) + %w( prototype effects dragdrop controls application ).each do |javascript| + m.file "html/javascripts/#{javascript}.js", "public/javascripts/#{javascript}.js" + end + end + + def mysql_socket_location - MYSQL_SOCKET_LOCATIONS.find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/ - end - - - # Installation skeleton. Intermediate directories are automatically - # created so don't sweat their absence here. - BASEDIRS = %w( - app/controllers - app/helpers - app/models - app/views/layouts - config/environments - config/initializers - config/locales - db - doc - lib - lib/tasks - log - public/images - public/javascripts - public/stylesheets - script/performance - script/process - test/fixtures - test/functional - test/integration - test/performance - test/unit - vendor - vendor/plugins - tmp/sessions - tmp/sockets - tmp/cache - tmp/pids - ) - - MYSQL_SOCKET_LOCATIONS = [ - "/tmp/mysql.sock", # default - "/var/run/mysqld/mysqld.sock", # debian/gentoo - "/var/tmp/mysql.sock", # freebsd - "/var/lib/mysql/mysql.sock", # fedora - "/opt/local/lib/mysql/mysql.sock", # fedora - "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql - "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 - "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 - "/opt/lampp/var/mysql/mysql.sock" # xampp for linux - ] -end + [ + "/tmp/mysql.sock", # default + "/var/run/mysqld/mysqld.sock", # debian/gentoo + "/var/tmp/mysql.sock", # freebsd + "/var/lib/mysql/mysql.sock", # fedora + "/opt/local/lib/mysql/mysql.sock", # fedora + "/opt/local/var/run/mysqld/mysqld.sock", # mac + darwinports + mysql + "/opt/local/var/run/mysql4/mysqld.sock", # mac + darwinports + mysql4 + "/opt/local/var/run/mysql5/mysqld.sock", # mac + darwinports + mysql5 + "/opt/lampp/var/mysql/mysql.sock" # xampp for linux + ].find { |f| File.exist?(f) } unless RUBY_PLATFORM =~ /(:?mswin|mingw)/ + end +end \ No newline at end of file -- cgit v1.2.3 From 6e66e7d6460b99bb0877a891aa3fbb789b563123 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:53:21 -0600 Subject: Even more polish of the default configration files and split off the session store configuration into its own file --- railties/configs/initializers/session_store.rb | 13 +++++++++ railties/environments/environment.rb | 37 ++++++-------------------- railties/environments/test.rb | 5 ++++ 3 files changed, 26 insertions(+), 29 deletions(-) create mode 100644 railties/configs/initializers/session_store.rb (limited to 'railties') diff --git a/railties/configs/initializers/session_store.rb b/railties/configs/initializers/session_store.rb new file mode 100644 index 0000000000..29bfbe68a8 --- /dev/null +++ b/railties/configs/initializers/session_store.rb @@ -0,0 +1,13 @@ +# Your secret key for verifying cookie session data integrity. +# If you change this key, all old sessions will become invalid! +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +ActionController::Base.session = { + :session_key => '_<%= app_name %>_session', + :secret => '<%= app_secret %>' +} + +# Use the database for sessions instead of the cookie-based default, +# which shouldn't be used to store highly confidential information +# (create the session table with "rake db:sessions:create") +# ActionController::Base.session_store = :active_record_store diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 66f71e5d9b..392e12f438 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -12,7 +12,7 @@ Rails::Initializer.run do |config| # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs - # config.load_paths += %W( #{RAILS_ROOT}/extras ) + # config.load_paths += %w( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" @@ -28,35 +28,14 @@ Rails::Initializer.run do |config| # you must remove the Active Record framework. # config.frameworks -= [ :active_record, :active_resource, :action_mailer ] - # Make Time.zone default to the specified zone, and make Active Record store time values - # in the database in UTC, and return them converted to the specified local zone. - # Run "rake -D time" for a list of tasks for finding time zone names. Comment line to use default local time. + # Activate observers that should always be running + # config.active_record.observers = :cacher, :garbage_collector, :forum_observer + + # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. + # Run "rake -D time" for a list of tasks for finding time zone names. config.time_zone = 'UTC' - # The internationalization framework can be changed to have another default locale (default is :en) or more load paths. - # All files from config/locales/*.rb,yml are added automatically. + # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path << Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de - - # Your secret key for verifying cookie session data integrity. - # If you change this key, all old sessions will become invalid! - # Make sure the secret is at least 30 characters and all random, - # no regular words or you'll be exposed to dictionary attacks. - config.action_controller.session = { - :session_key => '_<%= app_name %>_session', - :secret => '<%= app_secret %>' - } - - # Use the database for sessions instead of the cookie-based default, - # which shouldn't be used to store highly confidential information - # (create the session table with "rake db:sessions:create") - # config.action_controller.session_store = :active_record_store - - # Use SQL instead of Active Record's schema dumper when creating the test database. - # This is necessary if your schema can't be completely dumped by the schema dumper, - # like if you have constraints or database-specific column types - # config.active_record.schema_format = :sql - - # Activate observers that should always be running - # config.active_record.observers = :cacher, :garbage_collector, :forum_observer -end +end \ No newline at end of file diff --git a/railties/environments/test.rb b/railties/environments/test.rb index 1e709e1d19..496eb9572b 100644 --- a/railties/environments/test.rb +++ b/railties/environments/test.rb @@ -20,3 +20,8 @@ config.action_controller.allow_forgery_protection = false # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test + +# Use SQL instead of Active Record's schema dumper when creating the test database. +# This is necessary if your schema can't be completely dumped by the schema dumper, +# like if you have constraints or database-specific column types +# config.active_record.schema_format = :sql \ No newline at end of file -- cgit v1.2.3 From 668872efd85291895d3e68f3a5af312973a1be74 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:54:44 -0600 Subject: Add restart notice where missing --- railties/configs/initializers/new_rails_defaults.rb | 2 ++ railties/configs/initializers/session_store.rb | 2 ++ 2 files changed, 4 insertions(+) (limited to 'railties') diff --git a/railties/configs/initializers/new_rails_defaults.rb b/railties/configs/initializers/new_rails_defaults.rb index 78e0117cc4..8ec3186c84 100644 --- a/railties/configs/initializers/new_rails_defaults.rb +++ b/railties/configs/initializers/new_rails_defaults.rb @@ -1,3 +1,5 @@ +# Be sure to restart your server when you modify this file. + # These settings change the behavior of Rails 2 apps and will be defaults # for Rails 3. You can remove this initializer when Rails 3 is released. diff --git a/railties/configs/initializers/session_store.rb b/railties/configs/initializers/session_store.rb index 29bfbe68a8..40179e0aa3 100644 --- a/railties/configs/initializers/session_store.rb +++ b/railties/configs/initializers/session_store.rb @@ -1,3 +1,5 @@ +# Be sure to restart your server when you modify this file. + # Your secret key for verifying cookie session data integrity. # If you change this key, all old sessions will become invalid! # Make sure the secret is at least 30 characters and all random, -- cgit v1.2.3 From be140e8c6be966349c6fa35a87f84d5a73995b9a Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 15:59:30 -0600 Subject: Changed Rails.root to return a Pathname object (allows for Rails.root.join("app", "controllers") => "#{RAILS_ROOT}/app/controllers") [#1482] --- railties/CHANGELOG | 2 +- railties/lib/initializer.rb | 4 ++-- railties/test/initializer_test.rb | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index ad8ba43c17..6d822a2f88 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,6 +1,6 @@ *2.3.0 [Edge]* -* Enhanced Rails.root to take parameters that'll be join with the root, like Rails.root('app', 'controllers') => File.join(Rails.root, 'app', 'controllers') #1482 [Damian Janowski] +* Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?] * Added view path support for engines [DHH] diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index ef0c335478..a134c68a50 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -48,8 +48,8 @@ module Rails end end - def root(*args) - File.join(RAILS_ROOT, *args.compact) if defined?(RAILS_ROOT) + def root + Pathname.new(RAILS_ROOT) if defined?(RAILS_ROOT) end def env diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 33c81bc5ad..99f69a1575 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -317,7 +317,7 @@ class RailsRootTest < Test::Unit::TestCase assert_equal RAILS_ROOT, Rails.root end - def test_rails_dot_root_accepts_arguments_for_file_dot_join - assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root('app', 'controllers') + def test_rails_dot_root_should_be_a_pathname + assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root.join('app', 'controllers') end end \ No newline at end of file -- cgit v1.2.3 From 3b3c0507e2f67a0f64dc04b396c1d13411ab5890 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Sun, 30 Nov 2008 16:23:20 -0600 Subject: Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [DHH] --- railties/CHANGELOG | 2 + railties/Rakefile | 6 +- railties/bin/process/inspector | 3 - railties/bin/process/reaper | 3 - railties/bin/process/spawner | 3 - railties/lib/commands/process/inspector.rb | 68 ------- railties/lib/commands/process/reaper.rb | 149 -------------- railties/lib/commands/process/spawner.rb | 219 --------------------- railties/lib/commands/process/spinner.rb | 57 ------ .../generators/applications/app/app_generator.rb | 5 +- 10 files changed, 5 insertions(+), 510 deletions(-) delete mode 100755 railties/bin/process/inspector delete mode 100755 railties/bin/process/reaper delete mode 100755 railties/bin/process/spawner delete mode 100644 railties/lib/commands/process/inspector.rb delete mode 100644 railties/lib/commands/process/reaper.rb delete mode 100644 railties/lib/commands/process/spawner.rb delete mode 100644 railties/lib/commands/process/spinner.rb (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 6d822a2f88..3c56f9cecb 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,7 @@ *2.3.0 [Edge]* +* Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [DHH] + * Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?] * Added view path support for engines [DHH] diff --git a/railties/Rakefile b/railties/Rakefile index bf70219aa8..f812b42f1d 100644 --- a/railties/Rakefile +++ b/railties/Rakefile @@ -53,7 +53,6 @@ BASE_DIRS = %w( public script script/performance - script/process test vendor vendor/plugins @@ -71,7 +70,7 @@ LOG_FILES = %w( server.log development.log test.log production.log ) HTML_FILES = %w( 422.html 404.html 500.html index.html robots.txt favicon.ico images/rails.png javascripts/prototype.js javascripts/application.js javascripts/effects.js javascripts/dragdrop.js javascripts/controls.js ) -BIN_FILES = %w( about console destroy generate performance/benchmarker performance/profiler process/reaper process/spawner process/inspector runner server plugin ) +BIN_FILES = %w( about console destroy generate performance/benchmarker performance/profiler runner server plugin ) VENDOR_LIBS = %w( actionpack activerecord actionmailer activesupport activeresource railties ) @@ -174,9 +173,6 @@ task :copy_dispatches do copy_with_rewritten_ruby_path("dispatches/dispatch.fcgi", "#{PKG_DESTINATION}/public/dispatch.fcgi") chmod 0755, "#{PKG_DESTINATION}/public/dispatch.fcgi" - - # copy_with_rewritten_ruby_path("dispatches/gateway.cgi", "#{PKG_DESTINATION}/public/gateway.cgi") - # chmod 0755, "#{PKG_DESTINATION}/public/gateway.cgi" end task :copy_html_files do diff --git a/railties/bin/process/inspector b/railties/bin/process/inspector deleted file mode 100755 index bf25ad86d1..0000000000 --- a/railties/bin/process/inspector +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env ruby -require File.dirname(__FILE__) + '/../../config/boot' -require 'commands/process/inspector' diff --git a/railties/bin/process/reaper b/railties/bin/process/reaper deleted file mode 100755 index c77f04535f..0000000000 --- a/railties/bin/process/reaper +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env ruby -require File.dirname(__FILE__) + '/../../config/boot' -require 'commands/process/reaper' diff --git a/railties/bin/process/spawner b/railties/bin/process/spawner deleted file mode 100755 index 7118f3983c..0000000000 --- a/railties/bin/process/spawner +++ /dev/null @@ -1,3 +0,0 @@ -#!/usr/bin/env ruby -require File.dirname(__FILE__) + '/../../config/boot' -require 'commands/process/spawner' diff --git a/railties/lib/commands/process/inspector.rb b/railties/lib/commands/process/inspector.rb deleted file mode 100644 index 8a6437e715..0000000000 --- a/railties/lib/commands/process/inspector.rb +++ /dev/null @@ -1,68 +0,0 @@ -require 'optparse' - -if RUBY_PLATFORM =~ /(:?mswin|mingw)/ then abort("Inspector is only for Unix") end - -OPTIONS = { - :pid_path => File.expand_path(RAILS_ROOT + '/tmp/pids'), - :pattern => "dispatch.*.pid", - :ps => "ps -o pid,state,user,start,time,pcpu,vsz,majflt,command -p %s" -} - -class Inspector - def self.inspect(pid_path, pattern) - new(pid_path, pattern).inspect - end - - def initialize(pid_path, pattern) - @pid_path, @pattern = pid_path, pattern - end - - def inspect - header = `#{OPTIONS[:ps] % 1}`.split("\n")[0] + "\n" - lines = pids.collect { |pid| `#{OPTIONS[:ps] % pid}`.split("\n")[1] } - - puts(header + lines.join("\n")) - end - - private - def pids - pid_files.collect do |pid_file| - File.read(pid_file).to_i - end - end - - def pid_files - Dir.glob(@pid_path + "/" + @pattern) - end -end - - -ARGV.options do |opts| - opts.banner = "Usage: inspector [options]" - - opts.separator "" - - opts.on <<-EOF - Description: - Displays system information about Rails dispatchers (or other processes that use pid files) through - the ps command. - - Examples: - inspector # default ps on all tmp/pids/dispatch.*.pid files - inspector -s 'ps -o user,start,majflt,pcpu,vsz -p %s' # custom ps, %s is where the pid is interleaved - EOF - - opts.on(" Options:") - - opts.on("-s", "--ps=command", "default: #{OPTIONS[:ps]}", String) { |v| OPTIONS[:ps] = v } - opts.on("-p", "--pidpath=path", "default: #{OPTIONS[:pid_path]}", String) { |v| OPTIONS[:pid_path] = v } - opts.on("-r", "--pattern=pattern", "default: #{OPTIONS[:pattern]}", String) { |v| OPTIONS[:pattern] = v } - - opts.separator "" - - opts.on("-h", "--help", "Show this help message.") { puts opts; exit } - - opts.parse! -end - -Inspector.inspect(OPTIONS[:pid_path], OPTIONS[:pattern]) diff --git a/railties/lib/commands/process/reaper.rb b/railties/lib/commands/process/reaper.rb deleted file mode 100644 index 95175d41e0..0000000000 --- a/railties/lib/commands/process/reaper.rb +++ /dev/null @@ -1,149 +0,0 @@ -require 'optparse' -require 'net/http' -require 'uri' - -if RUBY_PLATFORM =~ /(:?mswin|mingw)/ then abort("Reaper is only for Unix") end - -class Killer - class << self - # Searches for all processes matching the given keywords, and then invokes - # a specific action on each of them. This is useful for (e.g.) reloading a - # set of processes: - # - # Killer.process(:reload, "/tmp/pids", "dispatcher.*.pid") - def process(action, pid_path, pattern, keyword) - new(pid_path, pattern, keyword).process(action) - end - - # Forces the (rails) application to reload by sending a +HUP+ signal to the - # process. - def reload(pid) - `kill -s HUP #{pid}` - end - - # Force the (rails) application to restart by sending a +USR2+ signal to the - # process. - def restart(pid) - `kill -s USR2 #{pid}` - end - - # Forces the (rails) application to gracefully terminate by sending a - # +TERM+ signal to the process. - def graceful(pid) - `kill -s TERM #{pid}` - end - - # Forces the (rails) application to terminate immediately by sending a -9 - # signal to the process. - def kill(pid) - `kill -9 #{pid}` - end - - # Send a +USR1+ signal to the process. - def usr1(pid) - `kill -s USR1 #{pid}` - end - end - - def initialize(pid_path, pattern, keyword=nil) - @pid_path, @pattern, @keyword = pid_path, pattern, keyword - end - - def process(action) - pids = find_processes - - if pids.empty? - warn "Couldn't find any pid file in '#{@pid_path}' matching '#{@pattern}'" - warn "(also looked for processes matching #{@keyword.inspect})" if @keyword - else - pids.each do |pid| - puts "#{action.capitalize}ing #{pid}" - self.class.send(action, pid) - end - - delete_pid_files if terminating?(action) - end - end - - private - def terminating?(action) - [ "kill", "graceful" ].include?(action) - end - - def find_processes - files = pid_files - if files.empty? - find_processes_via_grep - else - files.collect { |pid_file| File.read(pid_file).to_i } - end - end - - def find_processes_via_grep - lines = `ps axww -o 'pid command' | grep #{@keyword}`.split(/\n/). - reject { |line| line =~ /inq|ps axww|grep|spawn-fcgi|spawner|reaper/ } - lines.map { |line| line[/^\s*(\d+)/, 1].to_i } - end - - def delete_pid_files - pid_files.each { |pid_file| File.delete(pid_file) } - end - - def pid_files - Dir.glob(@pid_path + "/" + @pattern) - end -end - - -OPTIONS = { - :action => "restart", - :pid_path => File.expand_path(RAILS_ROOT + '/tmp/pids'), - :pattern => "dispatch.[0-9]*.pid", - :dispatcher => File.expand_path("#{RAILS_ROOT}/public/dispatch.fcgi") -} - -ARGV.options do |opts| - opts.banner = "Usage: reaper [options]" - - opts.separator "" - - opts.on <<-EOF - Description: - The reaper is used to restart, reload, gracefully exit, and forcefully exit processes - running a Rails Dispatcher (or any other process responding to the same signals). This - is commonly done when a new version of the application is available, so the existing - processes can be updated to use the latest code. - - It uses pid files to work on the processes and by default assume them to be located - in RAILS_ROOT/tmp/pids. - - The reaper actions are: - - * restart : Restarts the application by reloading both application and framework code - * reload : Only reloads the application, but not the framework (like the development environment) - * graceful: Marks all of the processes for exit after the next request - * kill : Forcefully exists all processes regardless of whether they're currently serving a request - - Restart is the most common and default action. - - Examples: - reaper # restarts the default dispatchers - reaper -a reload # reload the default dispatchers - reaper -a kill -r *.pid # kill all processes that keep pids in tmp/pids - EOF - - opts.on(" Options:") - - opts.on("-a", "--action=name", "reload|graceful|kill (default: #{OPTIONS[:action]})", String) { |v| OPTIONS[:action] = v } - opts.on("-p", "--pidpath=path", "default: #{OPTIONS[:pid_path]}", String) { |v| OPTIONS[:pid_path] = v } - opts.on("-r", "--pattern=pattern", "default: #{OPTIONS[:pattern]}", String) { |v| OPTIONS[:pattern] = v } - opts.on("-d", "--dispatcher=path", "DEPRECATED. default: #{OPTIONS[:dispatcher]}", String) { |v| OPTIONS[:dispatcher] = v } - - opts.separator "" - - opts.on("-h", "--help", "Show this help message.") { puts opts; exit } - - opts.parse! -end - -Killer.process(OPTIONS[:action], OPTIONS[:pid_path], OPTIONS[:pattern], OPTIONS[:dispatcher]) diff --git a/railties/lib/commands/process/spawner.rb b/railties/lib/commands/process/spawner.rb deleted file mode 100644 index 8bf47abb75..0000000000 --- a/railties/lib/commands/process/spawner.rb +++ /dev/null @@ -1,219 +0,0 @@ -require 'active_support' -require 'optparse' -require 'socket' -require 'fileutils' - -def daemonize #:nodoc: - exit if fork # Parent exits, child continues. - Process.setsid # Become session leader. - exit if fork # Zap session leader. See [1]. - Dir.chdir "/" # Release old working directory. - File.umask 0000 # Ensure sensible umask. Adjust as needed. - STDIN.reopen "/dev/null" # Free file descriptors and - STDOUT.reopen "/dev/null", "a" # point them somewhere sensible. - STDERR.reopen STDOUT # STDOUT/ERR should better go to a logfile. -end - -class Spawner - def self.record_pid(name = "#{OPTIONS[:process]}.spawner", id = Process.pid) - FileUtils.mkdir_p(OPTIONS[:pids]) - File.open(File.expand_path(OPTIONS[:pids] + "/#{name}.pid"), "w+") { |f| f.write(id) } - end - - def self.spawn_all - OPTIONS[:instances].times do |i| - port = OPTIONS[:port] + i - print "Checking if something is already running on #{OPTIONS[:address]}:#{port}..." - - begin - srv = TCPServer.new(OPTIONS[:address], port) - srv.close - srv = nil - - puts "NO" - puts "Starting dispatcher on port: #{OPTIONS[:address]}:#{port}" - - FileUtils.mkdir_p(OPTIONS[:pids]) - spawn(port) - rescue - puts "YES" - end - end - end -end - -class FcgiSpawner < Spawner - def self.spawn(port) - cmd = "#{OPTIONS[:spawner]} -f #{OPTIONS[:dispatcher]} -p #{port} -P #{OPTIONS[:pids]}/#{OPTIONS[:process]}.#{port}.pid" - cmd << " -a #{OPTIONS[:address]}" if can_bind_to_custom_address? - system(cmd) - end - - def self.can_bind_to_custom_address? - @@can_bind_to_custom_address ||= /^\s-a\s/.match `#{OPTIONS[:spawner]} -h` - end -end - -class MongrelSpawner < Spawner - def self.spawn(port) - cmd = - "mongrel_rails start -d " + - "-a #{OPTIONS[:address]} " + - "-p #{port} " + - "-P #{OPTIONS[:pids]}/#{OPTIONS[:process]}.#{port}.pid " + - "-e #{OPTIONS[:environment]} " + - "-c #{OPTIONS[:rails_root]} " + - "-l #{OPTIONS[:rails_root]}/log/mongrel.log" - - # Add prefix functionality to spawner's call to mongrel_rails - # Digging through mongrel's project subversion server, the earliest - # Tag that has prefix implemented in the bin/mongrel_rails file - # is 0.3.15 which also happens to be the earliest tag listed. - # References: http://mongrel.rubyforge.org/svn/tags - if Mongrel::Const::MONGREL_VERSION.to_f >=0.3 && !OPTIONS[:prefix].nil? - cmd = cmd + " --prefix #{OPTIONS[:prefix]}" - end - system(cmd) - end - - def self.can_bind_to_custom_address? - true - end -end - - -begin - require_library_or_gem 'fcgi' -rescue Exception - # FCGI not available -end - -begin - require_library_or_gem 'mongrel' -rescue Exception - # Mongrel not available -end - -server = case ARGV.first - when "fcgi", "mongrel" - ARGV.shift - else - if defined?(Mongrel) - "mongrel" - elsif RUBY_PLATFORM !~ /(:?mswin|mingw)/ && !silence_stderr { `spawn-fcgi -version` }.blank? && defined?(FCGI) - "fcgi" - end -end - -case server - when "fcgi" - puts "=> Starting FCGI dispatchers" - spawner_class = FcgiSpawner - when "mongrel" - puts "=> Starting mongrel dispatchers" - spawner_class = MongrelSpawner - else - puts "Neither FCGI (spawn-fcgi) nor Mongrel was installed and available!" - exit(0) -end - - - -OPTIONS = { - :environment => "production", - :spawner => '/usr/bin/env spawn-fcgi', - :dispatcher => File.expand_path(RELATIVE_RAILS_ROOT + '/public/dispatch.fcgi'), - :pids => File.expand_path(RELATIVE_RAILS_ROOT + "/tmp/pids"), - :rails_root => File.expand_path(RELATIVE_RAILS_ROOT), - :process => "dispatch", - :port => 8000, - :address => '0.0.0.0', - :instances => 3, - :repeat => nil, - :prefix => nil -} - -ARGV.options do |opts| - opts.banner = "Usage: spawner [platform] [options]" - - opts.separator "" - - opts.on <<-EOF - Description: - The spawner is a wrapper for spawn-fcgi and mongrel that makes it - easier to start multiple processes running the Rails dispatcher. The - spawn-fcgi command is included with the lighttpd web server, but can - be used with both Apache and lighttpd (and any other web server - supporting externally managed FCGI processes). Mongrel automatically - ships with with mongrel_rails for starting dispatchers. - - The first choice you need to make is whether to spawn the Rails - dispatchers as FCGI or Mongrel. By default, this spawner will prefer - Mongrel, so if that's installed, and no platform choice is made, - Mongrel is used. - - Then decide a starting port (default is 8000) and the number of FCGI - process instances you'd like to run. So if you pick 9100 and 3 - instances, you'll start processes on 9100, 9101, and 9102. - - By setting the repeat option, you get a protection loop, which will - attempt to restart any FCGI processes that might have been exited or - outright crashed. - - You can select bind address for started processes. By default these - listen on every interface. For single machine installations you would - probably want to use 127.0.0.1, hiding them form the outside world. - - Examples: - spawner # starts instances on 8000, 8001, and 8002 - # using Mongrel if available. - spawner fcgi # starts instances on 8000, 8001, and 8002 - # using FCGI. - spawner mongrel -i 5 # starts instances on 8000, 8001, 8002, - # 8003, and 8004 using Mongrel. - spawner -p 9100 -i 10 # starts 10 instances counting from 9100 to - # 9109 using Mongrel if available. - spawner -p 9100 -r 5 # starts 3 instances counting from 9100 to - # 9102 and attempts start them every 5 - # seconds. - spawner -a 127.0.0.1 # starts 3 instances binding to localhost - EOF - - opts.on(" Options:") - - opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v } - - if spawner_class.can_bind_to_custom_address? - opts.on("-a", "--address=ip", String, "Bind to IP address (default: #{OPTIONS[:address]})") { |v| OPTIONS[:address] = v } - end - - opts.on("-p", "--port=number", Integer, "Starting port number (default: #{OPTIONS[:port]})") { |v| OPTIONS[:port] = v } - opts.on("-i", "--instances=number", Integer, "Number of instances (default: #{OPTIONS[:instances]})") { |v| OPTIONS[:instances] = v } - opts.on("-r", "--repeat=seconds", Integer, "Repeat spawn attempts every n seconds (default: off)") { |v| OPTIONS[:repeat] = v } - opts.on("-e", "--environment=name", String, "test|development|production (default: #{OPTIONS[:environment]})") { |v| OPTIONS[:environment] = v } - opts.on("-P", "--prefix=path", String, "URL prefix for Rails app. [Used only with Mongrel > v0.3.15]: (default: #{OPTIONS[:prefix]})") { |v| OPTIONS[:prefix] = v } - opts.on("-n", "--process=name", String, "default: #{OPTIONS[:process]}") { |v| OPTIONS[:process] = v } - opts.on("-s", "--spawner=path", String, "default: #{OPTIONS[:spawner]}") { |v| OPTIONS[:spawner] = v } - opts.on("-d", "--dispatcher=path", String, "default: #{OPTIONS[:dispatcher]}") { |dispatcher| OPTIONS[:dispatcher] = File.expand_path(dispatcher) } - - opts.separator "" - - opts.on("-h", "--help", "Show this help message.") { puts opts; exit } - - opts.parse! -end - -ENV["RAILS_ENV"] = OPTIONS[:environment] - -if OPTIONS[:repeat] - daemonize - trap("TERM") { exit } - spawner_class.record_pid - - loop do - spawner_class.spawn_all - sleep(OPTIONS[:repeat]) - end -else - spawner_class.spawn_all -end diff --git a/railties/lib/commands/process/spinner.rb b/railties/lib/commands/process/spinner.rb deleted file mode 100644 index c0b2f09a94..0000000000 --- a/railties/lib/commands/process/spinner.rb +++ /dev/null @@ -1,57 +0,0 @@ -require 'optparse' - -def daemonize #:nodoc: - exit if fork # Parent exits, child continues. - Process.setsid # Become session leader. - exit if fork # Zap session leader. See [1]. - Dir.chdir "/" # Release old working directory. - File.umask 0000 # Ensure sensible umask. Adjust as needed. - STDIN.reopen "/dev/null" # Free file descriptors and - STDOUT.reopen "/dev/null", "a" # point them somewhere sensible. - STDERR.reopen STDOUT # STDOUT/ERR should better go to a logfile. -end - -OPTIONS = { - :interval => 5.0, - :command => File.expand_path(RAILS_ROOT + '/script/process/spawner'), - :daemon => false -} - -ARGV.options do |opts| - opts.banner = "Usage: spinner [options]" - - opts.separator "" - - opts.on <<-EOF - Description: - The spinner is a protection loop for the spawner, which will attempt to restart any FCGI processes - that might have been exited or outright crashed. It's a brute-force attempt that'll just try - to run the spawner every X number of seconds, so it does pose a light load on the server. - - Examples: - spinner # attempts to run the spawner with default settings every second with output on the terminal - spinner -i 3 -d # only run the spawner every 3 seconds and detach from the terminal to become a daemon - spinner -c '/path/to/app/script/process/spawner -p 9000 -i 10' -d # using custom spawner - EOF - - opts.on(" Options:") - - opts.on("-c", "--command=path", String) { |v| OPTIONS[:command] = v } - opts.on("-i", "--interval=seconds", Float) { |v| OPTIONS[:interval] = v } - opts.on("-d", "--daemon") { |v| OPTIONS[:daemon] = v } - - opts.separator "" - - opts.on("-h", "--help", "Show this help message.") { puts opts; exit } - - opts.parse! -end - -daemonize if OPTIONS[:daemon] - -trap(OPTIONS[:daemon] ? "TERM" : "INT") { exit } - -loop do - system(OPTIONS[:command]) - sleep(OPTIONS[:interval]) -end \ No newline at end of file diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 5435b2aeb3..fb3a407d2e 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -85,7 +85,6 @@ class AppGenerator < Rails::Generator::Base public/javascripts public/stylesheets script/performance - script/process test/fixtures test/functional test/integration @@ -139,8 +138,8 @@ class AppGenerator < Rails::Generator::Base def create_script_files(m) %w( - about console dbconsole destroy generate performance/benchmarker performance/profiler - performance/request process/reaper process/spawner process/inspector runner server plugin + about console dbconsole destroy generate runner server plugin + performance/benchmarker performance/profiler performance/request ).each do |file| m.file "bin/#{file}", "script/#{file}", { :chmod => 0755, -- cgit v1.2.3 From 926844e869b747fa1e9474fd95f9b97fa04ae092 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Fri, 28 Nov 2008 17:36:17 -0600 Subject: Switch FCGI handler over to Rack --- railties/lib/fcgi_handler.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/fcgi_handler.rb b/railties/lib/fcgi_handler.rb index 1bb55b9275..1256ef2286 100644 --- a/railties/lib/fcgi_handler.rb +++ b/railties/lib/fcgi_handler.rb @@ -98,7 +98,7 @@ class RailsFCGIHandler with_signal_handler 'USR1' do begin - Dispatcher.dispatch(cgi) + ::Rack::Handler::FastCGI.serve(cgi, Dispatcher.new) rescue SignalException, SystemExit raise rescue Exception => error -- cgit v1.2.3 From 725928854d4b6ff5dbafc2bbc95cfade243411a9 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 1 Dec 2008 12:12:57 -0600 Subject: fix failing railties test --- railties/test/initializer_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/test/initializer_test.rb b/railties/test/initializer_test.rb index 99f69a1575..dad9e55e61 100644 --- a/railties/test/initializer_test.rb +++ b/railties/test/initializer_test.rb @@ -314,10 +314,10 @@ end class RailsRootTest < Test::Unit::TestCase def test_rails_dot_root_equals_rails_root - assert_equal RAILS_ROOT, Rails.root + assert_equal RAILS_ROOT, Rails.root.to_s end def test_rails_dot_root_should_be_a_pathname - assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root.join('app', 'controllers') + assert_equal File.join(RAILS_ROOT, 'app', 'controllers'), Rails.root.join('app', 'controllers').to_s end end \ No newline at end of file -- cgit v1.2.3 From 61958032d3dbb8da8363d02ccda8933b99421fb1 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 1 Dec 2008 12:21:18 -0600 Subject: Generate rackup dispatcher with rails:update:generate_dispatchers --- railties/config.ru | 17 ----------------- railties/dispatches/config.ru | 7 +++++++ railties/lib/commands/server.rb | 20 +++++++++++--------- .../generators/applications/app/app_generator.rb | 1 + railties/lib/tasks/framework.rake | 1 + 5 files changed, 20 insertions(+), 26 deletions(-) delete mode 100644 railties/config.ru create mode 100644 railties/dispatches/config.ru (limited to 'railties') diff --git a/railties/config.ru b/railties/config.ru deleted file mode 100644 index 43492a2dcc..0000000000 --- a/railties/config.ru +++ /dev/null @@ -1,17 +0,0 @@ -# Rackup Configuration -# -# Start Rails mongrel server with rackup -# $ rackup -p 3000 config.ru -# -# Start server with webrick (or any compatible Rack server) instead -# $ rackup -p 3000 -s webrick config.ru - -# Require your environment file to bootstrap Rails -require File.dirname(__FILE__) + '/config/environment' - -# Static server middleware -# You can remove this extra check if you use an asset server -use Rails::Rack::Static - -# Dispatch the request -run ActionController::Dispatcher.new diff --git a/railties/dispatches/config.ru b/railties/dispatches/config.ru new file mode 100644 index 0000000000..acbfe4e9ae --- /dev/null +++ b/railties/dispatches/config.ru @@ -0,0 +1,7 @@ +# Rack Dispatcher + +# Require your environment file to bootstrap Rails +require File.dirname(__FILE__) + '/config/environment' + +# Dispatch the request +run ActionController::Dispatcher.new diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index a4bb52592f..3611f80ed3 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -65,7 +65,6 @@ end ENV["RAILS_ENV"] = options[:environment] RAILS_ENV.replace(options[:environment]) if defined?(RAILS_ENV) -require RAILS_ROOT + "/config/environment" if File.exist?(options[:config]) config = options[:config] @@ -74,20 +73,23 @@ if File.exist?(options[:config]) if cfgfile[/^#\\(.*)/] opts.parse!($1.split(/\s+/)) end - app = eval("Rack::Builder.new {( " + cfgfile + "\n )}.to_app", nil, config) + inner_app = eval("Rack::Builder.new {( " + cfgfile + "\n )}.to_app", nil, config) else require config - app = Object.const_get(File.basename(config, '.rb').capitalize) + inner_app = Object.const_get(File.basename(config, '.rb').capitalize) end else - app = Rack::Builder.new { - use Rails::Rack::Logger - use Rails::Rack::Static - use Rails::Rack::Debugger if options[:debugger] - run ActionController::Dispatcher.new - }.to_app + require RAILS_ROOT + "/config/environment" end +inner_app = ActionController::Dispatcher.new +app = Rack::Builder.new { + use Rails::Rack::Logger + use Rails::Rack::Static + use Rails::Rack::Debugger if options[:debugger] + run inner_app +}.to_app + puts "=> Call with -d to detach" trap(:INT) { exit } diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index fb3a407d2e..4bb94ff96d 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -197,6 +197,7 @@ class AppGenerator < Rails::Generator::Base if options[:with_dispatchers] dispatcher_options = { :chmod => 0755, :shebang => options[:shebang] } + m.file "dispatches/config.ru", "config.ru" m.file "dispatches/dispatch.rb", "public/dispatch.rb", dispatcher_options m.file "dispatches/dispatch.rb", "public/dispatch.cgi", dispatcher_options m.file "dispatches/dispatch.fcgi", "public/dispatch.fcgi", dispatcher_options diff --git a/railties/lib/tasks/framework.rake b/railties/lib/tasks/framework.rake index df080e94ac..d639214ffe 100644 --- a/railties/lib/tasks/framework.rake +++ b/railties/lib/tasks/framework.rake @@ -128,6 +128,7 @@ namespace :rails do desc "Generate dispatcher files in RAILS_ROOT/public" task :generate_dispatchers do require 'railties_path' + FileUtils.cp(RAILTIES_PATH + '/dispatches/config.ru', RAILS_ROOT + '/config.ru') FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.fcgi', RAILS_ROOT + '/public/dispatch.fcgi') FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.rb') FileUtils.cp(RAILTIES_PATH + '/dispatches/dispatch.rb', RAILS_ROOT + '/public/dispatch.cgi') -- cgit v1.2.3 From 25f6524b89900378d08de9ec45757813dbb650cf Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 1 Dec 2008 12:24:02 -0600 Subject: opps, inner_app is in the wrong conditional --- railties/lib/commands/server.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'railties') diff --git a/railties/lib/commands/server.rb b/railties/lib/commands/server.rb index 3611f80ed3..7057fcc33f 100644 --- a/railties/lib/commands/server.rb +++ b/railties/lib/commands/server.rb @@ -80,9 +80,9 @@ if File.exist?(options[:config]) end else require RAILS_ROOT + "/config/environment" + inner_app = ActionController::Dispatcher.new end -inner_app = ActionController::Dispatcher.new app = Rack::Builder.new { use Rails::Rack::Logger use Rails::Rack::Static -- cgit v1.2.3 From 3c07a8828ede3d41000513af29c293ae2e2a49d4 Mon Sep 17 00:00:00 2001 From: Matt Jones Date: Mon, 24 Nov 2008 23:07:12 -0500 Subject: handle missing dependecies in gem loading Signed-off-by: Michael Koziarski --- railties/lib/rails/gem_dependency.rb | 1 + railties/test/gem_dependency_test.rb | 14 ++++++++ .../vendor/gems/dummy-gem-f-1.0.0/.specification | 39 ++++++++++++++++++++++ .../gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb | 1 + .../vendor/gems/dummy-gem-g-1.0.0/.specification | 39 ++++++++++++++++++++++ .../gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb | 1 + 6 files changed, 95 insertions(+) create mode 100644 railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification create mode 100644 railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb create mode 100644 railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification create mode 100644 railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb (limited to 'railties') diff --git a/railties/lib/rails/gem_dependency.rb b/railties/lib/rails/gem_dependency.rb index cd280ac023..5a07841be8 100644 --- a/railties/lib/rails/gem_dependency.rb +++ b/railties/lib/rails/gem_dependency.rb @@ -74,6 +74,7 @@ module Rails def dependencies return [] if framework_gem? + return [] if specification.nil? all_dependencies = specification.dependencies.map do |dependency| GemDependency.new(dependency.name, :requirement => dependency.version_requirements) end diff --git a/railties/test/gem_dependency_test.rb b/railties/test/gem_dependency_test.rb index 4f9e824c9f..1d4f2b18b3 100644 --- a/railties/test/gem_dependency_test.rb +++ b/railties/test/gem_dependency_test.rb @@ -129,5 +129,19 @@ uses_mocha "Plugin Tests" do assert_equal '1.0.0', DUMMY_GEM_E_VERSION end + def test_gem_handle_missing_dependencies + dummy_gem = Rails::GemDependency.new "dummy-gem-g" + dummy_gem.add_load_paths + dummy_gem.load + assert dummy_gem.loaded? + debugger + assert_equal 2, dummy_gem.dependencies.size + assert_nothing_raised do + dummy_gem.dependencies.each do |g| + g.dependencies + end + end + end + end end diff --git a/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification b/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification new file mode 100644 index 0000000000..70a36b9a8c --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-f-1.0.0/.specification @@ -0,0 +1,39 @@ +--- !ruby/object:Gem::Specification +name: dummy-gem-f +version: !ruby/object:Gem::Version + version: 1.3.0 +platform: ruby +authors: +- "Nobody" +date: 2008-10-03 00:00:00 -04:00 +dependencies: +- !ruby/object:Gem::Dependency + name: absolutely-no-such-gem + type: :runtime + version_requirement: + version_requirements: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: 1.0.0 + version: +files: +- lib +- lib/dummy-gem-f.rb +require_paths: +- lib +required_ruby_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +required_rubygems_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +requirements: [] +specification_version: 2 +summary: Dummy Gem F diff --git a/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb b/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb new file mode 100644 index 0000000000..0271c8c48a --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-f-1.0.0/lib/dummy-gem-f.rb @@ -0,0 +1 @@ +DUMMY_GEM_F_VERSION="1.0.0" diff --git a/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification b/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification new file mode 100644 index 0000000000..5483048c1c --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-g-1.0.0/.specification @@ -0,0 +1,39 @@ +--- !ruby/object:Gem::Specification +name: dummy-gem-g +version: !ruby/object:Gem::Version + version: 1.3.0 +platform: ruby +authors: +- "Nobody" +date: 2008-10-03 00:00:00 -04:00 +dependencies: +- !ruby/object:Gem::Dependency + name: dummy-gem-f + type: :development + version_requirement: + version_requirements: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: 1.0.0 + version: +files: +- lib +- lib/dummy-gem-g.rb +require_paths: +- lib +required_ruby_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +required_rubygems_version: !ruby/object:Gem::Requirement + requirements: + - - ">=" + - !ruby/object:Gem::Version + version: "0" + version: +requirements: [] +specification_version: 2 +summary: Dummy Gem G diff --git a/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb b/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb new file mode 100644 index 0000000000..8fc056586c --- /dev/null +++ b/railties/test/vendor/gems/dummy-gem-g-1.0.0/lib/dummy-gem-g.rb @@ -0,0 +1 @@ +DUMMY_GEM_G_VERSION="1.0.0" -- cgit v1.2.3 From 06ed8e451198b2296d8b2752741e259b4f995081 Mon Sep 17 00:00:00 2001 From: Joshua Peek Date: Mon, 1 Dec 2008 13:48:47 -0600 Subject: Add internal middleware stack to Dispatcher config.middleware.use Rack::Cache --- railties/lib/initializer.rb | 5 +++++ railties/lib/tasks/middleware.rake | 7 +++++++ 2 files changed, 12 insertions(+) create mode 100644 railties/lib/tasks/middleware.rake (limited to 'railties') diff --git a/railties/lib/initializer.rb b/railties/lib/initializer.rb index a134c68a50..4bb1e480b7 100644 --- a/railties/lib/initializer.rb +++ b/railties/lib/initializer.rb @@ -881,6 +881,11 @@ Run `rake gems:install` to install the missing gems. end end + def middleware + require 'action_controller' + ActionController::Dispatcher.middleware + end + def builtin_directories # Include builtins only in the development environment. (environment == 'development') ? Dir["#{RAILTIES_PATH}/builtin/*/"] : [] diff --git a/railties/lib/tasks/middleware.rake b/railties/lib/tasks/middleware.rake new file mode 100644 index 0000000000..e0dcf50307 --- /dev/null +++ b/railties/lib/tasks/middleware.rake @@ -0,0 +1,7 @@ +desc 'Prints out your Rack middleware stack' +task :middleware => :environment do + ActionController::Dispatcher.middleware.each do |middleware| + puts "use #{middleware.inspect}" + end + puts "run ActionController::Dispatcher.new" +end -- cgit v1.2.3 From a8fc494dbb86be13248613565c0b611c561cdc48 Mon Sep 17 00:00:00 2001 From: Michael Koziarski Date: Mon, 1 Dec 2008 21:19:55 +0100 Subject: Manually load the DB config rather than firing the whole initializer [Gerrit Kaiser] --- railties/lib/tasks/databases.rake | 13 +++++++++---- railties/lib/tasks/misc.rake | 6 ++++++ 2 files changed, 15 insertions(+), 4 deletions(-) (limited to 'railties') diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index 5cb27f1f10..2140adb76e 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -1,7 +1,12 @@ namespace :db do + task :load_config => :rails_env do + require 'active_record' + ActiveRecord::Base.configurations = Rails::Configuration.new.database_configuration + end + namespace :create do desc 'Create all the local databases defined in config/database.yml' - task :all => :environment do + task :all => :load_config do ActiveRecord::Base.configurations.each_value do |config| # Skip entries that don't have a database key, such as the first entry here: # @@ -22,7 +27,7 @@ namespace :db do end desc 'Create the database defined in config/database.yml for the current RAILS_ENV' - task :create => :environment do + task :create => :load_config do create_database(ActiveRecord::Base.configurations[RAILS_ENV]) end @@ -76,7 +81,7 @@ namespace :db do namespace :drop do desc 'Drops all the local databases defined in config/database.yml' - task :all => :environment do + task :all => :load_config do ActiveRecord::Base.configurations.each_value do |config| # Skip entries that don't have a database key next unless config['database'] @@ -87,7 +92,7 @@ namespace :db do end desc 'Drops the database for the current RAILS_ENV' - task :drop => :environment do + task :drop => :load_config do config = ActiveRecord::Base.configurations[RAILS_ENV || 'development'] begin drop_database(config) diff --git a/railties/lib/tasks/misc.rake b/railties/lib/tasks/misc.rake index 5c99725203..411750bf40 100644 --- a/railties/lib/tasks/misc.rake +++ b/railties/lib/tasks/misc.rake @@ -3,6 +3,12 @@ task :environment do require(File.join(RAILS_ROOT, 'config', 'environment')) end +task :rails_env do + unless defined? RAILS_ENV + RAILS_ENV = ENV['RAILS_ENV'] ||= 'development' + end +end + desc 'Generate a crytographically secure secret key. This is typically used to generate a secret for cookie sessions.' task :secret do puts ActiveSupport::SecureRandom.hex(64) -- cgit v1.2.3 From a0bc480e1ddcaa015927c2d941e7b96a8ce4f6fa Mon Sep 17 00:00:00 2001 From: Aliaksey Kandratsenka Date: Fri, 28 Nov 2008 17:09:46 +0200 Subject: establish mysql connection before dropping database Signed-off-by: Michael Koziarski [#63 state:committed] --- railties/lib/tasks/databases.rake | 1 + 1 file changed, 1 insertion(+) (limited to 'railties') diff --git a/railties/lib/tasks/databases.rake b/railties/lib/tasks/databases.rake index 2140adb76e..a90c1d4a77 100644 --- a/railties/lib/tasks/databases.rake +++ b/railties/lib/tasks/databases.rake @@ -398,6 +398,7 @@ end def drop_database(config) case config['adapter'] when 'mysql' + ActiveRecord::Base.establish_connection(config) ActiveRecord::Base.connection.drop_database config['database'] when /^sqlite/ FileUtils.rm(File.join(RAILS_ROOT, config['database'])) -- cgit v1.2.3 From bf024b6a11253b3d2599caf41f7ccf2d31e68cb3 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Mon, 1 Dec 2008 23:06:29 -0600 Subject: Github comments are an excellent way to perform community code review -- keep it up! --- railties/environments/environment.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'railties') diff --git a/railties/environments/environment.rb b/railties/environments/environment.rb index 392e12f438..4a2df36307 100644 --- a/railties/environments/environment.rb +++ b/railties/environments/environment.rb @@ -12,7 +12,7 @@ Rails::Initializer.run do |config| # -- all .rb files in that directory are automatically loaded. # Add additional load paths for your own custom dirs - # config.load_paths += %w( #{RAILS_ROOT}/extras ) + # config.load_paths += %W( #{RAILS_ROOT}/extras ) # Specify gems that this application depends on and have them installed with rake gems:install # config.gem "bj" @@ -36,6 +36,6 @@ Rails::Initializer.run do |config| config.time_zone = 'UTC' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. - # config.i18n.load_path << Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] + # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}')] # config.i18n.default_locale = :de end \ No newline at end of file -- cgit v1.2.3 From e8cc4b116c460c524961a07da92da3f323854c15 Mon Sep 17 00:00:00 2001 From: Jeremy McAnally Date: Tue, 2 Dec 2008 17:22:27 +0100 Subject: Add "-m/--template" option to Rails generator to apply template to generated application. Signed-off-by: Pratik Naik --- railties/CHANGELOG | 43 +++ railties/bin/rails | 1 + railties/lib/rails_generator/base.rb | 3 + railties/lib/rails_generator/commands.rb | 1 + .../generators/applications/app/app_generator.rb | 12 + .../generators/applications/app/scm/git.rb | 16 + .../generators/applications/app/scm/scm.rb | 8 + .../generators/applications/app/scm/svn.rb | 7 + .../generators/applications/app/template_runner.rb | 376 +++++++++++++++++++++ 9 files changed, 467 insertions(+) create mode 100644 railties/lib/rails_generator/generators/applications/app/scm/git.rb create mode 100644 railties/lib/rails_generator/generators/applications/app/scm/scm.rb create mode 100644 railties/lib/rails_generator/generators/applications/app/scm/svn.rb create mode 100644 railties/lib/rails_generator/generators/applications/app/template_runner.rb (limited to 'railties') diff --git a/railties/CHANGELOG b/railties/CHANGELOG index 3c56f9cecb..ca49c5d1c7 100644 --- a/railties/CHANGELOG +++ b/railties/CHANGELOG @@ -1,5 +1,48 @@ *2.3.0 [Edge]* +* Add "-m/--template" option to Rails generator to apply a template to the generated application. [Jeremy McAnally] + + This has been extracted from rg - http://github.com/jeremymcanally/rg + + Example: + + # template.rb + + # Install plugins from git or svn + plugin "will-paginate", :git => "git://github.com/mislav/will_paginate.git" + plugin "old-restful-auth", :svn => "http://svn.techno-weenie.net/projects/plugins/restful_authentication/" + + # Add gems to environment.rb + gem "jeremymcanally-context" + gem "bluecloth" + + # Vendor file. Data in a string or... + vendor("borrowed.rb", < -m /path/to/my/template.rb + + 2. Or directly from a URL : + + rails --template=http://gist.github.com/31208.txt + * Extracted the process scripts (inspector, reaper, spawner) into the plugin irs_process_scripts [DHH] * Changed Rails.root to return a Pathname object (allows for Rails.root.join('app', 'controllers') => "#{RAILS_ROOT}/app/controllers") #1482 [Damian Janowski/?] diff --git a/railties/bin/rails b/railties/bin/rails index ae0cc8adca..6a0c675206 100755 --- a/railties/bin/rails +++ b/railties/bin/rails @@ -8,6 +8,7 @@ if %w(--version -v).include? ARGV.first end freeze = ARGV.any? { |option| %w(--freeze -f).include?(option) } + app_path = ARGV.first require File.dirname(__FILE__) + '/../lib/rails_generator' diff --git a/railties/lib/rails_generator/base.rb b/railties/lib/rails_generator/base.rb index b5cfe79867..aa7081f8da 100644 --- a/railties/lib/rails_generator/base.rb +++ b/railties/lib/rails_generator/base.rb @@ -154,6 +154,9 @@ module Rails File.join(destination_root, relative_destination) end + def after_generate + end + protected # Convenience method for generator subclasses to record a manifest. def record diff --git a/railties/lib/rails_generator/commands.rb b/railties/lib/rails_generator/commands.rb index 6b9a636847..cacb3807d6 100644 --- a/railties/lib/rails_generator/commands.rb +++ b/railties/lib/rails_generator/commands.rb @@ -40,6 +40,7 @@ module Rails # Replay action manifest. RewindBase subclass rewinds manifest. def invoke! manifest.replay(self) + after_generate end def dependency(generator_name, args, runtime_options = {}) diff --git a/railties/lib/rails_generator/generators/applications/app/app_generator.rb b/railties/lib/rails_generator/generators/applications/app/app_generator.rb index 4bb94ff96d..4a191578cf 100644 --- a/railties/lib/rails_generator/generators/applications/app/app_generator.rb +++ b/railties/lib/rails_generator/generators/applications/app/app_generator.rb @@ -1,4 +1,5 @@ require 'rbconfig' +require File.dirname(__FILE__) + '/template_runner' require 'digest/md5' require 'active_support/secure_random' @@ -37,6 +38,12 @@ class AppGenerator < Rails::Generator::Base end end + def after_generate + if options[:template] + Rails::TemplateRunner.new(@destination_root, options[:template]) + end + end + protected def banner "Usage: #{$0} /path/to/your/app [options]" @@ -60,6 +67,11 @@ class AppGenerator < Rails::Generator::Base opt.on("-f", "--freeze", "Freeze Rails in vendor/rails from the gems generating the skeleton", "Default: false") { |v| options[:freeze] = v } + + opt.on("-m", "--template=path", String, + "Use an application template that lives at path (can be a filesystem path or URL).", + "Default: (none)") { |v| options[:template] = v } + end diff --git a/railties/lib/rails_generator/generators/applications/app/scm/git.rb b/railties/lib/rails_generator/generators/applications/app/scm/git.rb new file mode 100644 index 0000000000..445de6ab42 --- /dev/null +++ b/railties/lib/rails_generator/generators/applications/app/scm/git.rb @@ -0,0 +1,16 @@ +module Rails + class Git < Scm + def self.clone(repos, branch=nil) + `git clone #{repos}` + + if branch + `cd #{repos.split('/').last}/` + `git checkout #{branch}` + end + end + + def self.run(command) + `git #{command}` + end + end +end \ No newline at end of file diff --git a/railties/lib/rails_generator/generators/applications/app/scm/scm.rb b/railties/lib/rails_generator/generators/applications/app/scm/scm.rb new file mode 100644 index 0000000000..f6c08cad39 --- /dev/null +++ b/railties/lib/rails_generator/generators/applications/app/scm/scm.rb @@ -0,0 +1,8 @@ +module Rails + class Scm + private + def self.hash_to_parameters(hash) + hash.collect { |key, value| "--#{key} #{(value.kind_of?(String) ? value : "")}"}.join(" ") + end + end +end \ No newline at end of file diff --git a/railties/lib/rails_generator/generators/applications/app/scm/svn.rb b/railties/lib/rails_generator/generators/applications/app/scm/svn.rb new file mode 100644 index 0000000000..22b5966d25 --- /dev/null +++ b/railties/lib/rails_generator/generators/applications/app/scm/svn.rb @@ -0,0 +1,7 @@ +module Rails + class Svn < Scm + def self.checkout(repos, branch = nil) + `svn checkout #{repos}/#{branch || "trunk"}` + end + end +end \ No newline at end of file diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb new file mode 100644 index 0000000000..6f988df4bf --- /dev/null +++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb @@ -0,0 +1,376 @@ +require File.dirname(__FILE__) + '/scm/scm' +require File.dirname(__FILE__) + '/scm/git' +require File.dirname(__FILE__) + '/scm/svn' + +require 'open-uri' +require 'fileutils' + +module Rails + class TemplateRunner + attr_reader :behavior, :description, :root + + def initialize(root, template) # :nodoc: + @root = Dir.pwd + "/" + root + + puts "applying template: #{template}" + + load_template(template) + + puts "#{template} applied." + end + + def load_template(template) + begin + code = open(template).read + in_root { self.instance_eval(code) } + rescue LoadError + raise "The template [#{template}] could not be loaded." + end + end + + # Create a new file in the Rails project folder. Specify the + # relative path from RAILS_ROOT. Data is the return value of a block + # or a data string. + # + # ==== Examples + # + # file("lib/fun_party.rb") do + # hostname = ask("What is the virtual hostname I should use?") + # "vhost.name = #{hostname}" + # end + # + # file("config/apach.conf", "your apache config") + # + def file(filename, data = nil, &block) + puts "creating file #{filename}" + dir, file = [File.dirname(filename), File.basename(filename)] + + inside(dir) do + File.open(file, "w") do |f| + if block_given? + f.write(block.call) + else + f.write(data) + end + end + end + end + + # Install a plugin. You must provide either a Subversion url or Git url. + # + # ==== Examples + # + # plugin 'restful-authentication', :git => 'git://github.com/technoweenie/restful-authentication.git' + # plugin 'restful-authentication', :svn => 'svn://svnhub.com/technoweenie/restful-authentication/trunk' + # + def plugin(name, options) + puts "installing plugin #{name}" + + if options[:git] || options[:svn] + in_root do + `script/plugin install #{options[:svn] || options[:git]}` + end + else + puts "! no git or svn provided for #{name}. skipping..." + end + end + + # Adds an entry into config/environment.rb for the supplied gem : + # + # 1. Provide a git repository URL... + # + # gem 'will-paginate', :git => 'git://github.com/mislav/will_paginate.git' + # + # 2. Provide a subversion repository URL... + # + # gem 'will-paginate', :svn => 'svn://svnhub.com/mislav/will_paginate/trunk' + # + # 3. Provide a gem name and use your system sources to install and unpack it. + # + # gem 'ruby-openid' + # + def gem(name, options = {}) + puts "adding gem #{name}" + + sentinel = 'Rails::Initializer.run do |config|' + gems_code = "config.gem '#{name}'" + + if options.any? + opts = options.inject([]) {|result, h| result << [":#{h[0]} => '#{h[1]}'"] }.join(", ") + gems_code << ", #{opts}" + end + + in_root do + gsub_file 'config/environment.rb', /(#{Regexp.escape(sentinel)})/mi do |match| + "#{match}\n #{gems_code}" + end + end + end + + # Run a command in git. + # + # ==== Examples + # + # git :init + # git :add => "this.file that.rb" + # git :add => "onefile.rb", :rm => "badfile.cxx" + # + def git(command = {}) + puts "running git #{command}" + + in_root do + if command.is_a?(Symbol) + Git.run(command.to_s) + else + command.each do |command, options| + Git.run("#{command} #{options}") + end + end + end + end + + # Create a new file in the vendor/ directory. Code can be specified + # in a block or a data string can be given. + # + # ==== Examples + # + # vendor("sekrit.rb") do + # sekrit_salt = "#{Time.now}--#{3.years.ago}--#{rand}--" + # "salt = '#{sekrit_salt}'" + # end + # + # vendor("foreign.rb", "# Foreign code is fun") + # + def vendor(filename, data = nil, &block) + puts "vendoring file #{filename}" + inside("vendor") do |folder| + File.open("#{folder}/#{filename}", "w") do |f| + if block_given? + f.write(block.call) + else + f.write(data) + end + end + end + end + + # Create a new file in the lib/ directory. Code can be specified + # in a block or a data string can be given. + # + # ==== Examples + # + # lib("crypto.rb") do + # "crypted_special_value = '#{rand}--#{Time.now}--#{rand(1337)}--'" + # end + # + # lib("foreign.rb", "# Foreign code is fun") + # + def lib(filename, data = nil) + puts "add lib file #{filename}" + inside("lib") do |folder| + File.open("#{folder}/#{filename}", "w") do |f| + if block_given? + f.write(block.call) + else + f.write(data) + end + end + end + end + + # Create a new Rakefile with the provided code (either in a block or a string). + # + # ==== Examples + # + # rakefile("bootstrap.rake") do + # project = ask("What is the UNIX name of your project?") + # + # <<-TASK + # namespace :#{project} do + # task :bootstrap do + # puts "i like boots!" + # end + # end + # TASK + # end + # + # rakefile("seed.rake", "puts 'im plantin ur seedz'") + # + def rakefile(filename, data = nil, &block) + puts "adding rakefile #{filename}" + inside("lib/tasks") do |folder| + File.open("#{folder}/#{filename}", "w") do |f| + if block_given? + f.write(block.call) + else + f.write(data) + end + end + end + end + + # Create a new initializer with the provided code (either in a block or a string). + # + # ==== Examples + # + # initializer("globals.rb") do + # data = "" + # + # ['MY_WORK', 'ADMINS', 'BEST_COMPANY_EVAR'].each do + # data << "#{const} = :entp" + # end + # + # data + # end + # + # initializer("api.rb", "API_KEY = '123456'") + # + def initializer(filename, data = nil, &block) + puts "adding initializer #{filename}" + inside("config/initializers") do |folder| + File.open("#{folder}/#{filename}", "w") do |f| + if block_given? + f.write(block.call) + else + f.write(data) + end + end + end + end + + # Generate something using a generator from Rails or a plugin. + # The second parameter is the argument string that is passed to + # the generator or an Array that is joined. + # + # ==== Example + # + # generate(:authenticated, "user session") + # + def generate(what, args = nil) + puts "generating #{what}" + args = args.join(" ") if args.class == Array + + in_root { `#{root}/script/generate #{what} #{args}` } + end + + # Executes a command + # + # ==== Example + # + # inside('vendor') do + # run('ln -s ~/edge rails) + # end + # + def run(command) + puts "executing #{command} from #{Dir.pwd}" + `#{command}` + end + + # Runs the supplied rake task + # + # ==== Example + # + # rake("db:migrate") + # rake("db:migrate", "production") + # + def rake(command, env = 'development') + puts "running rake task #{command}" + in_root { `rake #{command} RAILS_ENV=#{env}` } + end + + # Just run the capify command in root + # + # ==== Example + # + # capify! + # + def capify! + in_root { `capify .` } + end + + # Add Rails to /vendor/rails + # + # ==== Example + # + # freeze! + # + def freeze!(args = {}) + puts "vendoring rails edge" + in_root { `rake rails:freeze:edge` } + end + + # Make an entry in Rails routing file conifg/routes.rb + # + # === Example + # + # route "map.root :controller => :welcome" + # + def route(routing_code) + sentinel = 'ActionController::Routing::Routes.draw do |map|' + + in_root do + gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match| + "#{match}\n #{routing_code}\n" + end + end + end + + protected + + # Get a user's input + # + # ==== Example + # + # answer = ask("Should I freeze the latest Rails?") + # freeze! if ask("Should I freeze the latest Rails?") == "yes" + # + def ask(string) + puts string + gets.strip + end + + # Do something in the root of the Rails application or + # a provided subfolder; the full path is yielded to the block you provide. + # The path is set back to the previous path when the method exits. + def inside(dir = '', &block) + folder = File.join(root, dir) + FileUtils.mkdir_p(folder) unless File.exist?(folder) + FileUtils.cd(folder) { block.arity == 1 ? yield(folder) : yield } + end + + def in_root + FileUtils.cd(root) { yield } + end + + # Helper to test if the user says yes(y)? + # + # ==== Example + # + # freeze! if yes?("Should I freeze the latest Rails?") + # + def yes?(question) + answer = ask(question).downcase + answer == "y" || answer == "yes" + end + + # Helper to test if the user does NOT say yes(y)? + # + # ==== Example + # + # capify! if no?("Will you be using vlad to deploy your application?") + # + def no?(question) + !yes?(question) + end + + def gsub_file(relative_destination, regexp, *args, &block) + path = destination_path(relative_destination) + content = File.read(path).gsub(regexp, *args, &block) + File.open(path, 'wb') { |file| file.write(content) } + end + + def destination_path(relative_destination) + File.join(root, relative_destination) + end + end +end \ No newline at end of file -- cgit v1.2.3 From be75cb8877e84e8d312402435eeb02d7ea6af600 Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Tue, 2 Dec 2008 19:48:25 +0100 Subject: Remove docs for TemplateRunner#gem as the behaviour has been changed --- .../generators/applications/app/template_runner.rb | 13 ------------- 1 file changed, 13 deletions(-) (limited to 'railties') diff --git a/railties/lib/rails_generator/generators/applications/app/template_runner.rb b/railties/lib/rails_generator/generators/applications/app/template_runner.rb index 6f988df4bf..0083e0d5a5 100644 --- a/railties/lib/rails_generator/generators/applications/app/template_runner.rb +++ b/railties/lib/rails_generator/generators/applications/app/template_runner.rb @@ -76,19 +76,6 @@ module Rails end # Adds an entry into config/environment.rb for the supplied gem : - # - # 1. Provide a git repository URL... - # - # gem 'will-paginate', :git => 'git://github.com/mislav/will_paginate.git' - # - # 2. Provide a subversion repository URL... - # - # gem 'will-paginate', :svn => 'svn://svnhub.com/mislav/will_paginate/trunk' - # - # 3. Provide a gem name and use your system sources to install and unpack it. - # - # gem 'ruby-openid' - # def gem(name, options = {}) puts "adding gem #{name}" -- cgit v1.2.3 From 0b4858cf38f522208381f9bfbbb5c066aceb30d2 Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 3 Dec 2008 10:23:58 -0600 Subject: Require rack/utils explicitly --- railties/lib/rails/rack/static.rb | 2 ++ 1 file changed, 2 insertions(+) (limited to 'railties') diff --git a/railties/lib/rails/rack/static.rb b/railties/lib/rails/rack/static.rb index 45eb0e5921..ef4e2642e2 100644 --- a/railties/lib/rails/rack/static.rb +++ b/railties/lib/rails/rack/static.rb @@ -1,3 +1,5 @@ +require 'rack/utils' + module Rails module Rack class Static -- cgit v1.2.3