Merge docrails changes

This commit is contained in:
Pratik Naik
2008-07-28 12:26:59 +01:00
parent 10d9fe4bf3
commit 6e75455125
52 changed files with 3183 additions and 183 deletions

View File

@@ -165,11 +165,19 @@ module ActionController
status/100 == 3
end
# Performs a GET request with the given parameters. The parameters may
# be +nil+, a Hash, or a string that is appropriately encoded
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
# The headers should be a hash. The keys will automatically be upcased, with the
# prefix 'HTTP_' added if needed.
# Performs a GET request with the given parameters.
#
# - +path+: The URI (as a String) on which you want to perform a GET request.
# - +parameters+: The HTTP parameters that you want to pass. This may be +nil+,
# a Hash, or a String that is appropriately encoded
# (<tt>application/x-www-form-urlencoded</tt> or <tt>multipart/form-data</tt>).
# - +headers+: Additional HTTP headers to pass, as a Hash. The keys will
# automatically be upcased, with the prefix 'HTTP_' added if needed.
#
# This method returns an AbstractResponse object, which one can use to inspect
# the details of the response. Furthermore, if this method was called from an
# ActionController::IntegrationTest object, then that object's <tt>@response</tt>
# instance variable will point to the same response object.
#
# You can also perform POST, PUT, DELETE, and HEAD requests with +post+,
# +put+, +delete+, and +head+.

View File

@@ -1,19 +1,61 @@
require 'digest/md5'
module ActionController
class AbstractResponse #:nodoc:
module ActionController # :nodoc:
# Represents an HTTP response generated by a controller action. One can use an
# ActionController::AbstractResponse object to retrieve the current state of the
# response, or customize the response. An AbstractResponse object can either
# represent a "real" HTTP response (i.e. one that is meant to be sent back to the
# web browser) or a test response (i.e. one that is generated from integration
# tests). See CgiResponse and TestResponse, respectively.
#
# AbstractResponse is mostly a Ruby on Rails framework implement detail, and should
# never be used directly in controllers. Controllers should use the methods defined
# in ActionController::Base instead. For example, if you want to set the HTTP
# response's content MIME type, then use ActionControllerBase#headers instead of
# AbstractResponse#headers.
#
# Nevertheless, integration tests may want to inspect controller responses in more
# detail, and that's when AbstractResponse can be useful for application developers.
# Integration test methods such as ActionController::Integration::Session#get and
# ActionController::Integration::Session#post return objects of type TestResponse
# (which are of course also of type AbstractResponse).
#
# For example, the following demo integration "test" prints the body of the
# controller response to the console:
#
# class DemoControllerTest < ActionController::IntegrationTest
# def test_print_root_path_to_console
# get('/')
# puts @response.body
# end
# end
class AbstractResponse
DEFAULT_HEADERS = { "Cache-Control" => "no-cache" }
attr_accessor :request
attr_accessor :body, :headers, :session, :cookies, :assigns, :template, :redirected_to, :redirected_to_method_params, :layout
# The body content (e.g. HTML) of the response, as a String.
attr_accessor :body
# The headers of the response, as a Hash. It maps header names to header values.
attr_accessor :headers
attr_accessor :session, :cookies, :assigns, :template, :redirected_to, :redirected_to_method_params, :layout
def initialize
@body, @headers, @session, @assigns = "", DEFAULT_HEADERS.merge("cookie" => []), [], []
end
# Sets the HTTP response's content MIME type. For example, in the controller
# you could write this:
#
# response.content_type = "text/plain"
#
# If a character set has been defined for this response (see charset=) then
# the character set information will also be included in the content type
# information.
def content_type=(mime_type)
self.headers["Content-Type"] = charset ? "#{mime_type}; charset=#{charset}" : mime_type
end
# Returns the response's content MIME type, or nil if content type has been set.
def content_type
content_type = String(headers["Content-Type"] || headers["type"]).split(";")[0]
content_type.blank? ? nil : content_type

View File

@@ -15,23 +15,61 @@ module ActionController
end
end
# Superclass for Action Controller functional tests. Infers the controller under test from the test class name,
# and creates @controller, @request, @response instance variables.
# Superclass for ActionController functional tests. Functional tests allow you to
# test a single controller action per test method. This should not be confused with
# integration tests (see ActionController::IntegrationTest), which are more like
# "stories" that can involve multiple controllers and mutliple actions (i.e. multiple
# different HTTP requests).
#
# class WidgetsControllerTest < ActionController::TestCase
# def test_index
# get :index
# == Basic example
#
# Functional tests are written as follows:
# 1. First, one uses the +get+, +post+, +put+, +delete+ or +head+ method to simulate
# an HTTP request.
# 2. Then, one asserts whether the current state is as expected. "State" can be anything:
# the controller's HTTP response, the database contents, etc.
#
# For example:
#
# class BooksControllerTest < ActionController::TestCase
# def test_create
# # Simulate a POST response with the given HTTP parameters.
# post(:create, :book => { :title => "Love Hina" })
#
# # Assert that the controller tried to redirect us to
# # the created book's URI.
# assert_response :found
#
# # Assert that the controller really put the book in the database.
# assert_not_nil Book.find_by_title("Love Hina")
# end
# end
#
# * @controller - WidgetController.new
# * @request - ActionController::TestRequest.new
# * @response - ActionController::TestResponse.new
# == Special instance variables
#
# (Earlier versions of Rails required each functional test to subclass Test::Unit::TestCase and define
# @controller, @request, @response in +setup+.)
# ActionController::TestCase will also automatically provide the following instance
# variables for use in the tests:
#
# If the controller cannot be inferred from the test class name, you can explicity set it with +tests+.
# <b>@controller</b>::
# The controller instance that will be tested.
# <b>@request</b>::
# An ActionController::TestRequest, representing the current HTTP
# request. You can modify this object before sending the HTTP request. For example,
# you might want to set some session properties before sending a GET request.
# <b>@response</b>::
# An ActionController::TestResponse object, representing the response
# of the last HTTP response. In the above example, <tt>@response</tt> becomes valid
# after calling +post+. If the various assert methods are not sufficient, then you
# may use this object to inspect the HTTP response in detail.
#
# (Earlier versions of Rails required each functional test to subclass
# Test::Unit::TestCase and define @controller, @request, @response in +setup+.)
#
# == Controller is automatically inferred
#
# ActionController::TestCase will automatically infer the controller under test
# from the test class name. If the controller cannot be inferred from the test
# class name, you can explicity set it with +tests+.
#
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
# tests WidgetController
@@ -103,4 +141,4 @@ module ActionController
@request.remote_addr = '208.77.188.166' # example.com
end
end
end
end

View File

@@ -266,7 +266,13 @@ module ActionController #:nodoc:
end
end
class TestResponse < AbstractResponse #:nodoc:
# Integration test methods such as ActionController::Integration::Session#get
# and ActionController::Integration::Session#post return objects of class
# TestResponse, which represent the HTTP response results of the requested
# controller actions.
#
# See AbstractResponse for more information on controller response objects.
class TestResponse < AbstractResponse
include TestResponseBehavior
end
@@ -348,6 +354,7 @@ module ActionController #:nodoc:
module TestProcess
def self.included(base)
# execute the request simulating a specific HTTP method and set/volley the response
# TODO: this should be un-DRY'ed for the sake of API documentation.
%w( get post put delete head ).each do |method|
base.class_eval <<-EOV, __FILE__, __LINE__
def #{method}(action, parameters = nil, session = nil, flash = nil)

View File

@@ -1,19 +1,96 @@
module ActionController
# Write URLs from arbitrary places in your codebase, such as your mailers.
# In <b>routes.rb</b> one defines URL-to-controller mappings, but the reverse
# is also possible: an URL can be generated from one of your routing definitions.
# URL generation functionality is centralized in this module.
#
# Example:
# See ActionController::Routing and ActionController::Resources for general
# information about routing and routes.rb.
#
# class MyMailer
# include ActionController::UrlWriter
# default_url_options[:host] = 'www.basecamphq.com'
# <b>Tip:</b> If you need to generate URLs from your models or some other place,
# then ActionController::UrlWriter is what you're looking for. Read on for
# an introduction.
#
# def signup_url(token)
# url_for(:controller => 'signup', action => 'index', :token => token)
# == URL generation from parameters
#
# As you may know, some functions - such as ActionController::Base#url_for
# and ActionView::Helpers::UrlHelper#link_to, can generate URLs given a set
# of parameters. For example, you've probably had the chance to write code
# like this in one of your views:
#
# <%= link_to('Click here', :controller => 'users',
# :action => 'new', :message => 'Welcome!') %>
#
# #=> Generates a link to: /users/new?message=Welcome%21
#
# link_to, and all other functions that require URL generation functionality,
# actually use ActionController::UrlWriter under the hood. And in particular,
# they use the ActionController::UrlWriter#url_for method. One can generate
# the same path as the above example by using the following code:
#
# include UrlWriter
# url_for(:controller => 'users',
# :action => 'new',
# :message => 'Welcome!',
# :only_path => true)
# # => "/users/new?message=Welcome%21"
#
# Notice the <tt>:only_path => true</tt> part. This is because UrlWriter has no
# information about the website hostname that your Rails app is serving. So if you
# want to include the hostname as well, then you must also pass the <tt>:host</tt>
# argument:
#
# include UrlWriter
# url_for(:controller => 'users',
# :action => 'new',
# :message => 'Welcome!',
# :host => 'www.example.com') # Changed this.
# # => "http://www.example.com/users/new?message=Welcome%21"
#
# By default, all controllers and views have access to a special version of url_for,
# that already knows what the current hostname is. So if you use url_for in your
# controllers or your views, then you don't need to explicitly pass the <tt>:host</tt>
# argument.
#
# For convenience reasons, mailers provide a shortcut for ActionController::UrlWriter#url_for.
# So within mailers, you only have to type 'url_for' instead of 'ActionController::UrlWriter#url_for'
# in full. However, mailers don't have hostname information, and what's why you'll still
# have to specify the <tt>:host</tt> argument when generating URLs in mailers.
#
#
# == URL generation for named routes
#
# UrlWriter also allows one to access methods that have been auto-generated from
# named routes. For example, suppose that you have a 'users' resource in your
# <b>routes.rb</b>:
#
# map.resources :users
#
# This generates, among other things, the method <tt>users_path</tt>. By default,
# this method is accessible from your controllers, views and mailers. If you need
# to access this auto-generated method from other places (such as a model), then
# you can do that in two ways.
#
# The first way is to include ActionController::UrlWriter in your class:
#
# class User < ActiveRecord::Base
# include ActionController::UrlWriter # !!!
#
# def name=(value)
# write_attribute('name', value)
# write_attribute('base_uri', users_path) # !!!
# end
# end
# end
#
# In addition to providing +url_for+, named routes are also accessible after
# including UrlWriter.
# The second way is to access them through ActionController::UrlWriter.
# The autogenerated named routes methods are available as class methods:
#
# class User < ActiveRecord::Base
# def name=(value)
# write_attribute('name', value)
# path = ActionController::UrlWriter.users_path # !!!
# write_attribute('base_uri', path) # !!!
# end
# end
module UrlWriter
# The default options for urls written by this writer. Typically a <tt>:host</tt>
# pair is provided.

View File

@@ -73,6 +73,7 @@ module ActiveRecord
end
end
# See ActiveRecord::Associations::ClassMethods for documentation.
module Associations # :nodoc:
def self.included(base)
base.extend(ClassMethods)
@@ -150,6 +151,7 @@ module ActiveRecord
# #others.destroy_all | X | X | X
# #others.find(*args) | X | X | X
# #others.find_first | X | |
# #others.exist? | X | X | X
# #others.uniq | X | X | X
# #others.reset | X | X | X
#
@@ -612,31 +614,53 @@ module ActiveRecord
# All of the association macros can be specialized through options. This makes cases more complex than the simple and guessable ones
# possible.
module ClassMethods
# Adds the following methods for retrieval and query of collections of associated objects:
# +collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.
# * <tt>collection(force_reload = false)</tt> - Returns an array of all the associated objects.
# An empty array is returned if none are found.
# * <tt>collection<<(object, ...)</tt> - Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
# * <tt>collection.delete(object, ...)</tt> - Removes one or more objects from the collection by setting their foreign keys to +NULL+.
# This will also destroy the objects if they're declared as +belongs_to+ and dependent on this model.
# * <tt>collection=objects</tt> - Replaces the collections content by deleting and adding objects as appropriate.
# * <tt>collection_singular_ids</tt> - Returns an array of the associated objects' ids
# * <tt>collection_singular_ids=ids</tt> - Replace the collection with the objects identified by the primary keys in +ids+
# * <tt>collection.clear</tt> - Removes every object from the collection. This destroys the associated objects if they
# are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the database if <tt>:dependent => :delete_all</tt>,
# otherwise sets their foreign keys to +NULL+.
# * <tt>collection.empty?</tt> - Returns +true+ if there are no associated objects.
# * <tt>collection.size</tt> - Returns the number of associated objects.
# * <tt>collection.find</tt> - Finds an associated object according to the same rules as Base.find.
# * <tt>collection.build(attributes = {}, ...)</tt> - Returns one or more new objects of the collection type that have been instantiated
# with +attributes+ and linked to this object through a foreign key, but have not yet been saved. *Note:* This only works if an
# associated object already exists, not if it's +nil+!
# * <tt>collection.create(attributes = {})</tt> - Returns a new object of the collection type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that has already been saved (if it passed the validation).
# *Note:* This only works if an associated object already exists, not if it's +nil+!
# Specifies a one-to-many association. The following methods for retrieval and query of
# collections of associated objects will be added:
#
# Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
# [collection(force_reload = false)]
# Returns an array of all the associated objects.
# An empty array is returned if none are found.
# [collection<<(object, ...)]
# Adds one or more objects to the collection by setting their foreign keys to the collection's primary key.
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
# This will also destroy the objects if they're declared as +belongs_to+ and dependent on this model.
# [collection=objects]
# Replaces the collections content by deleting and adding objects as appropriate.
# [collection_singular_ids]
# Returns an array of the associated objects' ids
# [collection_singular_ids=ids]
# Replace the collection with the objects identified by the primary keys in +ids+
# [collection.clear]
# Removes every object from the collection. This destroys the associated objects if they
# are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
# database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
# [collection.empty?]
# Returns +true+ if there are no associated objects.
# [collection.size]
# Returns the number of associated objects.
# [collection.find(...)]
# Finds an associated object according to the same rules as ActiveRecord::Base.find.
# [collection.exist?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {}, ...)]
# Returns one or more new objects of the collection type that have been instantiated
# with +attributes+ and linked to this object through a foreign key, but have not yet
# been saved. <b>Note:</b> This only works if an associated object already exists, not if
# it's +nil+!
# [collection.create(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that has already
# been saved (if it passed the validation). <b>Note:</b> This only works if an associated
# object already exists, not if it's +nil+!
#
# (*Note*: +collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_many :clients</tt> would add among others <tt>clients.empty?</tt>.)
#
# === Example
#
# A Firm class declares <tt>has_many :clients</tt>, which will add:
# * <tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions => "firm_id = #{id}"</tt>)
# * <tt>Firm#clients<<</tt>
# * <tt>Firm#clients.delete</tt>
@@ -647,54 +671,77 @@ module ActiveRecord
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
# * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
# * <tt>Firm#clients.exist?(:name => 'ACME')</tt> (similar to <tt>Client.exist?(:name => 'ACME', :firm_id => firm.id)</tt>)
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# Options are:
# * <tt>:class_name</tt> - Specify the class name of the association. Use it only if that name can't be inferred
# === Supported options
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_many :products</tt> will by default be linked to the Product class, but
# if the real class name is SpecialProduct, you'll have to specify it with this option.
# * <tt>:conditions</tt> - Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
# [:conditions]
# Specify the conditions that the associated objects must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>price > 5 AND name LIKE 'B%'</tt>. Record creations from the association are scoped if a hash
# is used. <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
# * <tt>:order</tt> - Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# * <tt>:foreign_key</tt> - Specify the foreign key used for the association. By default this is guessed to be the name
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_many+ association will use "person_id"
# as the default <tt>:foreign_key</tt>.
# * <tt>:primary_key</tt> - Specify the method that returns the primary key used for the association. By default this is +id+.
# * <tt>:dependent</tt> - If set to <tt>:destroy</tt> all the associated objects are destroyed
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:dependent]
# If set to <tt>:destroy</tt> all the associated objects are destroyed
# alongside this object by calling their +destroy+ method. If set to <tt>:delete_all</tt> all associated
# objects are deleted *without* calling their +destroy+ method. If set to <tt>:nullify</tt> all associated
# objects' foreign keys are set to +NULL+ *without* calling their +save+ callbacks. *Warning:* This option is ignored when also using
# the <tt>:through</tt> option.
# * <tt>:finder_sql</tt> - Specify a complete SQL statement to fetch the association. This is a good way to go for complex
# [:finder_sql]
# Specify a complete SQL statement to fetch the association. This is a good way to go for complex
# associations that depend on multiple tables. Note: When this option is used, +find_in_collection+ is _not_ added.
# * <tt>:counter_sql</tt> - Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
# [:counter_sql]
# Specify a complete SQL statement to fetch the size of the association. If <tt>:finder_sql</tt> is
# specified but not <tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing <tt>SELECT ... FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.
# * <tt>:extend</tt> - Specify a named module for extending the proxy. See "Association extensions".
# * <tt>:include</tt> - Specify second-order associations that should be eager loaded when the collection is loaded.
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join
# [:extend]
# Specify a named module for extending the proxy. See "Association extensions".
# [:include]
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
# An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if you, for example, want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# * <tt>:as</tt> - Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# * <tt>:through</tt> - Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:through]
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a <tt>belongs_to</tt>
# or <tt>has_many</tt> association on the join model.
# * <tt>:source</tt> - Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
# [:source]
# Specifies the source association name used by <tt>has_many :through</tt> queries. Only use it if the name cannot be
# inferred from the association. <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
# * <tt>:source_type</tt> - Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
# [:source_type]
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
# * <tt>:uniq</tt> - If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
# * <tt>:readonly</tt> - If true, all the associated objects are readonly through the association.
# * <tt>:validate</tt> - If false, don't validate the associated objects when saving the parent object. true by default.
# * <tt>:accessible</tt> - Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
#
# [:uniq]
# If true, duplicates will be omitted from the collection. Useful in conjunction with <tt>:through</tt>.
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. true by default.
# [:accessible]
# Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
# Option examples:
# has_many :comments, :order => "posted_on"
# has_many :comments, :include => :author
@@ -725,58 +772,91 @@ module ActiveRecord
end
end
# Adds the following methods for retrieval and query of a single associated object:
# +association+ is replaced with the symbol passed as the first argument, so
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.
# * <tt>association(force_reload = false)</tt> - Returns the associated object. +nil+ is returned if none is found.
# * <tt>association=(associate)</tt> - Assigns the associate object, extracts the primary key, sets it as the foreign key,
# and saves the associate object.
# * <tt>association.nil?</tt> - Returns +true+ if there is no associated object.
# * <tt>build_association(attributes = {})</tt> - Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved. Note: This ONLY works if
# an association already exists. It will NOT work if the association is +nil+.
# * <tt>create_association(attributes = {})</tt> - Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that has already been saved (if it passed the validation).
# Specifies a one-to-one association with another class. This method should only be used
# if the other class contains the foreign key. If the current class contains the foreign key,
# then you should use +belongs_to+ instead. See also ActiveRecord::Associations::ClassMethods's overview
# on when to use has_one and when to use belongs_to.
#
# Example: An Account class declares <tt>has_one :beneficiary</tt>, which will add:
# The following methods for retrieval and query of a single associated object will be added:
#
# [association(force_reload = false)]
# Returns the associated object. +nil+ is returned if none is found.
# [association=(associate)]
# Assigns the associate object, extracts the primary key, sets it as the foreign key,
# and saves the associate object.
# [association.nil?]
# Returns +true+ if there is no associated object.
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not
# yet been saved. <b>Note:</b> This ONLY works if an association already exists.
# It will NOT work if the association is +nil+.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>has_one :manager</tt> would add among others <tt>manager.nil?</tt>.)
#
# === Example
#
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
# * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first, :conditions => "account_id = #{id}")</tt>)
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
# * <tt>Account#beneficiary.nil?</tt>
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
#
# === Options
#
# The declaration can also include an options hash to specialize the behavior of the association.
#
# Options are:
# * <tt>:class_name</tt> - Specify the class name of the association. Use it only if that name can't be inferred
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_one :manager</tt> will by default be linked to the Manager class, but
# if the real class name is Person, you'll have to specify it with this option.
# * <tt>:conditions</tt> - Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>rank = 5</tt>.
# * <tt>:order</tt> - Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>.
# * <tt>:dependent</tt> - If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. If set to <tt>:nullify</tt>, the associated
# object's foreign key is set to +NULL+. Also, association is assigned.
# * <tt>:foreign_key</tt> - Specify the foreign key used for the association. By default this is guessed to be the name
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_one+ association will use "person_id"
# as the default <tt>:foreign_key</tt>.
# * <tt>:primary_key</tt> - Specify the method that returns the primary key used for the association. By default this is +id+.
# * <tt>:include</tt> - Specify second-order associations that should be eager loaded when this object is loaded.
# * <tt>:as</tt> - Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# [:primary_key]
# Specify the method that returns the primary key used for the association. By default this is +id+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
# [:as]
# Specifies a polymorphic interface (See <tt>belongs_to</tt>).
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# * <tt>:through</tt>: Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# [:through]
# Specifies a Join Model through which to perform the query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt>
# are ignored, as the association uses the source reflection. You can only use a <tt>:through</tt> query through a
# <tt>has_one</tt> or <tt>belongs_to</tt> association on the join model.
# * <tt>:source</tt> - Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be
# [:source]
# Specifies the source association name used by <tt>has_one :through</tt> queries. Only use it if the name cannot be
# inferred from the association. <tt>has_one :favorite, :through => :favorites</tt> will look for a
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
# * <tt>:source_type</tt> - Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
# [:source_type]
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
# association is a polymorphic +belongs_to+.
# * <tt>:readonly</tt> - If true, the associated object is readonly through the association.
# * <tt>:validate</tt> - If false, don't validate the associated object when saving the parent object. +false+ by default.
# * <tt>:accessible</tt> - Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
# If false, don't validate the associated object when saving the parent object. +false+ by default.
# [:accessible]
# Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
#
# Option examples:
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
@@ -816,18 +896,34 @@ module ActiveRecord
end
end
# Adds the following methods for retrieval and query for a single associated object for which this object holds an id:
# +association+ is replaced with the symbol passed as the first argument, so
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.
# * <tt>association(force_reload = false)</tt> - Returns the associated object. +nil+ is returned if none is found.
# * <tt>association=(associate)</tt> - Assigns the associate object, extracts the primary key, and sets it as the foreign key.
# * <tt>association.nil?</tt> - Returns +true+ if there is no associated object.
# * <tt>build_association(attributes = {})</tt> - Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
# * <tt>create_association(attributes = {})</tt> - Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that has already been saved (if it passed the validation).
# Specifies a one-to-one association with another class. This method should only be used
# if this class contains the foreign key. If the other class contains the foreign key,
# then you should use +has_one+ instead. See also ActiveRecord::Associations::ClassMethods's overview
# on when to use +has_one+ and when to use +belongs_to+.
#
# Example: A Post class declares <tt>belongs_to :author</tt>, which will add:
# Methods will be added for retrieval and query for a single associated object, for which
# this object holds an id:
#
# [association(force_reload = false)]
# Returns the associated object. +nil+ is returned if none is found.
# [association=(associate)]
# Assigns the associate object, extracts the primary key, and sets it as the foreign key.
# [association.nil?]
# Returns +true+ if there is no associated object.
# [build_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+ and linked to this object through a foreign key, but has not yet been saved.
# [create_association(attributes = {})]
# Returns a new object of the associated type that has been instantiated
# with +attributes+, linked to this object through a foreign key, and that
# has already been saved (if it passed the validation).
#
# (+association+ is replaced with the symbol passed as the first argument, so
# <tt>belongs_to :author</tt> would add among others <tt>author.nil?</tt>.)
#
# === Example
#
# A Post class declares <tt>belongs_to :author</tt>, which will add:
# * <tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)
# * <tt>Post#author=(author)</tt> (similar to <tt>post.author_id = author.id</tt>)
# * <tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)
@@ -836,23 +932,30 @@ module ActiveRecord
# * <tt>Post#create_author</tt> (similar to <tt>post.author = Author.new; post.author.save; post.author</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
#
# Options are:
# * <tt>:class_name</tt> - Specify the class name of the association. Use it only if that name can't be inferred
# === Options
#
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_one :author</tt> will by default be linked to the Author class, but
# if the real class name is Person, you'll have to specify it with this option.
# * <tt>:conditions</tt> - Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>.
# * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# * <tt>:foreign_key</tt> - Specify the foreign key used for the association. By default this is guessed to be the name
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt> association will use
# "person_id" as the default <tt>:foreign_key</tt>. Similarly, <tt>belongs_to :favorite_person, :class_name => "Person"</tt>
# will use a foreign key of "favorite_person_id".
# * <tt>:dependent</tt> - If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# [:dependent]
# If set to <tt>:destroy</tt>, the associated object is destroyed when this object is. If set to
# <tt>:delete</tt>, the associated object is deleted *without* calling its destroy method. This option should not be specified when
# <tt>belongs_to</tt> is used in conjunction with a <tt>has_many</tt> relationship on another class because of the potential to leave
# orphaned records behind.
# * <tt>:counter_cache</tt> - Caches the number of belonging objects on the associate class through the use of +increment_counter+
# [:counter_cache]
# Caches the number of belonging objects on the associate class through the use of +increment_counter+
# and +decrement_counter+. The counter cache is incremented when an object of this class is created and decremented when it's
# destroyed. This requires that a column named <tt>#{table_name}_count</tt> (such as +comments_count+ for a belonging Comment class)
# is used on the associate class (such as a Post class). You can also specify a custom counter cache column by providing
@@ -860,13 +963,18 @@ module ActiveRecord
# When creating a counter cache column, the database statement or migration must specify a default value of <tt>0</tt>, failing to do
# this results in a counter with +NULL+ value, which will never increment.
# Note: Specifying a counter cache will add it to that model's list of readonly attributes using +attr_readonly+.
# * <tt>:include</tt> - Specify second-order associations that should be eager loaded when this object is loaded.
# * <tt>:polymorphic</tt> - Specify this association is a polymorphic association by passing +true+.
# [:include]
# Specify second-order associations that should be eager loaded when this object is loaded.
# [:polymorphic]
# Specify this association is a polymorphic association by passing +true+.
# Note: If you've enabled the counter cache, then you may want to add the counter cache attribute
# to the +attr_readonly+ list in the associated classes (e.g. <tt>class Post; attr_readonly :comments_count; end</tt>).
# * <tt>:readonly</tt> - If true, the associated object is readonly through the association.
# * <tt>:validate</tt> - If false, don't validate the associated objects when saving the parent object. +false+ by default.
# * <tt>:accessible</tt> - Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
# [:readonly]
# If true, the associated object is readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +false+ by default.
# [:accessible]
# Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
#
# Option examples:
# belongs_to :firm, :foreign_key => "client_of"
@@ -952,8 +1060,9 @@ module ActiveRecord
configure_dependency_for_belongs_to(reflection)
end
# Associates two classes via an intermediate join table. Unless the join table is explicitly specified as
# an option, it is guessed using the lexical order of the class names. So a join between Developer and Project
# Specifies a many-to-many relationship with another class. This associates two classes via an
# intermediate join table. Unless the join table is explicitly specified as an option, it is
# guessed using the lexical order of the class names. So a join between Developer and Project
# will give the default join table name of "developers_projects" because "D" outranks "P". Note that this precedence
# is calculated using the <tt><</tt> operator for String. This means that if the strings are of different lengths,
# and the strings are equal when compared up to the shortest length, then the longer string is considered of higher
@@ -968,28 +1077,48 @@ module ActiveRecord
# associations with attributes to a real join model (see introduction).
#
# Adds the following methods for retrieval and query:
# +collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.
# * <tt>collection(force_reload = false)</tt> - Returns an array of all the associated objects.
#
# [collection(force_reload = false)]
# Returns an array of all the associated objects.
# An empty array is returned if none are found.
# * <tt>collection<<(object, ...)</tt> - Adds one or more objects to the collection by creating associations in the join table
# [collection<<(object, ...)]
# Adds one or more objects to the collection by creating associations in the join table
# (<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to this method).
# * <tt>collection.delete(object, ...)</tt> - Removes one or more objects from the collection by removing their associations from the join table.
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by removing their associations from the join table.
# This does not destroy the objects.
# * <tt>collection=objects</tt> - Replaces the collection's content by deleting and adding objects as appropriate.
# * <tt>collection_singular_ids</tt> - Returns an array of the associated objects' ids.
# * <tt>collection_singular_ids=ids</tt> - Replace the collection by the objects identified by the primary keys in +ids+.
# * <tt>collection.clear</tt> - Removes every object from the collection. This does not destroy the objects.
# * <tt>collection.empty?</tt> - Returns +true+ if there are no associated objects.
# * <tt>collection.size</tt> - Returns the number of associated objects.
# * <tt>collection.find(id)</tt> - Finds an associated object responding to the +id+ and that
# [collection=objects]
# Replaces the collection's content by deleting and adding objects as appropriate.
# [collection_singular_ids]
# Returns an array of the associated objects' ids.
# [collection_singular_ids=ids]
# Replace the collection by the objects identified by the primary keys in +ids+.
# [collection.clear]
# Removes every object from the collection. This does not destroy the objects.
# [collection.empty?]
# Returns +true+ if there are no associated objects.
# [collection.size]
# Returns the number of associated objects.
# [collection.find(id)]
# Finds an associated object responding to the +id+ and that
# meets the condition that it has to be associated with this object.
# * <tt>collection.build(attributes = {})</tt> - Returns a new object of the collection type that has been instantiated
# Uses the same rules as ActiveRecord::Base.find.
# [collection.exist?(...)]
# Checks whether an associated object with the given conditions exists.
# Uses the same rules as ActiveRecord::Base.exists?.
# [collection.build(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+ and linked to this object through the join table, but has not yet been saved.
# * <tt>collection.create(attributes = {})</tt> - Returns a new object of the collection type that has been instantiated
# [collection.create(attributes = {})]
# Returns a new object of the collection type that has been instantiated
# with +attributes+, linked to this object through the join table, and that has already been saved (if it passed the validation).
#
# Example: A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
# (+collection+ is replaced with the symbol passed as the first argument, so
# <tt>has_and_belongs_to_many :categories</tt> would add among others <tt>categories.empty?</tt>.)
#
# === Example
#
# A Developer class declares <tt>has_and_belongs_to_many :projects</tt>, which will add:
# * <tt>Developer#projects</tt>
# * <tt>Developer#projects<<</tt>
# * <tt>Developer#projects.delete</tt>
@@ -1000,45 +1129,66 @@ module ActiveRecord
# * <tt>Developer#projects.empty?</tt>
# * <tt>Developer#projects.size</tt>
# * <tt>Developer#projects.find(id)</tt>
# * <tt>Developer#clients.exist?(...)</tt>
# * <tt>Developer#projects.build</tt> (similar to <tt>Project.new("project_id" => id)</tt>)
# * <tt>Developer#projects.create</tt> (similar to <tt>c = Project.new("project_id" => id); c.save; c</tt>)
# The declaration may include an options hash to specialize the behavior of the association.
#
# Options are:
# * <tt>:class_name</tt> - Specify the class name of the association. Use it only if that name can't be inferred
# === Options
#
# [:class_name]
# Specify the class name of the association. Use it only if that name can't be inferred
# from the association name. So <tt>has_and_belongs_to_many :projects</tt> will by default be linked to the
# Project class, but if the real class name is SuperProject, you'll have to specify it with this option.
# * <tt>:join_table</tt> - Specify the name of the join table if the default based on lexical order isn't what you want.
# WARNING: If you're overwriting the table name of either class, the +table_name+ method MUST be declared underneath any
# +has_and_belongs_to_many+ declaration in order to work.
# * <tt>:foreign_key</tt> - Specify the foreign key used for the association. By default this is guessed to be the name
# [:join_table]
# Specify the name of the join table if the default based on lexical order isn't what you want.
# <b>WARNING:</b> If you're overwriting the table name of either class, the +table_name+ method
# MUST be declared underneath any +has_and_belongs_to_many+ declaration in order to work.
# [:foreign_key]
# Specify the foreign key used for the association. By default this is guessed to be the name
# of this class in lower-case and "_id" suffixed. So a Person class that makes a +has_and_belongs_to_many+ association
# will use "person_id" as the default <tt>:foreign_key</tt>.
# * <tt>:association_foreign_key</tt> - Specify the association foreign key used for the association. By default this is
# [:association_foreign_key]
# Specify the association foreign key used for the association. By default this is
# guessed to be the name of the associated class in lower-case and "_id" suffixed. So if the associated class is Project,
# the +has_and_belongs_to_many+ association will use "project_id" as the default <tt>:association_foreign_key</tt>.
# * <tt>:conditions</tt> - Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# [:conditions]
# Specify the conditions that the associated object must meet in order to be included as a +WHERE+
# SQL fragment, such as <tt>authorized = 1</tt>. Record creations from the association are scoped if a hash is used.
# <tt>has_many :posts, :conditions => {:published => true}</tt> will create published posts with <tt>@blog.posts.create</tt>
# or <tt>@blog.posts.build</tt>.
# * <tt>:order</tt> - Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# [:order]
# Specify the order in which the associated objects are returned as an <tt>ORDER BY</tt> SQL fragment,
# such as <tt>last_name, first_name DESC</tt>
# * <tt>:uniq</tt> - If true, duplicate associated objects will be ignored by accessors and query methods.
# * <tt>:finder_sql</tt> - Overwrite the default generated SQL statement used to fetch the association with a manual statement
# * <tt>:delete_sql</tt> - Overwrite the default generated SQL statement used to remove links between the associated
# [:uniq]
# If true, duplicate associated objects will be ignored by accessors and query methods.
# [:finder_sql]
# Overwrite the default generated SQL statement used to fetch the association with a manual statement
# [:delete_sql]
# Overwrite the default generated SQL statement used to remove links between the associated
# classes with a manual statement.
# * <tt>:insert_sql</tt> - Overwrite the default generated SQL statement used to add links between the associated classes
# [:insert_sql]
# Overwrite the default generated SQL statement used to add links between the associated classes
# with a manual statement.
# * <tt>:extend</tt> - Anonymous module for extending the proxy, see "Association extensions".
# * <tt>:include</tt> - Specify second-order associations that should be eager loaded when the collection is loaded.
# * <tt>:group</tt> - An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# * <tt>:limit</tt> - An integer determining the limit on the number of rows that should be returned.
# * <tt>:offset</tt> - An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# * <tt>:select</tt> - By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# [:extend]
# Anonymous module for extending the proxy, see "Association extensions".
# [:include]
# Specify second-order associations that should be eager loaded when the collection is loaded.
# [:group]
# An attribute name by which the result should be grouped. Uses the <tt>GROUP BY</tt> SQL-clause.
# [:limit]
# An integer determining the limit on the number of rows that should be returned.
# [:offset]
# An integer determining the offset from where the rows should be fetched. So at 5, it would skip the first 4 rows.
# [:select]
# By default, this is <tt>*</tt> as in <tt>SELECT * FROM</tt>, but can be changed if, for example, you want to do a join
# but not include the joined columns. Do not forget to include the primary and foreign keys, otherwise it will raise an error.
# * <tt>:readonly</tt> - If true, all the associated objects are readonly through the association.
# * <tt>:validate</tt> - If false, don't validate the associated objects when saving the parent object. +true+ by default.
# * <tt>:accessible</tt> - Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
# [:readonly]
# If true, all the associated objects are readonly through the association.
# [:validate]
# If false, don't validate the associated objects when saving the parent object. +true+ by default.
# [:accessible<]
# Mass assignment is allowed for this assocation (similar to <tt>ActiveRecord::Base#attr_accessible</tt>).
#
# Option examples:
# has_and_belongs_to_many :projects

View File

@@ -83,8 +83,33 @@ module ActiveRecord #:nodoc:
class ReadOnlyRecord < ActiveRecordError
end
# Used by Active Record transaction mechanism to distinguish rollback from other exceptional situations.
# You can use it to roll your transaction back explicitly in the block passed to +transaction+ method.
# ActiveRecord::Transactions::ClassMethods.transaction uses this exception
# to distinguish a deliberate rollback from other exceptional situations.
# Normally, raising an exception will cause the +transaction+ method to rollback
# the database transaction *and* pass on the exception. But if you raise an
# ActiveRecord::Rollback exception, then the database transaction will be rolled back,
# without passing on the exception.
#
# For example, you could do this in your controller to rollback a transaction:
#
# class BooksController < ActionController::Base
# def create
# Book.transaction do
# book = Book.new(params[:book])
# book.save!
# if today_is_friday?
# # The system must fail on Friday so that our support department
# # won't be out of job. We silently rollback this transaction
# # without telling the user.
# raise ActiveRecord::Rollback, "Call tech support!"
# end
# end
# # ActiveRecord::Rollback is the only exception that won't be passed on
# # by ActiveRecord::Base.transaction, so this line will still be reached
# # even on Friday.
# redirect_to root_url
# end
# end
class Rollback < ActiveRecordError
end

View File

@@ -66,12 +66,15 @@ module ActiveRecord
# will happen under the protected cover of a transaction. So you can use validations to check for values that the transaction
# depends on or you can raise exceptions in the callbacks to rollback.
#
# == Exception handling
# == Exception handling and rolling back
#
# Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you
# should be ready to catch those in your application code. One exception is the ActiveRecord::Rollback exception, which will
# trigger a ROLLBACK when raised, but not be re-raised by the transaction block.
# should be ready to catch those in your application code.
#
# One exception is the ActiveRecord::Rollback exception, which will trigger a ROLLBACK when raised,
# but not be re-raised by the transaction block.
module ClassMethods
# See ActiveRecord::Transactions::ClassMethods for detailed documentation.
def transaction(&block)
connection.increment_open_transactions

View File

@@ -8,6 +8,7 @@ module ActiveSupport #:nodoc:
# %w( a b c d ).from(0) # => %w( a b c d )
# %w( a b c d ).from(2) # => %w( c d )
# %w( a b c d ).from(10) # => nil
# %w().from(0) # => nil
def from(position)
self[position..-1]
end
@@ -17,51 +18,52 @@ module ActiveSupport #:nodoc:
# %w( a b c d ).to(0) # => %w( a )
# %w( a b c d ).to(2) # => %w( a b c )
# %w( a b c d ).to(10) # => %w( a b c d )
# %w().to(0) # => %w()
def to(position)
self[0..position]
end
# Equal to self[1]
# Equals to <tt>self[1]</tt>.
def second
self[1]
end
# Equal to self[2]
# Equals to <tt>self[2]</tt>.
def third
self[2]
end
# Equal to self[3]
# Equals to <tt>self[3]</tt>.
def fourth
self[3]
end
# Equal to self[4]
# Equals to <tt>self[4]</tt>.
def fifth
self[4]
end
# Equal to self[5]
# Equals to <tt>self[5]</tt>.
def sixth
self[5]
end
# Equal to self[6]
# Equals to <tt>self[6]</tt>.
def seventh
self[6]
end
# Equal to self[7]
# Equals to <tt>self[7]</tt>.
def eighth
self[7]
end
# Equal to self[8]
# Equals to <tt>self[8]</tt>.
def ninth
self[8]
end
# Equal to self[9]
# Equals to <tt>self[9]</tt>.
def tenth
self[9]
end

View File

@@ -30,6 +30,7 @@ module ActiveSupport #:nodoc:
# time.to_s(:time) # => "06:10:17"
#
# time.to_formatted_s(:db) # => "2007-01-18 06:10:17"
# time.to_formatted_s(:number) # => "20070118061017"
# time.to_formatted_s(:short) # => "18 Jan 06:10"
# time.to_formatted_s(:long) # => "January 18, 2007 06:10"
# time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10"

View File

@@ -272,6 +272,21 @@ Rake::RDocTask.new { |rdoc|
rdoc.rdoc_files.include('lib/commands/**/*.rb')
}
guides = ['securing_rails_applications', 'testing_rails_applications', 'creating_plugins']
guides_html_files = []
guides.each do |guide_name|
input = "doc/guides/#{guide_name}/#{guide_name}.txt"
output = "doc/guides/#{guide_name}/#{guide_name}.html"
guides_html_files << output
file output => Dir["doc/guides/#{guide_name}/*.txt"] do
sh "mizuho", input, "--template", "manualsonrails", "--multi-page",
"--icons-dir", "../icons"
end
end
desc "Generate HTML output for the guides"
task :generate_guides => guides_html_files
# Generate GEM ----------------------------------------------------------------------------
task :copy_gem_environment do

View File

@@ -0,0 +1,193 @@
== Add an `acts_as_yaffle` method to ActiveRecord ==
A common pattern in plugins is to add a method called `acts_as_something` to models. In this case, you want to write a method called `acts_as_yaffle` that adds a `squawk` method to your models.
To keep things clean, create a new test file called 'acts_as_yaffle_test.rb' in your plugin's test directory and require your test helper.
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class ActsAsYaffleTest < Test::Unit::TestCase
end
------------------------------------------------------
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/lib/acts_as_yaffle.rb
module Yaffle
end
------------------------------------------------------
One of the most common plugin patterns for `acts_as_yaffle` plugins is to structure your file like so:
[source, ruby]
------------------------------------------------------
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
# any method placed here will apply to classes, like Hickwall
def acts_as_something
send :include, InstanceMethods
end
end
module InstanceMethods
# any method placed here will apply to instaces, like @hickwall
end
end
------------------------------------------------------
With structure you can easily separate the methods that will be used for the class (like `Hickwall.some_method`) and the instance (like `@hickwell.some_method`).
Let's add class method named `acts_as_yaffle` - testing it out first. You already defined the ActiveRecord models in your test helper, so if you run tests now they will fail.
Back in your `acts_as_yaffle` file, update ClassMethods like so:
[source, ruby]
------------------------------------------------------
module ClassMethods
def acts_as_yaffle(options = {})
send :include, InstanceMethods
end
end
------------------------------------------------------
Now that test should pass. Since your plugin is going to work with field names, you need to allow people to define the field names, in case there is a naming conflict. You can write a few simple tests for this:
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_tweet
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_tweeted_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
end
------------------------------------------------------
To make these tests pass, you could modify your `acts_as_yaffle` file like so:
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
end
end
------------------------------------------------------
Now you can add tests for the instance methods, and the instance method itself:
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/test/acts_as_yaffle_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
class ActsAsYaffleTest < Test::Unit::TestCase
def test_a_hickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_squawk", Hickwall.yaffle_text_field
end
def test_a_hickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_squawked_at", Hickwall.yaffle_date_field
end
def test_a_wickwalls_yaffle_text_field_should_be_last_squawk
assert_equal "last_tweet", Wickwall.yaffle_text_field
end
def test_a_wickwalls_yaffle_date_field_should_be_last_squawked_at
assert_equal "last_tweeted_at", Wickwall.yaffle_date_field
end
def test_hickwalls_squawk_should_populate_last_squawk
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal "squawk! Hello World", hickwall.last_squawk
end
def test_hickwalls_squawk_should_populate_last_squawked_at
hickwall = Hickwall.new
hickwall.squawk("Hello World")
assert_equal Date.today, hickwall.last_squawked_at
end
def test_wickwalls_squawk_should_populate_last_tweet
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal "squawk! Hello World", wickwall.last_tweet
end
def test_wickwalls_squawk_should_populate_last_tweeted_at
wickwall = Wickwall.new
wickwall.squawk("Hello World")
assert_equal Date.today, wickwall.last_tweeted_at
end
end
------------------------------------------------------
[source, ruby]
------------------------------------------------------
# File: vendor/plugins/yaffle/lib/acts_as_yaffle.rb
module Yaffle
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def acts_as_yaffle(options = {})
cattr_accessor :yaffle_text_field, :yaffle_date_field
self.yaffle_text_field = (options[:yaffle_text_field] || :last_squawk).to_s
self.yaffle_date_field = (options[:yaffle_date_field] || :last_squawked_at).to_s
send :include, InstanceMethods
end
end
module InstanceMethods
def squawk(string)
write_attribute(self.class.yaffle_text_field, string.to_squawk)
write_attribute(self.class.yaffle_date_field, Date.today)
end
end
end
------------------------------------------------------
Note the use of `write_attribute` to write to the field in model.

View File

@@ -0,0 +1,46 @@
== Appendix ==
=== References ===
* http://nubyonrails.com/articles/the-complete-guide-to-rails-plugins-part-i
* http://nubyonrails.com/articles/2006/05/09/the-complete-guide-to-rails-plugins-part-ii
* http://github.com/technoweenie/attachment_fu/tree/master
* http://daddy.platte.name/2007/05/rails-plugins-keep-initrb-thin.html
=== Final plugin directory structure ===
The final plugin should have a directory structure that looks something like this:
------------------------------------------------
|-- MIT-LICENSE
|-- README
|-- Rakefile
|-- generators
| `-- yaffle
| |-- USAGE
| |-- templates
| | `-- definition.txt
| `-- yaffle_generator.rb
|-- init.rb
|-- install.rb
|-- lib
| |-- acts_as_yaffle.rb
| |-- commands.rb
| |-- core_ext.rb
| |-- routing.rb
| `-- view_helpers.rb
|-- tasks
| `-- yaffle_tasks.rake
|-- test
| |-- acts_as_yaffle_test.rb
| |-- core_ext_test.rb
| |-- database.yml
| |-- debug.log
| |-- routing_test.rb
| |-- schema.rb
| |-- test_helper.rb
| `-- view_helpers_test.rb
|-- uninstall.rb
`-- yaffle_plugin.sqlite3.db
------------------------------------------------

View File

@@ -0,0 +1,84 @@
The Basics of Creating Rails Plugins
====================================
Pretend for a moment that you are an avid bird watcher. Your favorite bird is the Yaffle, and you want to create a plugin that allows other developers to share in the Yaffle goodness.
In this tutorial you will learn how to create a plugin that includes:
* Core Extensions - extending String with a `to_squawk` method:
+
[source, ruby]
-------------------------------------------
# Anywhere
"hello!".to_squawk # => "squawk! hello!"
-------------------------------------------
* An `acts_as_yaffle` method for ActiveRecord models that adds a `squawk` method:
+
[source, ruby]
-------------------------------------------
class Hickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_sang_at
end
Hickwall.new.squawk("Hello World")
-------------------------------------------
* A view helper that will print out squawking info:
+
[source, ruby]
-------------------------------------------
squawk_info_for(@hickwall)
-------------------------------------------
* A generator that creates a migration to add squawk columns to a model:
+
-------------------------------------------
script/generate yaffle hickwall
-------------------------------------------
* A custom generator command:
+
[source, ruby]
-------------------------------------------
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
-------------------------------------------
* A custom route method:
+
[source, ruby]
-------------------------------------------
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
-------------------------------------------
In addition you'll learn how to:
* test your plugins.
* work with 'init.rb', how to store model, views, controllers, helpers and even other plugins in your plugins.
* create documentation for your plugin.
* write custom Rake tasks in your plugin.
include::preparation.txt[]
include::string_to_squawk.txt[]
include::acts_as_yaffle.txt[]
include::view_helper.txt[]
include::migration_generator.txt[]
include::custom_generator.txt[]
include::custom_route.txt[]
include::odds_and_ends.txt[]
include::appendix.txt[]

View File

@@ -0,0 +1,69 @@
== Add a custom generator command ==
You may have noticed above that you can used one of the built-in rails migration commands `m.migration_template`. You can create your own commands for these, using the following steps:
1. Add the require and hook statements to init.rb.
2. Create the commands - creating 3 sets, Create, Destroy, List.
3. Add the method to your generator.
Working with the internals of generators is beyond the scope of this tutorial, but here is a basic example:
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "commands"
Rails::Generator::Commands::Create.send :include, Yaffle::Generator::Commands::Create
Rails::Generator::Commands::Destroy.send :include, Yaffle::Generator::Commands::Destroy
Rails::Generator::Commands::List.send :include, Yaffle::Generator::Commands::List
-----------------------------------------------------------
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/lib/commands.rb
require 'rails_generator'
require 'rails_generator/commands'
module Yaffle #:nodoc:
module Generator #:nodoc:
module Commands #:nodoc:
module Create
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
module Destroy
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
module List
def yaffle_definition
file("definition.txt", "definition.txt")
end
end
end
end
end
-----------------------------------------------------------
-----------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/templates/definition.txt
Yaffle is a bird
-----------------------------------------------------------
[source, ruby]
-----------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
m.yaffle_definition
end
end
-----------------------------------------------------------
This example just uses the built-in "file" method, but you could do anything that Ruby allows.

View File

@@ -0,0 +1,69 @@
== 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.
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/routing_test.rb
require "#{File.dirname(__FILE__)}/test_helper"
class RoutingTest < Test::Unit::TestCase
def setup
ActionController::Routing::Routes.draw do |map|
map.yaffles
end
end
def test_yaffles_route
assert_recognition :get, "/yaffles", :controller => "yaffles_controller", :action => "index"
end
private
# yes, I know about assert_recognizes, but it has proven problematic to
# use in these tests, since it uses RouteSet#recognize (which actually
# tries to instantiate the controller) and because it uses an awkward
# parameter order.
def assert_recognition(method, path, options)
result = ActionController::Routing::Routes.recognize_path(path, :method => method)
assert_equal options, result
end
end
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "routing"
ActionController::Routing::RouteSet::Mapper.send :include, Yaffle::Routing::MapperExtensions
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/lib/routing.rb
module Yaffle #:nodoc:
module Routing #:nodoc:
module MapperExtensions
def yaffles
@set.add_route("/yaffles", {:controller => "yaffles_controller", :action => "index"})
end
end
end
end
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: config/routes.rb
ActionController::Routing::Routes.draw do |map|
...
map.yaffles
end
--------------------------------------------------------
You can also see if your routes work by running `rake routes` from your app directory.

View File

@@ -0,0 +1,89 @@
== Create a migration generator ==
When you created the plugin above, you specified the --with-generator option, so you already have the generator stubs in your plugin.
We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.
Type:
script/generate
You should see the line:
Plugins (vendor/plugins): yaffle
When you run `script/generate yaffle` you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:
------------------------------------------------------------------
Description:
Creates a migration that adds yaffle squawk fields to the given model
Example:
./script/generate yaffle hickwall
This will create:
db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall
------------------------------------------------------------------
Now you can add code to your generator:
[source, ruby]
------------------------------------------------------------------
# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
class YaffleGenerator < Rails::Generator::NamedBase
def manifest
record do |m|
m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
:migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
}
end
end
private
def custom_file_name
custom_name = class_name.underscore.downcase
custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
end
def yaffle_local_assigns
returning(assigns = {}) do
assigns[:migration_action] = "add"
assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
assigns[:table_name] = custom_file_name
assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
end
end
end
------------------------------------------------------------------
Note that you need to be aware of whether or not table names are pluralized.
This does a few things:
* Reuses the built in rails `migration_template` method.
* Reuses the built-in rails migration template.
When you run the generator like
script/generate yaffle bird
You will see a new file:
[source, ruby]
------------------------------------------------------------------
# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb
class AddYaffleFieldsToBirds < ActiveRecord::Migration
def self.up
add_column :birds, :last_squawk, :string
add_column :birds, :last_squawked_at, :datetime
end
def self.down
remove_column :birds, :last_squawked_at
remove_column :birds, :last_squawk
end
end
------------------------------------------------------------------

View File

@@ -0,0 +1,122 @@
== Odds and ends ==
=== Work with init.rb ===
The plugin initializer script 'init.rb' is invoked via `eval` (not `require`) so it has slightly different behavior.
If you reopen any classes in init.rb itself your changes will potentially be made to the wrong module. There are 2 ways around this:
The first way is to explicitly define the top-level module space for all modules and classes, like `::Hash`:
[source, ruby]
---------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
class ::Hash
def is_a_special_hash?
true
end
end
---------------------------------------------------
OR you can use `module_eval` or `class_eval`:
---------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
Hash.class_eval do
def is_a_special_hash?
true
end
end
---------------------------------------------------
=== Generate RDoc Documentation ===
Once your plugin is stable, the tests pass on all database and you are ready to deploy do everyone else a favor and document it! Luckily, writing documentation for your plugin is easy.
The first step is to update the README file with detailed information about how to use your plugin. A few key things to include are:
* Your name.
* How to install.
* How to add the functionality to the app (several examples of common use cases).
* Warning, gotchas or tips that might help save users time.
Once your README is solid, go through and add rdoc comments to all of the methods that developers will use.
Before you generate your documentation, be sure to go through and add nodoc comments to those modules and methods that are not important to your users.
Once your comments are good to go, navigate to your plugin directory and run:
rake rdoc
=== Store models, views, helpers, and controllers in your plugins ===
You can easily store models, views, helpers and controllers in plugins. Just create a folder for each in the lib folder, add them to the load path and remove them from the load once path:
[source, ruby]
---------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
%w{ models controllers helpers }.each do |dir|
path = File.join(directory, 'lib', dir)
$LOAD_PATH << path
Dependencies.load_paths << path
Dependencies.load_once_paths.delete(path)
end
---------------------------------------------------------
Adding directories to the load path makes them appear just like files in the the main app directory - except that they are only loaded once, so you have to restart the web server to see the changes in the browser.
Adding directories to the load once paths allow those changes to picked up as soon as you save the file - without having to restart the web server.
=== Write custom Rake tasks in your plugin ===
When you created the plugin with the built-in rails generator, it generated a rake file for you in 'vendor/plugins/yaffle/tasks/yaffle.rake'. Any rake task you add here will be available to the app.
Many plugin authors put all of their rake tasks into a common namespace that is the same as the plugin, like so:
[source, ruby]
---------------------------------------------------------
# File: vendor/plugins/yaffle/tasks/yaffle.rake
namespace :yaffle do
desc "Prints out the word 'Yaffle'"
task :squawk => :environment do
puts "squawk!"
end
end
---------------------------------------------------------
When you run `rake -T` from your plugin you will see:
---------------------------------------------------------
yaffle:squawk # Prints out the word 'Yaffle'
---------------------------------------------------------
You can add as many files as you want in the tasks directory, and if they end in .rake Rails will pick them up.
=== Store plugins in alternate locations ===
You can store plugins wherever you want - you just have to add those plugins to the plugins path in 'environment.rb'.
Since the plugin is only loaded after the plugin paths are defined, you can't redefine this in your plugins - but it may be good to now.
You can even store plugins inside of other plugins for complete plugin madness!
[source, ruby]
---------------------------------------------------------
config.plugin_paths << File.join(RAILS_ROOT,"vendor","plugins","yaffle","lib","plugins")
---------------------------------------------------------
=== Create your own Plugin Loaders and Plugin Locators ===
If the built-in plugin behavior is inadequate, you can change almost every aspect of the location and loading process. You can write your own plugin locators and plugin loaders, but that's beyond the scope of this tutorial.
=== Use Custom Plugin Generators ===
If you are an RSpec fan, you can install the `rspec_plugin_generator` gem, which will generate the spec folder and database for you. See http://github.com/pat-maddox/rspec-plugin-generator/tree/master.

View File

@@ -0,0 +1,169 @@
== Preparation ==
=== Create the basic app ===
In this tutorial we will create a basic rails application with 1 resource: bird. Start out by building the basic rails app:
------------------------------------------------
rails plugin_demo
cd plugin_demo
script/generate scaffold bird name:string
rake db:migrate
script/server
------------------------------------------------
Then navigate to http://localhost:3000/birds. Make sure you have a functioning rails app before continuing.
NOTE: The aforementioned instructions will work for sqlite3. For more detailed instructions on how to create a rails app for other databases see the API docs.
=== Create the plugin ===
The built-in Rails plugin generator stubs out a new plugin. Pass the plugin name, either 'CamelCased' or 'under_scored', as an argument. Pass `\--with-generator` to add an example generator also.
This creates a plugin in 'vendor/plugins' including an 'init.rb' and 'README' as well as standard 'lib', 'task', and 'test' directories.
Examples:
----------------------------------------------
./script/generate plugin BrowserFilters
./script/generate plugin BrowserFilters --with-generator
----------------------------------------------
Later in the plugin we will create a generator, so go ahead and add the `\--with-generator` option now:
----------------------------------------------
script/generate plugin yaffle --with-generator
----------------------------------------------
You should see the following output:
----------------------------------------------
create vendor/plugins/yaffle/lib
create vendor/plugins/yaffle/tasks
create vendor/plugins/yaffle/test
create vendor/plugins/yaffle/README
create vendor/plugins/yaffle/MIT-LICENSE
create vendor/plugins/yaffle/Rakefile
create vendor/plugins/yaffle/init.rb
create vendor/plugins/yaffle/install.rb
create vendor/plugins/yaffle/uninstall.rb
create vendor/plugins/yaffle/lib/yaffle.rb
create vendor/plugins/yaffle/tasks/yaffle_tasks.rake
create vendor/plugins/yaffle/test/core_ext_test.rb
create vendor/plugins/yaffle/generators
create vendor/plugins/yaffle/generators/yaffle
create vendor/plugins/yaffle/generators/yaffle/templates
create vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb
create vendor/plugins/yaffle/generators/yaffle/USAGE
----------------------------------------------
For this plugin you won't need the file 'vendor/plugins/yaffle/lib/yaffle.rb' so you can delete that.
----------------------------------------------
rm vendor/plugins/yaffle/lib/yaffle.rb
----------------------------------------------
.Editor's note:
NOTE: Many plugin authors prefer to keep this file, and add all of the require statements in it. That way, they only line in init.rb would be `require "yaffle"`. If you are developing a plugin that has a lot of files in the lib directory, you may want to create a subdirectory like lib/yaffle and store your files in there. That way your init.rb file stays clean
=== Setup the plugin for testing ===
Testing plugins that use the entire Rails stack can be complex, and the generator doesn't offer any help. In this tutorial you will learn how to test your plugin against multiple different adapters using ActiveRecord. This tutorial will not cover how to use fixtures in plugin tests.
To setup your plugin to allow for easy testing you'll need to add 3 files:
* A 'database.yml' file with all of your connection strings.
* A 'schema.rb' file with your table definitions.
* A test helper that sets up the database before your tests.
For this plugin you'll need 2 tables/models, Hickwalls and Wickwalls, so add the following files:
*vendor/plugins/yaffle/test/database.yml:*
----------------------------------------------
sqlite:
:adapter: sqlite
:dbfile: yaffle_plugin.sqlite.db
sqlite3:
:adapter: sqlite3
:dbfile: yaffle_plugin.sqlite3.db
postgresql:
:adapter: postgresql
:username: postgres
:password: postgres
:database: yaffle_plugin_test
:min_messages: ERROR
mysql:
:adapter: mysql
:host: localhost
:username: rails
:password:
:database: yaffle_plugin_test
----------------------------------------------
*vendor/plugins/yaffle/test/test_helper.rb:*
[source, ruby]
----------------------------------------------
ActiveRecord::Schema.define(:version => 0) do
create_table :hickwalls, :force => true do |t|
t.string :name
t.string :last_squawk
t.datetime :last_squawked_at
end
create_table :wickwalls, :force => true do |t|
t.string :name
t.string :last_tweet
t.datetime :last_tweeted_at
end
end
# File: vendor/plugins/yaffle/test/test_helper.rb
ENV['RAILS_ENV'] = 'test'
ENV['RAILS_ROOT'] ||= File.dirname(__FILE__) + '/../../../..'
require 'test/unit'
require File.expand_path(File.join(ENV['RAILS_ROOT'], 'config/environment.rb'))
config = YAML::load(IO.read(File.dirname(__FILE__) + '/database.yml'))
ActiveRecord::Base.logger = Logger.new(File.dirname(__FILE__) + "/debug.log")
db_adapter = ENV['DB']
# no db passed, try one of these fine config-free DBs before bombing.
db_adapter ||=
begin
require 'rubygems'
require 'sqlite'
'sqlite'
rescue MissingSourceFile
begin
require 'sqlite3'
'sqlite3'
rescue MissingSourceFile
end
end
if db_adapter.nil?
raise "No DB Adapter selected. Pass the DB= option to pick one, or install Sqlite or Sqlite3."
end
ActiveRecord::Base.establish_connection(config[db_adapter])
load(File.dirname(__FILE__) + "/schema.rb")
require File.dirname(__FILE__) + '/../init.rb'
class Hickwall < ActiveRecord::Base
acts_as_yaffle
end
class Wickwall < ActiveRecord::Base
acts_as_yaffle :yaffle_text_field => :last_tweet, :yaffle_date_field => :last_tweeted_at
end
----------------------------------------------

View File

@@ -0,0 +1,103 @@
== Add a `to_squawk` method to String ==
To update a core class you will have to:
* Write tests for the desired functionality.
* Create a file for the code you wish to use.
* Require that file from your 'init.rb'.
Most plugins store their code classes in the plugin's lib directory. When you add a file to the lib directory, you must also require that file from 'init.rb'. The file you are going to add for this tutorial is 'lib/core_ext.rb'.
First, you need to write the tests. Testing plugins is very similar to testing rails apps. The generated test file should look something like this:
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
class CoreExtTest < Test::Unit::TestCase
# Replace this with your real tests.
def test_this_plugin
flunk
end
end
--------------------------------------------------------
Start off by removing the default test, and adding a require statement for your test helper.
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/test/core_ext_test.rb
require 'test/unit'
require File.dirname(__FILE__) + '/test_helper.rb'
class CoreExtTest < Test::Unit::TestCase
end
--------------------------------------------------------
Navigate to your plugin directory and run `rake test`:
--------------------------------------------------------
cd vendor/plugins/yaffle
rake test
--------------------------------------------------------
Your test should fail with `no such file to load -- ./test/../lib/core_ext.rb (LoadError)` because we haven't created any file yet. Create the file 'lib/core_ext.rb' and re-run the tests. You should see a different error message:
--------------------------------------------------------
1.) Failure ...
No tests were specified
--------------------------------------------------------
Great - now you are ready to start development. The first thing we'll do is to add a method to String called `to_squawk` which will prefix the string with the word ``squawk!''. The test will look something like this:
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
class CoreExtTest < Test::Unit::TestCase
def test_string_should_respond_to_squawk
assert_equal true, "".respond_to?(:to_squawk)
end
def test_string_prepend_empty_strings_with_the_word_squawk
assert_equal "squawk!", "".to_squawk
end
def test_string_prepend_non_empty_strings_with_the_word_squawk
assert_equal "squawk! Hello World", "Hello World".to_squawk
end
end
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "core_ext"
--------------------------------------------------------
[source, ruby]
--------------------------------------------------------
# File: vendor/plugins/yaffle/lib/core_ext.rb
String.class_eval do
def to_squawk
"squawk! #{self}".strip
end
end
--------------------------------------------------------
When monkey-patching existing classes it's often better to use `class_eval` instead of opening the class directly.
To test that your method does what it says it does, run the unit tests. To test this manually, fire up a console and start squawking:
--------------------------------------------------------
$ ./script/console
>> "Hello World".to_squawk
=> "squawk! Hello World"
--------------------------------------------------------
If that worked, congratulations! You just created your first test-driven plugin that extends a core ruby class.

View File

@@ -0,0 +1,61 @@
== Create a `squawk_info_for` view helper ==
Creating a view helper is a 3-step process:
* Add an appropriately named file to the 'lib' directory.
* Require the file and hooks in 'init.rb'.
* Write the tests.
First, create the test to define the functionality you want:
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/test/view_helpers_test.rb
require File.dirname(__FILE__) + '/test_helper.rb'
include YaffleViewHelper
class ViewHelpersTest < Test::Unit::TestCase
def test_squawk_info_for_should_return_the_text_and_date
time = Time.now
hickwall = Hickwall.new
hickwall.last_squawk = "Hello World"
hickwall.last_squawked_at = time
assert_equal "Hello World, #{time.to_s}", squawk_info_for(hickwall)
end
end
---------------------------------------------------------------
Then add the following statements to init.rb:
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/init.rb
require "view_helpers"
ActionView::Base.send :include, YaffleViewHelper
---------------------------------------------------------------
Then add the view helpers file and
[source, ruby]
---------------------------------------------------------------
# File: vendor/plugins/yaffle/lib/view_helpers.rb
module YaffleViewHelper
def squawk_info_for(yaffle)
returning "" do |result|
result << yaffle.read_attribute(yaffle.class.yaffle_text_field)
result << ", "
result << yaffle.read_attribute(yaffle.class.yaffle_date_field).to_s
end
end
end
---------------------------------------------------------------
You can also test this in script/console by using the `helper` method:
---------------------------------------------------------------
$ ./script/console
>> helper.squawk_info_for(@some_yaffle_instance)
---------------------------------------------------------------

View File

@@ -0,0 +1,5 @@
Replaced the plain DocBook XSL admonition icons with Jimmac's DocBook
icons (http://jimmac.musichall.cz/ikony.php3). I dropped transparency
from the Jimmac icons to get round MS IE and FOP PNG incompatibilies.
Stuart Rackham

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 361 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 565 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 617 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 623 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 411 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 640 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 353 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 350 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 345 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 348 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 355 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 344 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 357 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

@@ -0,0 +1,86 @@
== Creating records directly from form parameters ==
=== The problem ===
Let's say you want to make a user registration system. Your users table looks like this:
-------------------------------------------------------
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name VARCHAR(20) NOT NULL, -- the login name
password VARCHAR(20) NOT NULL,
role VARCHAR(20) NOT NULL DEFAULT "User", -- e.g. "Admin", "Moderator, "User"
approved INTEGER NOT NULL DEFAULT 0 -- is the registered accound approved by the administrator?
);
CREATE UNIQUE INDEX users_name_unique ON users(name);
-------------------------------------------------------
The registration form:
[source, xhtml]
-------------------------------------------------------
<form method="post" action="http://website.domain/user/register">
<input type="text" name="user[name]" />
<input type="text" name="user[password]" />
</form>
-------------------------------------------------------
The easiest way to create a user object from the form data in the controller is:
[source, ruby]
-------------------------------------------------------
User.create(params[:user])
-------------------------------------------------------
But what happens if someone decides to save the registration form to his disk and play around with adding a few fields?
[source, xhtml]
-------------------------------------------------------
<form method="post" action="http://website.domain/user/register">
<input type="text" name="user[name]" />
<input type="text" name="user[password]" />
<input type="text" name="user[role]" value="Admin" />
<input type="text" name="user[approved]" value="1" />
</form>
-------------------------------------------------------
He can create an account, make himself admin and approve his own account with one click.
=== The solution ===
Active Record provides two ways of securing sensitive attributes from being overwritten by malicious users that change the form. The first is `attr_protected` that denies mass-assignment the right to change the named parameters.
Using `attr_protected`, we can secure the User models like this:
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
attr_protected :approved, :role
end
-------------------------------------------------------
This will ensure that on doing `User.create(params[:user])` both `params[:user][:approved]` and `params[:user][:role]` will be ignored. You'll have to manually set them like this:
[source, ruby]
-------------------------------------------------------
user = User.new(params[:user])
user.approved = sanitize_properly(params[:user][:approved])
user.role = sanitize_properly(params[:user][:role])
-------------------------------------------------------
=== Allowing instead of protecting ===
If you're afraid you might forget to apply `attr_protected` to the right attributes before making your model available to the cruel world, you can also specify the protection in reverse. You simply allow access instead of deny it, so only the attributes named in `attr_accessible` are available for mass-assignment.
Using `attr_accessible`, we can secure the User models like this:
[source, ruby]
-------------------------------------------------------
class User < ActiveRecord::Base
attr_accessible :name, :password
end
-------------------------------------------------------
This description has exactly the same affect as doing `attr_protected :approved, :role`, but when you add new attrbutes to the User model, they'll be protected by default.

View File

@@ -0,0 +1,64 @@
== Cross Site Scripting (CSS/XSS) ==
=== The problem ===
Many web applications use session cookies to track the requests of a user. The cookie is used to identify the request and connect it to the session data (the `session` method in Rails). Usually the session contains a reference to the user that is currently logged in, e.g. the id of a User object.
Cross Site Scripting is a technique for ``stealing'' the cookie from another visitor of the website, and thus stealing the login. Cookies are only available from the domain where the were originally created. The easiest way to get access to the cookie is to place a specially crafted piece of JavaScript code on the website; the script can read the cookie of a visitor and send it to the attacker, e.g. by transmitting the data as an URL parameter to another website.
2.2 Example of an attack
A site with the following Eruby template is vulnerable to XSS:
------------------------------------
<%= params[:text] %>
------------------------------------
The 'text' parameter is directly included in the page, so it is possible to insert JavaScript code by setting the parameter to something like
[source, xhtml]
------------------------------------
<script>alert(document.cookie)</script>
------------------------------------
After url-encoding the script (e.g. with `CGI.encode`) the attacker can put it into an URL and make his victim open the URL in the browser.
If you open the URL
------------------------------------
http://website.domain/controller/action?text=%3Cscript%3Ealert%28document.cookie%29%3C%2Fscript%3E
------------------------------------
you will get a popup window with your session cookie. Instead of opening the popup the script could as well send the session id to another server.
=== How to protect your application ===
Obviously the key to a successful attack is the possibility to place JavaScript on a website that can receive the session cookie. This can be a blog with user comments, a web forum or a Wiki. How can you protect against it? Strictly convert HTML meta characters (`<` and `>`) to the equivalent HTML entities (`&lt;` and `&gt;`) in every string that is rendered in the website. This will ensure that, no matter what kind of text an attacker enters in a form or attaches to an URL, the browser will always render it as plain text and never interpret any HTML tags. This is a good idea anyway, as a user can easily mess up your layout by leaving tags open. If you want the user to be able to format his texts, it is usually better to use a markup language like Textile, Markdown or RDoc.
Rails provides the helper method `h` for HTML meta character conversion in Views.
Example:
------------------------------------
<%=h post.subject %>
<%=h post.text %>
------------------------------------
You should accustom to using `h` for any variable that is rendered in the view, even if you think you can trust it to be from a reliable source.
=== XSS attacks using an echo service ===
The echo service is a service running on TCP port 7 that returns back everything you send to it. On Debian it is active by default. Now how can this be a security problem for a web application?
If the server of the target website 'target.domain' is running an echo service, the attacker could create a form like the following on his own website:
[source, xhtml]
------------------------------------
<form action="http://target.domain:7/" method="post">
<input type="hidden" name="code" value="some_javascript_code_here" />
<input type="submit" />
</form>
------------------------------------
If he makes someone who has a session cookie on the target website submit this form, the content of the hidden field is sent to the echo server at port 7 and returned. If the browser decides to display the returned data as HTML (some versions of IE do), it will execute the JavaScript code; and because the domain is 'target.domain' the session cookie is available for the script.
This is rather a client-side issue, but to reduce the probability of a successful attack you should deactivate any echo services on the web server. However this does not provide full security, because there are also some other services (e.g. FTP, POP3) that can be used instead of the echo server.

View File

@@ -0,0 +1,14 @@
Securing Rails applications
===========================
This manual describes common security problems in web applications and how
to avoid them with Rails. If you have any questions or suggestions, please
mail me at ror(at)andreas-s.net.
include::sql_injection.txt[]
include::cross_site_scripting.txt[]
include::creating_records_directly_from_form_parameters.txt[]

View File

@@ -0,0 +1,87 @@
== SQL Injection ==
=== The problem ===
SQL injection is the #1 security problem in many web applications. How does it work? If the web application includes strings from unreliable sources (usually form parameters) in SQL statements and doesn't correctly quote any SQL meta characters like backslashes or single quotes, an attacker can change `WHERE` conditions in SQL statements, create records with invalid data or even execute arbitrary SQL statements.
=== How to protect your application ===
If you only use the predefined ActiveRecord functions (attributes, save, find) without writing any conditions, limits or SQL queries yourself, ActiveRecord takes care of quoting any dangerous characters in the data for you.
If you don't, you have to make sure that strings for arguments that are directly used to build SQL queries (like the condition, limit and sort arguments for `find :all`) do not contain any SQL meta characters.
=== Using arbitrary strings in conditions and SQL statements ===
==== Wrong ====
Imagine a webmail system where a user can select a list of all the emails with a certain subject. A query could look like this:
[source, ruby]
---------------------------------------------------------------------------
Email.find(:all, "owner_id = 123 AND subject = '#{params[:subject]}'")
---------------------------------------------------------------------------
This is dangerous. Imagine a user sending the string `\' OR 1 \--` in the parameter 'subject'; the resulting statement will look like this:
[source, ruby]
---------------------------------------------------------------------------
Email.find(:all, "owner_id = 123 AND subject = '' OR 1 --'")
---------------------------------------------------------------------------
Because of ``OR 1'' the condition is always true. The part ``\--'' starts a SQL comment; everything after it will be ignored. The result: the user will get a list of all the emails in the database.
(Of course the 'owner_id' would have to be inserted dynamically in a real application; this was omitted to keep the examples as simple as possible.)
==== Correct ====
[source, ruby]
---------------------------------------------------------------------------
Email.find(:all, ["owner_id = 123 AND subject = ?", params[:subject]])
---------------------------------------------------------------------------
If the argument for find_all is an array instead of a string, ActiveRecord will insert the elements 2..n of the array for the `?` placeholders in the element 1, add quotation marks if the elements are strings, and quote all characters that have a special meaning for the database adapter used by the `Email` model.
If you don't like the syntax of the array, you can take care of the quoting yourself by calling the `quote_value` method of the model class. You have to do this when you use `find_by_sql`, as the Array argument doesn't work there:
[source, ruby]
---------------------------------------------------------------------------
Email.find_by_sql("SELECT * FROM email WHERE owner_id = 123 AND subject = #{Email.quote_value(subject)}")
---------------------------------------------------------------------------
The quotation marks are added automatically by `Email.quote_value` if the argument is a string.
=== Extracting queries into model methods ===
If you need to execute a query with the similar options in several places in your code, you should create a model method for that query. Instead of
[source, ruby]
---------------------------------------------------------------------------
emails = Email.find(:all, ["subject = ?", subject])
---------------------------------------------------------------------------
you could define the following class method in the model:
[source, ruby]
---------------------------------------------------------------------------
class Email < ActiveRecord::Base
def self.find_with_subject(subject)
Email.find(:all, ["subject = ?", subject])
end
end
---------------------------------------------------------------------------
and call it like this:
[source, ruby]
---------------------------------------------------------------------------
emails = Email.find_with_subject(subject)
---------------------------------------------------------------------------
This has the advantage that you don't have to care about meta characters when using the function `find_with_subject`. Generally you should always make sure that this kind of model method can not break anything, even if it is called with untrusted arguments.
.ActiveRecord automatically generates finder methods
NOTE: The `find_with_subject` method given in the above example is actually redundant.
ActiveRecord automatically generates finder methods for columns. In this case, ActiveRecord
automatically generates the method `find_by_subject` (which works exactly like the `find_with_subject`
method given in the example). `find_with_subject` is only given here as an example. In general,
you should use ActiveRecord's auto-generated finder methods instead of writing your own.

File diff suppressed because it is too large Load Diff