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/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 +++++---- 14 files changed, 2655 insertions(+), 829 deletions(-) create mode 100644 railties/doc/guides/html/command_line.html create mode 100644 railties/doc/guides/html/configuring.html (limited to 'railties/doc/guides/html') 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)

    -- 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 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) (limited to 'railties/doc/guides/html') 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.

  • -- cgit v1.2.3