diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 43f6c1be4444e..f35c42f929b61 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -1029,10 +1029,10 @@ def default_url_options(options = nil) # # * Hash - The URL will be generated by calling url_for with the +options+. # * Record - The URL will be generated by calling url_for with the +options+, which will reference a named URL for that record. - # * String starting with protocol:// (like http://) - Is passed straight through as the target for redirection. - # * String not containing a protocol - The current protocol and host is prepended to the string. + # * String starting with protocol:// (like http://) - Is passed straight through as the target for redirection. + # * String not containing a protocol - The current protocol and host is prepended to the string. # * :back - Back to the page that issued the request. Useful for forms that are triggered from multiple places. - # Short-hand for redirect_to(request.env["HTTP_REFERER"]) + # Short-hand for redirect_to(request.env["HTTP_REFERER"]) # # Examples: # redirect_to :action => "show", :id => 5 diff --git a/railties/doc/README_FOR_APP b/railties/doc/README_FOR_APP index fe41f5cc24d66..e33b85817b4d3 100644 --- a/railties/doc/README_FOR_APP +++ b/railties/doc/README_FOR_APP @@ -1,2 +1,5 @@ -Use this README file to introduce your application and point to useful places in the API for learning more. -Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries. +To build the guides: + +* Install source-highlighter (http://www.gnu.org/software/src-highlite/source-highlight.html) +* Install the mizuho gem (http://github.com/FooBarWidget/mizuho/tree/master) +* Run `rake guides` from the railties directory \ No newline at end of file diff --git a/railties/doc/guides/html/2_2_release_notes.html b/railties/doc/guides/html/2_2_release_notes.html index 931786ef6cdb1..e79f7ec511f4f 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 @@

Chapters

  • Method Arrays for Member or Collection Routes
  • +
  • Resources With Specific Actions
  • +
  • Other Action Controller Changes
  • @@ -525,7 +527,7 @@

    5. Active Record

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

    5.6. Other ActiveRecord Changes

    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

    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.

    class AdminController < ApplicationController
     
    -  USERNAME, PASSWORD = "humbaba", "f59a4805511bf4bb61978445a5380c6c"
    +  USERNAME, PASSWORD = "humbaba", "5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"
     
       before_filter :authenticate
     
    @@ -1038,7 +1047,7 @@ 

    10. HTTP Basic Authentication

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

    11.1. Sending Files

    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 c9128a8533776..0aa507a9b94ce 100644 --- a/railties/doc/guides/html/activerecord_validations_callbacks.html +++ b/railties/doc/guides/html/activerecord_validations_callbacks.html @@ -199,10 +199,72 @@

    Sustainable productivity for web-application develop

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

      Active Record Validations and Callbacks

      -

      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 df30c46c356c4..7aa5999e1a64e 100644 --- a/railties/doc/guides/html/caching_with_rails.html +++ b/railties/doc/guides/html/caching_with_rails.html @@ -235,48 +235,54 @@

      1. Basic Caching

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

      1.1. Page Caching

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

      1.1. Page Caching

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

      1.2. Action Caching

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

      1.2. Action Caching

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

      1.3. Fragment Caching

      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:

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

      1.5. SQL Caching

      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 0000000000000..2add20446ebf1
      --- /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 0000000000000..4aa3a0f545299 --- /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 48d5f03687ba5..375d216b4ab2b 100644 --- a/railties/doc/guides/html/creating_plugins.html +++ b/railties/doc/guides/html/creating_plugins.html @@ -204,26 +204,61 @@

      Chapters

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

      Chapters

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

        Chapters

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

        1.1. Create the basic app

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

    1.2. Create the plugin

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

    1.3. Setup the plugin for testing

    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:

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

    -

    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

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

    3. Add an acts_ 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 @@ 

    5. Create a migration generator

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

    6. Add a custom generator command

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

    7. Add a Custom Route

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

    7. Add a Custom Route

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

      8.2. Generate RDoc Documentation

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

    8.4. Write custom Rake tasks in
    yaffle:squawk             # Prints out the word 'Yaffle'

    You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.

    -

    8.5. Store plugins in alternate locations

    +

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

    8.5. Store plugins in alternate l 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 @@

      9.1. References

    -

    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 95f5b39e4cf75..0653caaf7a99c 100644 --- a/railties/doc/guides/html/debugging_rails_applications.html +++ b/railties/doc/guides/html/debugging_rails_applications.html @@ -939,7 +939,7 @@

    3.9. Resuming Execution

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

    5. Plugins for Debugging

    • -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 18bc32306f36f..02c1654aa5ce7 100644 --- a/railties/doc/guides/html/finders.html +++ b/railties/doc/guides/html/finders.html @@ -198,9 +198,6 @@

      Sustainable productivity for web-application develop -

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

      4. IDs, First, Last and All

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

      4. IDs, First, Last and All

      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:

      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:

      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.males.active.all(:conditions => ["age > ?", params[:age]])
       
      +

      17.3. Runtime Evaluation of Named Scope Conditions

      Consider the following code:

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

      19. Existence of Objects

      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.

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

      3.8.4. Shallow Nesting

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

      2.3.4. ERb'in It Up

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

      2.3.5. Fixtures in Action

    -

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

    3.1. Running Tests

    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:

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

      5.2. Integration Testing Examples

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

      6.1. Keeping the Postman in Check

    -

    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.