1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Improve documentation coverage and markup

Signed-off-by: Pratik Naik <pratiknaik@gmail.com>
This commit is contained in:
Xavier Noria 2008-05-02 14:45:23 +01:00 committed by Pratik Naik
parent 87ec72bd8c
commit 64092de257
75 changed files with 811 additions and 659 deletions

View file

@ -198,31 +198,31 @@ module ActionMailer #:nodoc:
#
# These options are specified on the class level, like <tt>ActionMailer::Base.template_root = "/my/templates"</tt>
#
# * <tt>template_root</tt> - template root determines the base from which template references will be made.
# * <tt>template_root</tt> - Determines the base from which template references will be made.
#
# * <tt>logger</tt> - the logger is used for generating information on the mailing run if available.
# Can be set to nil for no logging. Compatible with both Ruby's own Logger and Log4r loggers.
#
# * <tt>smtp_settings</tt> - Allows detailed configuration for :smtp delivery method:
# * <tt>smtp_settings</tt> - Allows detailed configuration for <tt>:smtp</tt> delivery method:
# * <tt>:address</tt> Allows you to use a remote mail server. Just change it from its default "localhost" setting.
# * <tt>:port</tt> On the off chance that your mail server doesn't run on port 25, you can change it.
# * <tt>:domain</tt> If you need to specify a HELO domain, you can do it here.
# * <tt>:user_name</tt> If your mail server requires authentication, set the username in this setting.
# * <tt>:password</tt> If your mail server requires authentication, set the password in this setting.
# * <tt>:authentication</tt> If your mail server requires authentication, you need to specify the authentication type here.
# This is a symbol and one of :plain, :login, :cram_md5
# This is a symbol and one of <tt>:plain</tt>, <tt>:login</tt>, <tt>:cram_md5</tt>
#
# * <tt>sendmail_settings</tt> - Allows you to override options for the :sendmail delivery method
# * <tt>sendmail_settings</tt> - Allows you to override options for the <tt>:sendmail</tt> delivery method
# * <tt>:location</tt> The location of the sendmail executable, defaults to "/usr/sbin/sendmail"
# * <tt>:arguments</tt> The command line arguments
# * <tt>raise_delivery_errors</tt> - whether or not errors should be raised if the email fails to be delivered.
#
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are :smtp (default), :sendmail, and :test.
# * <tt>delivery_method</tt> - Defines a delivery method. Possible values are <tt>:smtp</tt> (default), <tt>:sendmail</tt>, and <tt>:test</tt>.
#
# * <tt>perform_deliveries</tt> - Determines whether deliver_* methods are actually carried out. By default they are,
# but this can be turned off to help functional testing.
#
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with delivery_method :test. Most useful
# * <tt>deliveries</tt> - Keeps an array of all the emails sent out through the Action Mailer with <tt>delivery_method :test</tt>. Most useful
# for unit and functional testing.
#
# * <tt>default_charset</tt> - The default charset used for the body and to encode the subject. Defaults to UTF-8. You can also

View file

@ -332,7 +332,8 @@ module ActionController #:nodoc:
@@resources_path_names = { :new => 'new', :edit => 'edit' }
cattr_accessor :resources_path_names
# Sets the token parameter name for RequestForgery. Calling #protect_from_forgery sets it to :authenticity_token by default
# Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
# sets it to <tt>:authenticity_token</tt> by default.
cattr_accessor :request_forgery_protection_token
# Indicates whether or not optimise the generated named
@ -544,8 +545,8 @@ module ActionController #:nodoc:
# * <tt>:host</tt> -- overrides the default (current) host if provided.
# * <tt>:protocol</tt> -- overrides the default (current) protocol if provided.
# * <tt>:port</tt> -- optionally specify the port to connect to.
# * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if :password is also present).
# * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if :user is also present).
# * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present).
# * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present).
# * <tt>:skip_relative_url_root</tt> -- if true, the url is not constructed using the relative_url_root of the request so the path
# will include the web server relative installation directory.
#
@ -598,7 +599,7 @@ module ActionController #:nodoc:
# url_for :controller => 'posts', :action => nil
#
# If you explicitly want to create a URL that's almost the same as the current URL, you can do so using the
# :overwrite_params options. Say for your posts you have different views for showing and printing them.
# <tt>:overwrite_params</tt> options. Say for your posts you have different views for showing and printing them.
# Then, in the show view, you get the URL for the print view like this
#
# url_for :overwrite_params => { :action => 'print' }
@ -769,7 +770,7 @@ module ActionController #:nodoc:
# # placed in "app/views/layouts/special.r(html|xml)"
# render :text => "Hi there!", :layout => "special"
#
# The :text option can also accept a Proc object, which can be used to manually control the page generation. This should
# The <tt>:text</tt> option can also accept a Proc object, which can be used to manually control the page generation. This should
# generally be avoided, as it violates the separation between code and content, and because almost everything that can be
# done with this method can also be done more cleanly using one of the other rendering methods, most notably templates.
#
@ -823,7 +824,7 @@ module ActionController #:nodoc:
#
# === Rendering with status and location headers
#
# All renders take the :status and :location options and turn them into headers. They can even be used together:
# All renders take the <tt>:status</tt> and <tt>:location</tt> options and turn them into headers. They can even be used together:
#
# render :xml => post.to_xml, :status => :created, :location => post_url(post)
def render(options = nil, extra_options = {}, &block) #:doc:

View file

@ -1,31 +1,38 @@
module ActionController #:nodoc:
# Cookies are read and written through ActionController#cookies. The cookies being read are what were received along with the request,
# the cookies being written are what will be sent out with the response. Cookies are read by value (so you won't get the cookie object
# itself back -- just the value it holds). Examples for writing:
# Cookies are read and written through ActionController#cookies.
#
# cookies[:user_name] = "david" # => Will set a simple session cookie
# The cookies being read are the ones received along with the request, the cookies
# being written will be sent out with the response. Reading a cookie does not get
# the cookie object itself back, just the value it holds.
#
# Examples for writing:
#
# # Sets a simple session cookie.
# cookies[:user_name] = "david"
#
# # Sets a cookie that expires in 1 hour.
# cookies[:login] = { :value => "XJ-122", :expires => 1.hour.from_now }
# # => Will set a cookie that expires in 1 hour
#
# Examples for reading:
#
# cookies[:user_name] # => "david"
# cookies.size # => 2
# cookies.size # => 2
#
# Example for deleting:
#
# cookies.delete :user_name
#
# All the option symbols for setting cookies are:
# The option symbols for setting cookies are:
#
# * <tt>value</tt> - the cookie's value or list of values (as an array).
# * <tt>path</tt> - the path for which this cookie applies. Defaults to the root of the application.
# * <tt>domain</tt> - the domain for which this cookie applies.
# * <tt>expires</tt> - the time at which this cookie expires, as a +Time+ object.
# * <tt>secure</tt> - whether this cookie is a secure cookie or not (default to false).
# Secure cookies are only transmitted to HTTPS servers.
# * <tt>http_only</tt> - whether this cookie is accessible via scripting or only HTTP (defaults to false).
# * <tt>:value</tt> - The cookie's value or list of values (as an array).
# * <tt>:path</tt> - The path for which this cookie applies. Defaults to the root
# of the application.
# * <tt>:domain</tt> - The domain for which this cookie applies.
# * <tt>:expires</tt> - The time at which this cookie expires, as a Time object.
# * <tt>:secure</tt> - Whether this cookie is a only transmitted to HTTPS servers.
# Default is +false+.
# * <tt>:http_only</tt> - Whether this cookie is accessible via scripting or
# only HTTP. Defaults to +false+.
module Cookies
def self.included(base)
base.helper_method :cookies
@ -45,8 +52,7 @@ module ActionController #:nodoc:
update(@cookies)
end
# Returns the value of the cookie by +name+ -- or nil if no such cookie exists. You set new cookies using cookies[]=
# (for simple name/value cookies without options).
# Returns the value of the cookie by +name+, or +nil+ if no such cookie exists.
def [](name)
cookie = @cookies[name.to_s]
if cookie && cookie.respond_to?(:value)
@ -54,6 +60,8 @@ module ActionController #:nodoc:
end
end
# Sets the cookie named +name+. The second argument may be the very cookie
# value, or a hash of options as documented above.
def []=(name, options)
if options.is_a?(Hash)
options = options.inject({}) { |options, pair| options[pair.first.to_s] = pair.last; options }
@ -66,14 +74,18 @@ module ActionController #:nodoc:
end
# Removes the cookie on the client machine by setting the value to an empty string
# and setting its expiration date into the past. Like []=, you can pass in an options
# hash to delete cookies with extra data such as a +path+.
# and setting its expiration date into the past. Like <tt>[]=</tt>, you can pass in
# an options hash to delete cookies with extra data such as a <tt>:path</tt>.
def delete(name, options = {})
options.stringify_keys!
set_cookie(options.merge("name" => name.to_s, "value" => "", "expires" => Time.at(0)))
end
private
# Builds a CGI::Cookie object and adds the cookie to the response headers.
#
# The path of the cookie defaults to "/" if there's none in +options+, and
# everything is passed to the CGI::Cookie constructor.
def set_cookie(options) #:doc:
options["path"] = "/" unless options["path"]
cookie = CGI::Cookie.new(options)

View file

@ -126,8 +126,8 @@ module ActionController #:nodoc:
# end
#
# To use a filter object with around_filter, pass an object responding
# to :filter or both :before and :after. With a filter method, yield to
# the block as above:
# to <tt>:filter</tt> or both <tt>:before</tt> and <tt>:after</tt>. With a
# filter method, yield to the block as above:
#
# around_filter BenchmarkingFilter
#
@ -191,8 +191,9 @@ module ActionController #:nodoc:
# == Filter conditions
#
# Filters may be limited to specific actions by declaring the actions to
# include or exclude. Both options accept single actions (:only => :index)
# or arrays of actions (:except => [:foo, :bar]).
# include or exclude. Both options accept single actions
# (<tt>:only => :index</tt>) or arrays of actions
# (<tt>:except => [:foo, :bar]</tt>).
#
# class Journal < ActionController::Base
# # Require authentication for edit and delete.

View file

@ -143,11 +143,19 @@ module ActionController #:nodoc:
# Declare a controller method as a helper. For example, the following
# makes the +current_user+ controller method available to the view:
# class ApplicationController < ActionController::Base
# helper_method :current_user
# helper_method :current_user, :logged_in?
#
# def current_user
# @current_user ||= User.find(session[:user])
# @current_user ||= User.find_by_id(session[:user])
# end
#
# def logged_in?
# current_user != nil
# end
# end
#
# In a view:
# <% if logged_in? -%>Welcome, <%= current_user.name %><% end -%>
def helper_method(*methods)
methods.flatten.each do |method|
master_helper_module.module_eval <<-end_eval

View file

@ -19,7 +19,7 @@ module ActionController
# * <tt>url_for</tt>, so you can use it with a record as the argument, e.g.
# <tt>url_for(@article)</tt>;
# * ActionView::Helpers::FormHelper uses <tt>polymorphic_path</tt>, so you can write
# <tt>form_for(@article)</tt> without having to specify :url parameter for the form
# <tt>form_for(@article)</tt> without having to specify <tt>:url</tt> parameter for the form
# action;
# * <tt>redirect_to</tt> (which, in fact, uses <tt>url_for</tt>) so you can write
# <tt>redirect_to(post)</tt> in your controllers;

View file

@ -15,7 +15,7 @@ module ActionController
# such as { 'RAILS_ENV' => 'production' }.
attr_reader :env
# The true HTTP request method as a lowercase symbol, such as :get.
# The true HTTP request method as a lowercase symbol, such as <tt>:get</tt>.
# UnknownHttpMethod is raised for invalid methods not listed in ACCEPTED_HTTP_METHODS.
def request_method
@request_method ||= begin
@ -28,35 +28,35 @@ module ActionController
end
end
# The HTTP request method as a lowercase symbol, such as :get.
# Note, HEAD is returned as :get since the two are functionally
# The HTTP request method as a lowercase symbol, such as <tt>:get</tt>.
# Note, HEAD is returned as <tt>:get</tt> since the two are functionally
# equivalent from the application's perspective.
def method
request_method == :head ? :get : request_method
end
# Is this a GET (or HEAD) request? Equivalent to request.method == :get
# Is this a GET (or HEAD) request? Equivalent to <tt>request.method == :get</tt>.
def get?
method == :get
end
# Is this a POST request? Equivalent to request.method == :post
# Is this a POST request? Equivalent to <tt>request.method == :post</tt>.
def post?
request_method == :post
end
# Is this a PUT request? Equivalent to request.method == :put
# Is this a PUT request? Equivalent to <tt>request.method == :put</tt>.
def put?
request_method == :put
end
# Is this a DELETE request? Equivalent to request.method == :delete
# Is this a DELETE request? Equivalent to <tt>request.method == :delete</tt>.
def delete?
request_method == :delete
end
# Is this a HEAD request? request.method sees HEAD as :get, so check the
# HTTP method directly.
# Is this a HEAD request? <tt>request.method</tt> sees HEAD as <tt>:get</tt>,
# so check the HTTP method directly.
def head?
request_method == :head
end

View file

@ -102,7 +102,8 @@ module ActionController #:nodoc:
request.format.html? || request.format.js?
end
# Sets the token value for the current session. Pass a :secret option in #protect_from_forgery to add a custom salt to the hash.
# Sets the token value for the current session. Pass a <tt>:secret</tt> option
# in +protect_from_forgery+ to add a custom salt to the hash.
def form_authenticity_token
@form_authenticity_token ||= if request_forgery_protection_options[:secret]
authenticity_token_from_session_id

View file

@ -58,33 +58,35 @@ module ActionController #:nodoc:
# Rescue exceptions raised in controller actions.
#
# <tt>rescue_from</tt> receives a series of exception classes or class
# names, and a trailing :with option with the name of a method or a Proc
# object to be called to handle them. Alternatively a block can be given.
# names, and a trailing <tt>:with</tt> option with the name of a method
# or a Proc object to be called to handle them. Alternatively a block can
# be given.
#
# Handlers that take one argument will be called with the exception, so
# that the exception can be inspected when dealing with it.
#
# Handlers are inherited. They are searched from right to left, from
# bottom to top, and up the hierarchy. The handler of the first class for
# which exception.is_a?(klass) holds true is the one invoked, if any.
# which <tt>exception.is_a?(klass)</tt> holds true is the one invoked, if
# any.
#
# class ApplicationController < ActionController::Base
# rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
# rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
# class ApplicationController < ActionController::Base
# rescue_from User::NotAuthorized, :with => :deny_access # self defined exception
# rescue_from ActiveRecord::RecordInvalid, :with => :show_errors
#
# rescue_from 'MyAppError::Base' do |exception|
# render :xml => exception, :status => 500
# rescue_from 'MyAppError::Base' do |exception|
# render :xml => exception, :status => 500
# end
#
# protected
# def deny_access
# ...
# end
#
# def show_errors(exception)
# exception.record.new_record? ? ...
# end
# end
#
# protected
# def deny_access
# ...
# end
#
# def show_errors(exception)
# exception.record.new_record? ? ...
# end
# end
def rescue_from(*klasses, &block)
options = klasses.extract_options!
unless options.has_key?(:with)

View file

@ -240,12 +240,12 @@ module ActionController
# * <tt>:collection</tt> - add named routes for other actions that operate on the collection.
# Takes a hash of <tt>#{action} => #{method}</tt>, where method is <tt>:get</tt>/<tt>:post</tt>/<tt>:put</tt>/<tt>:delete</tt>
# or <tt>:any</tt> if the method does not matter. These routes map to a URL like /messages/rss, with a route of rss_messages_url.
# * <tt>:member</tt> - same as :collection, but for actions that operate on a specific member.
# * <tt>:new</tt> - same as :collection, but for actions that operate on the new resource action.
# * <tt>:member</tt> - same as <tt>:collection</tt>, but for actions that operate on a specific member.
# * <tt>:new</tt> - same as <tt>:collection</tt>, but for actions that operate on the new resource action.
# * <tt>:controller</tt> - specify the controller name for the routes.
# * <tt>:singular</tt> - specify the singular name used in the member routes.
# * <tt>:requirements</tt> - set custom routing parameter requirements.
# * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the :method value for the method-specific routes.
# * <tt>:conditions</tt> - specify custom routing recognition conditions. Resources sets the <tt>:method</tt> value for the method-specific routes.
# * <tt>:as</tt> - specify a different resource name to use in the URL path. For example:
# # products_path == '/productos'
# map.resources :products, :as => 'productos' do |product|
@ -254,7 +254,7 @@ module ActionController
# end
#
# * <tt>:has_one</tt> - specify nested resources, this is a shorthand for mapping singleton resources beneath the current.
# * <tt>:has_many</tt> - same has :has_one, but for plural resources.
# * <tt>:has_many</tt> - same has <tt>:has_one</tt>, but for plural resources.
#
# You may directly specify the routing association with has_one and has_many like:
#
@ -288,7 +288,7 @@ module ActionController
# article.resources :comments
# end
#
# The comment resources work the same, but must now include a value for :article_id.
# The comment resources work the same, but must now include a value for <tt>:article_id</tt>.
#
# article_comments_url(@article)
# article_comment_url(@article, @comment)
@ -302,7 +302,7 @@ module ActionController
# map.resources :tags, :path_prefix => '/books/:book_id', :name_prefix => 'book_'
# map.resources :tags, :path_prefix => '/toys/:toy_id', :name_prefix => 'toy_'
#
# You may also use :name_prefix to override the generic named routes in a nested resource:
# You may also use <tt>:name_prefix</tt> to override the generic named routes in a nested resource:
#
# map.resources :articles do |article|
# article.resources :comments, :name_prefix => nil
@ -364,7 +364,7 @@ module ActionController
#
# See map.resources for general conventions. These are the main differences:
# * A singular name is given to map.resource. The default controller name is still taken from the plural name.
# * To specify a custom plural name, use the :plural option. There is no :singular option.
# * To specify a custom plural name, use the <tt>:plural</tt> option. There is no <tt>:singular</tt> option.
# * No default index route is created for the singleton resource controller.
# * When nesting singleton resources, only the singular name is used as the path prefix (example: 'account/messages/1')
#

View file

@ -23,7 +23,8 @@ module ActionController
# map.connect ':controller/:action/:id'
#
# This route states that it expects requests to consist of a
# :controller followed by an :action that in turn is fed some :id.
# <tt>:controller</tt> followed by an <tt>:action</tt> that in turn is fed
# some <tt>:id</tt>.
#
# Suppose you get an incoming request for <tt>/blog/edit/22</tt>, you'll end up
# with:
@ -36,11 +37,11 @@ module ActionController
# Think of creating routes as drawing a map for your requests. The map tells
# them where to go based on some predefined pattern:
#
# ActionController::Routing::Routes.draw do |map|
# Pattern 1 tells some request to go to one place
# Pattern 2 tell them to go to another
# ...
# end
# ActionController::Routing::Routes.draw do |map|
# Pattern 1 tells some request to go to one place
# Pattern 2 tell them to go to another
# ...
# end
#
# The following symbols are special:
#
@ -59,12 +60,12 @@ module ActionController
# Within blocks, the empty pattern is at the highest priority.
# In practice this works out nicely:
#
# ActionController::Routing::Routes.draw do |map|
# map.with_options :controller => 'blog' do |blog|
# blog.show '', :action => 'list'
# end
# map.connect ':controller/:action/:view'
# end
# ActionController::Routing::Routes.draw do |map|
# map.with_options :controller => 'blog' do |blog|
# blog.show '', :action => 'list'
# end
# map.connect ':controller/:action/:view'
# end
#
# In this case, invoking blog controller (with an URL like '/blog/')
# without parameters will activate the 'list' action by default.
@ -75,9 +76,10 @@ module ActionController
# Hash at the end of your mapping to set any default parameters.
#
# Example:
# ActionController::Routing:Routes.draw do |map|
# map.connect ':controller/:action/:id', :controller => 'blog'
# end
#
# ActionController::Routing:Routes.draw do |map|
# map.connect ':controller/:action/:id', :controller => 'blog'
# end
#
# This sets up +blog+ as the default controller if no other is specified.
# This means visiting '/' would invoke the blog controller.
@ -93,6 +95,7 @@ module ActionController
# for the full URL and +name_of_route_path+ for the URI path.
#
# Example:
#
# # In routes.rb
# map.login 'login', :controller => 'accounts', :action => 'login'
#
@ -138,22 +141,23 @@ module ActionController
#
# Routes can generate pretty URLs. For example:
#
# map.connect 'articles/:year/:month/:day',
# :controller => 'articles',
# :action => 'find_by_date',
# :year => /\d{4}/,
# :month => /\d{1,2}/,
# :day => /\d{1,2}/
# map.connect 'articles/:year/:month/:day',
# :controller => 'articles',
# :action => 'find_by_date',
# :year => /\d{4}/,
# :month => /\d{1,2}/,
# :day => /\d{1,2}/
#
# # Using the route above, the url below maps to:
# # params = {:year => '2005', :month => '11', :day => '06'}
# # http://localhost:3000/articles/2005/11/06
# Using the route above, the URL "http://localhost:3000/articles/2005/11/06"
# maps to
#
# params = {:year => '2005', :month => '11', :day => '06'}
#
# == Regular Expressions and parameters
# You can specify a regular expression to define a format for a parameter.
#
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show', :postalcode => /\d{5}(-\d{4})?/
# map.geocode 'geocode/:postalcode', :controller => 'geocode',
# :action => 'show', :postalcode => /\d{5}(-\d{4})?/
#
# or, more formally:
#
@ -182,7 +186,7 @@ module ActionController
#
# Specifying <tt>*[string]</tt> as part of a rule like:
#
# map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
# map.connect '*path' , :controller => 'blog' , :action => 'unrecognized?'
#
# will glob all remaining parts of the route that were not recognized earlier. This idiom
# must appear at the end of the path. The globbed values are in <tt>params[:path]</tt> in
@ -210,7 +214,7 @@ module ActionController
#
# You can reload routes if you feel you must:
#
# ActionController::Routing::Routes.reload
# ActionController::Routing::Routes.reload
#
# This will clear all named routes and reload routes.rb if the file has been modified from
# last load. To absolutely force reloading, use +reload!+.
@ -221,19 +225,19 @@ module ActionController
#
# === +assert_routing+
#
# def test_movie_route_properly_splits
# opts = {:controller => "plugin", :action => "checkout", :id => "2"}
# assert_routing "plugin/checkout/2", opts
# end
# def test_movie_route_properly_splits
# opts = {:controller => "plugin", :action => "checkout", :id => "2"}
# assert_routing "plugin/checkout/2", opts
# end
#
# +assert_routing+ lets you test whether or not the route properly resolves into options.
#
# === +assert_recognizes+
#
# def test_route_has_options
# opts = {:controller => "plugin", :action => "show", :id => "12"}
# assert_recognizes opts, "/plugins/show/12"
# end
# def test_route_has_options
# opts = {:controller => "plugin", :action => "show", :id => "12"}
# assert_recognizes opts, "/plugins/show/12"
# end
#
# Note the subtle difference between the two: +assert_routing+ tests that
# a URL fits options while +assert_recognizes+ tests that a URL
@ -241,16 +245,16 @@ module ActionController
#
# In tests you can simply pass the URL or named route to +get+ or +post+.
#
# def send_to_jail
# get '/jail'
# assert_response :success
# assert_template "jail/front"
# end
# def send_to_jail
# get '/jail'
# assert_response :success
# assert_template "jail/front"
# end
#
# def goes_to_login
# get login_url
# #...
# end
# def goes_to_login
# get login_url
# #...
# end
#
# == View a list of all your routes
#

View file

@ -124,7 +124,7 @@ module ActionController
route_requirements
end
# Assign default options, such as 'index' as a default for :action. This
# Assign default options, such as 'index' as a default for <tt>:action</tt>. This
# method must be run *after* user supplied requirements and defaults have
# been applied to the segments.
def assign_default_route_options(segments)
@ -187,7 +187,7 @@ module ActionController
end
# Routes cannot use the current string interpolation method
# if there are user-supplied :requirements as the interpolation
# if there are user-supplied <tt>:requirements</tt> as the interpolation
# code won't raise RoutingErrors when generating
if options.key?(:requirements) || route.requirements.keys.to_set != Routing::ALLOWED_REQUIREMENTS_FOR_OPTIMISATION
route.optimise = false

View file

@ -1,11 +1,11 @@
module ActionController
module Routing
# Much of the slow performance from routes comes from the
# complexity of expiry, :requirements matching, defaults providing
# complexity of expiry, <tt>:requirements</tt> matching, defaults providing
# and figuring out which url pattern to use. With named routes
# we can avoid the expense of finding the right route. So if
# they've provided the right number of arguments, and have no
# :requirements, we can just build up a string and return it.
# <tt>:requirements</tt>, we can just build up a string and return it.
#
# To support building optimisations for other common cases, the
# generation code is separated into several classes
@ -41,19 +41,20 @@ module ActionController
end
end
# Temporarily disabled :url optimisation pending proper solution to
# Temporarily disabled <tt>:url</tt> optimisation pending proper solution to
# Issues around request.host etc.
def applicable?
true
end
end
# Given a route:
# map.person '/people/:id'
# Given a route
#
# If the user calls person_url(@person), we can simply
# map.person '/people/:id'
#
# If the user calls <tt>person_url(@person)</tt>, we can simply
# return a string like "/people/#{@person.to_param}"
# rather than triggering the expensive logic in url_for
# rather than triggering the expensive logic in +url_for+.
class PositionalArguments < Optimiser
def guard_condition
number_of_arguments = route.segment_keys.size
@ -77,7 +78,7 @@ module ActionController
elements << '#{request.relative_url_root if request.relative_url_root}'
# The last entry in route.segments appears to # *always* be a
# The last entry in <tt>route.segments</tt> appears to *always* be a
# 'divider segment' for '/' but we have assertions to ensure that
# we don't include the trailing slashes, so skip them.
(route.segments.size == 1 ? route.segments : route.segments[0..-2]).each do |segment|
@ -106,7 +107,7 @@ module ActionController
super.insert(-2, '?#{args.last.to_query}')
end
# To avoid generating http://localhost/?host=foo.example.com we
# To avoid generating "http://localhost/?host=foo.example.com" we
# can't use this optimisation on routes without any segments
def applicable?
super && route.segment_keys.size > 0

View file

@ -139,8 +139,8 @@ module ActionController
# those that were not used to generate a particular route. The extra
# keys also do not include those recalled from the prior request, nor
# do they include any keys that were implied in the route (like a
# :controller that is required, but not explicitly used in the text of
# the route.)
# <tt>:controller</tt> that is required, but not explicitly used in the
# text of the route.)
def extra_keys(hash, recall={})
(hash || {}).keys.map { |k| k.to_sym } - (recall || {}).keys - significant_keys
end

View file

@ -14,27 +14,27 @@ require 'openssl' # to generate the HMAC message digest
# TamperedWithCookie is raised if the data integrity check fails.
#
# A message digest is included with the cookie to ensure data integrity:
# a user cannot alter his user_id without knowing the secret key included in
# a user cannot alter his +user_id+ without knowing the secret key included in
# the hash. New apps are generated with a pregenerated secret in
# config/environment.rb. Set your own for old apps you're upgrading.
#
# Session options:
# :secret An application-wide key string or block returning a string
# called per generated digest. The block is called with the
# CGI::Session instance as an argument. It's important that the
# secret is not vulnerable to a dictionary attack. Therefore,
# you should choose a secret consisting of random numbers and
# letters and more than 30 characters.
#
# Example: :secret => '449fe2e7daee471bffae2fd8dc02313d'
# :secret => Proc.new { User.current_user.secret_key }
# * <tt>:secret</tt>: An application-wide key string or block returning a string
# called per generated digest. The block is called with the CGI::Session
# instance as an argument. It's important that the secret is not vulnerable to
# a dictionary attack. Therefore, you should choose a secret consisting of
# random numbers and letters and more than 30 characters. Examples:
#
# :digest The message digest algorithm used to verify session integrity
# defaults to 'SHA1' but may be any digest provided by OpenSSL,
# such as 'MD5', 'RIPEMD160', 'SHA256', etc.
# :secret => '449fe2e7daee471bffae2fd8dc02313d'
# :secret => Proc.new { User.current_user.secret_key }
#
# * <tt>:digest</tt>: The message digest algorithm used to verify session
# integrity defaults to 'SHA1' but may be any digest provided by OpenSSL,
# such as 'MD5', 'RIPEMD160', 'SHA256', etc.
#
# To generate a secret key for an existing application, run
# `rake secret` and set the key in config/environment.rb
# `rake secret` and set the key in config/environment.rb.
#
# Note that changing digest or secret invalidates all existing sessions!
class CGI::Session::CookieStore

View file

@ -16,9 +16,11 @@ module ActionController #:nodoc:
end
module ClassMethods
# Set the session store to be used for keeping the session data between requests. By default, sessions are stored
# in browser cookies (:cookie_store), but you can also specify one of the other included stores
# (:active_record_store, :p_store, drb_store, :mem_cache_store, or :memory_store) or your own custom class.
# Set the session store to be used for keeping the session data between requests.
# By default, sessions are stored in browser cookies (<tt>:cookie_store</tt>),
# but you can also specify one of the other included stores (<tt>:active_record_store</tt>,
# <tt>:p_store</tt>, <tt>:drb_store</tt>, <tt>:mem_cache_store</tt>, or
# <tt>:memory_store</tt>) or your own custom class.
def session_store=(store)
ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS[:database_manager] =
store.is_a?(Symbol) ? CGI::Session.const_get(store == :drb_store ? "DRbStore" : store.to_s.camelize) : store

View file

@ -17,24 +17,24 @@ module ActionController #:nodoc:
# it feasible to send even large files.
#
# Be careful to sanitize the path parameter if it coming from a web
# page. send_file(params[:path]) allows a malicious user to
# page. <tt>send_file(params[:path])</tt> allows a malicious user to
# download any file on your server.
#
# Options:
# * <tt>:filename</tt> - suggests a filename for the browser to use.
# Defaults to File.basename(path).
# Defaults to <tt>File.basename(path)</tt>.
# * <tt>:type</tt> - specifies an HTTP content type.
# Defaults to 'application/octet-stream'.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
# Valid values are 'inline' and 'attachment' (default).
# * <tt>:stream</tt> - whether to send the file to the user agent as it is read (true)
# or to read the entire file before sending (false). Defaults to true.
# * <tt>:stream</tt> - whether to send the file to the user agent as it is read (+true+)
# or to read the entire file before sending (+false+). Defaults to +true+.
# * <tt>:buffer_size</tt> - specifies size (in bytes) of the buffer used to stream the file.
# Defaults to 4096.
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
# * <tt>:url_based_filename</tt> - set to true if you want the browser guess the filename from
# * <tt>:url_based_filename</tt> - set to +true+ if you want the browser guess the filename from
# the URL, which is necessary for i18n filenames on certain browsers
# (setting :filename overrides this option).
# (setting <tt>:filename</tt> overrides this option).
#
# The default Content-Type and Content-Disposition headers are
# set to download arbitrary binary files in as many browsers as
@ -42,17 +42,20 @@ module ActionController #:nodoc:
# a variety of quirks (especially when downloading over SSL).
#
# Simple download:
#
# send_file '/path/to.zip'
#
# Show a JPEG in the browser:
#
# send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'
#
# Show a 404 page in the browser:
#
# send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404
#
# Read about the other Content-* HTTP headers if you'd like to
# provide the user with more information (such as Content-Description).
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11
# provide the user with more information (such as Content-Description) in
# http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11.
#
# Also be aware that the document may be cached by proxies and browsers.
# The Pragma and Cache-Control headers declare how the file may be cached
@ -95,7 +98,7 @@ module ActionController #:nodoc:
# and specify whether to show data inline or download as an attachment.
#
# Options:
# * <tt>:filename</tt> - Suggests a filename for the browser to use.
# * <tt>:filename</tt> - suggests a filename for the browser to use.
# * <tt>:type</tt> - specifies an HTTP content type.
# Defaults to 'application/octet-stream'.
# * <tt>:disposition</tt> - specifies whether the file will be shown inline or downloaded.
@ -103,12 +106,15 @@ module ActionController #:nodoc:
# * <tt>:status</tt> - specifies the status code to send with the response. Defaults to '200 OK'.
#
# Generic data download:
#
# send_data buffer
#
# Download a dynamically-generated tarball:
#
# send_data generate_tgz('dir'), :filename => 'dir.tgz'
#
# Display an image Active Record in the browser:
#
# send_data image.data, :type => image.content_type, :disposition => 'inline'
#
# See +send_file+ for more information on HTTP Content-* headers and caching.

View file

@ -155,12 +155,12 @@ module ActionController #:nodoc:
# A refactoring of TestResponse to allow the same behavior to be applied
# to the "real" CgiResponse class in integration tests.
module TestResponseBehavior #:nodoc:
# the response code of the request
# The response code of the request
def response_code
headers['Status'][0,3].to_i rescue 0
end
# returns a String to ensure compatibility with Net::HTTPResponse
# Returns a String to ensure compatibility with Net::HTTPResponse
def code
headers['Status'].to_s.split(' ')[0]
end
@ -169,34 +169,34 @@ module ActionController #:nodoc:
headers['Status'].to_s.split(' ',2)[1]
end
# was the response successful?
# Was the response successful?
def success?
response_code == 200
end
# was the URL not found?
# Was the URL not found?
def missing?
response_code == 404
end
# were we redirected?
# Were we redirected?
def redirect?
(300..399).include?(response_code)
end
# was there a server-side error?
# Was there a server-side error?
def error?
(500..599).include?(response_code)
end
alias_method :server_error?, :error?
# returns the redirection location or nil
# Returns the redirection location or nil
def redirect_url
headers['Location']
end
# does the redirect location match this regexp pattern?
# Does the redirect location match this regexp pattern?
def redirect_url_match?( pattern )
return false if redirect_url.nil?
p = Regexp.new(pattern) if pattern.class == String
@ -205,7 +205,7 @@ module ActionController #:nodoc:
p.match(redirect_url) != nil
end
# returns the template path of the file which was used to
# Returns the template path of the file which was used to
# render this response (or nil)
def rendered_file(with_controller=false)
unless template.first_render.nil?
@ -217,50 +217,49 @@ module ActionController #:nodoc:
end
end
# was this template rendered by a file?
# Was this template rendered by a file?
def rendered_with_file?
!rendered_file.nil?
end
# a shortcut to the flash (or an empty hash if no flash.. hey! that rhymes!)
# A shortcut to the flash. Returns an empyt hash if no session flash exists.
def flash
session['flash'] || {}
end
# do we have a flash?
# Do we have a flash?
def has_flash?
!session['flash'].empty?
end
# do we have a flash that has contents?
# Do we have a flash that has contents?
def has_flash_with_contents?
!flash.empty?
end
# does the specified flash object exist?
# Does the specified flash object exist?
def has_flash_object?(name=nil)
!flash[name].nil?
end
# does the specified object exist in the session?
# Does the specified object exist in the session?
def has_session_object?(name=nil)
!session[name].nil?
end
# a shortcut to the template.assigns
# A shortcut to the template.assigns
def template_objects
template.assigns || {}
end
# does the specified template object exist?
# Does the specified template object exist?
def has_template_object?(name=nil)
!template_objects[name].nil?
end
# Returns the response cookies, converted to a Hash of (name => CGI::Cookie) pairs
# Example:
#
# assert_equal ['AuthorOfNewPage'], r.cookies['author'].value
# assert_equal ['AuthorOfNewPage'], r.cookies['author'].value
def cookies
headers['cookie'].inject({}) { |hash, cookie| hash[cookie.name] = cookie; hash }
end
@ -465,10 +464,13 @@ module ActionController #:nodoc:
return super
end
# Shortcut for ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type). Example:
# Shortcut for <tt>ActionController::TestUploadedFile.new(Test::Unit::TestCase.fixture_path + path, type)</tt>:
#
# post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png')
#
# To upload binary files on Windows, pass :binary as the last parameter. This will not affect other platforms.
# To upload binary files on Windows, pass <tt>:binary</tt> as the last parameter.
# This will not affect other platforms:
#
# post :change_avatar, :avatar => fixture_file_upload('/files/spongebob.png', 'image/png', :binary)
def fixture_file_upload(path, mime_type = nil, binary = false)
ActionController::TestUploadedFile.new(
@ -483,17 +485,17 @@ module ActionController #:nodoc:
# with a new RouteSet instance.
#
# The new instance is yielded to the passed block. Typically the block
# will create some routes using map.draw { map.connect ... }:
# will create some routes using <tt>map.draw { map.connect ... }</tt>:
#
# with_routing do |set|
# set.draw do |map|
# map.connect ':controller/:action/:id'
# assert_equal(
# ['/content/10/show', {}],
# map.generate(:controller => 'content', :id => 10, :action => 'show')
# end
# end
# end
# with_routing do |set|
# set.draw do |map|
# map.connect ':controller/:action/:id'
# assert_equal(
# ['/content/10/show', {}],
# map.generate(:controller => 'content', :id => 10, :action => 'show')
# end
# end
# end
#
def with_routing
real_routes = ActionController::Routing::Routes

View file

@ -15,8 +15,8 @@ module ActionController
# In addition to providing +url_for+, named routes are also accessible after
# including UrlWriter.
module UrlWriter
# The default options for urls written by this writer. Typically a :host pair
# is provided.
# The default options for urls written by this writer. Typically a <tt>:host</tt>
# pair is provided.
mattr_accessor :default_url_options
self.default_url_options = {}
@ -29,16 +29,19 @@ module ActionController
# Generate a url based on the options provided, default_url_options and the
# routes defined in routes.rb. The following options are supported:
#
# * <tt>:only_path</tt> If true, the relative url is returned. Defaults to false.
# * <tt>:only_path</tt> If true, the relative url is returned. Defaults to +false+.
# * <tt>:protocol</tt> The protocol to connect to. Defaults to 'http'.
# * <tt>:host</tt> Specifies the host the link should be targetted at. If <tt>:only_path</tt> is false, this option must be
# provided either explicitly, or via default_url_options.
# * <tt>:host</tt> Specifies the host the link should be targetted at.
# If <tt>:only_path</tt> is false, this option must be
# provided either explicitly, or via +default_url_options+.
# * <tt>:port</tt> Optionally specify the port to connect to.
# * <tt>:anchor</tt> An anchor name to be appended to the path.
# * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the relative_url_root set in <tt>ActionController::AbstractRequest.relative_url_root</tt>.
# * <tt>:skip_relative_url_root</tt> If true, the url is not constructed using the
# +relative_url_root+ set in ActionController::AbstractRequest.relative_url_root.
# * <tt>:trailing_slash</tt> If true, adds a trailing slash, as in "/archive/2009/"
#
# Any other key(:controller, :action, etc...) given to <tt>url_for</tt> is forwarded to the Routes module.
# Any other key (<tt>:controller</tt>, <tt>:action</tt>, etc.) given to
# +url_for+ is forwarded to the Routes module.
#
# Examples:
#

View file

@ -287,9 +287,10 @@ If you are rendering a subtemplate, you must now use controller-like partial syn
template_path.split('/').last[0,1] != '_'
end
# symbolized version of the :format parameter of the request, or :html by default.
# Returns a symbolized version of the <tt>:format</tt> parameter of the request,
# or <tt>:html</tt> by default.
#
# EXCEPTION: If the :format parameter is not set, the Accept header will be examined for
# EXCEPTION: If the <tt>:format</tt> parameter is not set, the Accept header will be examined for
# whether it contains the JavaScript mime type as its first priority. If that's the case,
# it will be used. This ensures that Ajax applications can use the same URL to support both
# JavaScript and non-JavaScript users.

View file

@ -8,47 +8,55 @@ module ActionView
end
module Helpers
# The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the form
# The Active Record Helper makes it easier to create forms for records kept in instance variables. The most far-reaching is the +form+
# method that creates a complete form for all the basic content types of the record (not associations or aggregations, though). This
# is a great way of making the record quickly available for editing, but likely to prove lackluster for a complicated real-world form.
# In that case, it's better to use the input method and the specialized form methods in link:classes/ActionView/Helpers/FormHelper.html
# In that case, it's better to use the +input+ method and the specialized +form+ methods in link:classes/ActionView/Helpers/FormHelper.html
module ActiveRecordHelper
# Returns a default input tag for the type of object returned by the method. For example, let's say you have a model
# that has an attribute +title+ of type VARCHAR column, and this instance holds "Hello World":
# input("post", "title") =>
# <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
# Returns a default input tag for the type of object returned by the method. For example, if <tt>@post</tt>
# has an attribute +title+ mapped to a +VARCHAR+ column that holds "Hello World":
#
# input("post", "title")
# # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
def input(record_name, method, options = {})
InstanceTag.new(record_name, method, self).to_tag(options)
end
# Returns an entire form with all needed input tags for a specified Active Record object. For example, let's say you
# have a table model <tt>Post</tt> with attributes named <tt>title</tt> of type <tt>VARCHAR</tt> and <tt>body</tt> of type <tt>TEXT</tt>:
# Returns an entire form with all needed input tags for a specified Active Record object. For example, if <tt>@post</tt>
# has attributes named +title+ of type +VARCHAR+ and +body+ of type +TEXT+ then
#
# form("post")
# That line would yield a form like the following:
# <form action='/post/create' method='post'>
# <p>
# <label for="post_title">Title</label><br />
# <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
# </p>
# <p>
# <label for="post_body">Body</label><br />
# <textarea cols="40" id="post_body" name="post[body]" rows="20">
# </textarea>
# </p>
# <input type='submit' value='Create' />
# </form>
#
# would yield a form like the following (modulus formatting):
#
# <form action='/posts/create' method='post'>
# <p>
# <label for="post_title">Title</label><br />
# <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
# </p>
# <p>
# <label for="post_body">Body</label><br />
# <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea>
# </p>
# <input name="commit" type="submit" value="Create" />
# </form>
#
# It's possible to specialize the form builder by using a different action name and by supplying another
# block renderer. For example, let's say you have a model <tt>Entry</tt> with an attribute <tt>message</tt> of type <tt>VARCHAR</tt>:
# block renderer. For example, if <tt>@entry</tt> has an attribute +message+ of type +VARCHAR+ then
#
# form("entry", :action => "sign", :input_block =>
# Proc.new { |record, column| "#{column.human_name}: #{input(record, column.name)}<br />" }) =>
# form("entry",
# :action => "sign",
# :input_block => Proc.new { |record, column|
# "#{column.human_name}: #{input(record, column.name)}<br />"
# })
#
# <form action='/post/sign' method='post'>
# Message:
# <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /><br />
# <input type='submit' value='Sign' />
# </form>
# would yield a form like the following (modulus formatting):
#
# <form action="/entries/sign" method="post">
# Message:
# <input id="entry_message" name="entry[message]" size="30" type="text" /><br />
# <input name="commit" type="submit" value="Sign" />
# </form>
#
# It's also possible to add additional content to the form by giving it a block, such as:
#
@ -59,11 +67,11 @@ module ActionView
#
# The following options are available:
#
# * <tt>action</tt> - the action used when submitting the form (default: create if a new record, otherwise update)
# * <tt>input_block</tt> - specialize the output using a different block, see above
# * <tt>method</tt> - the method used when submitting the form (default: post)
# * <tt>multipart</tt> - whether to change the enctype of the form to multipart/form-date, used when uploading a file (default: false)
# * <tt>submit_value</tt> - the text of the submit button (default: Create if a new record, otherwise Update)
# * <tt>:action</tt> - The action used when submitting the form (default: +create+ if a new record, otherwise +update+).
# * <tt>:input_block</tt> - Specialize the output using a different block, see above.
# * <tt>:method</tt> - The method used when submitting the form (default: +post+).
# * <tt>:multipart</tt> - Whether to change the enctype of the form to "multipart/form-data", used when uploading a file (default: +false+).
# * <tt>:submit_value</tt> - The text of the submit button (default: "Create" if a new record, otherwise "Update").
def form(record_name, options = {})
record = instance_variable_get("@#{record_name}")
@ -84,17 +92,16 @@ module ActionView
# Returns a string containing the error message attached to the +method+ on the +object+ if one exists.
# This error message is wrapped in a <tt>DIV</tt> tag, which can be extended to include a +prepend_text+ and/or +append_text+
# (to properly explain the error), and a +css_class+ to style it accordingly. +object+ should either be the name of an instance variable or
# the actual object. As an example, let's say you have a model
# +post+ that has an error message on the +title+ attribute:
# the actual object. As an example, let's say you have a model <tt>@post</tt> that has an error message on the +title+ attribute:
#
# <%= error_message_on "post", "title" %> =>
# <div class="formError">can't be empty</div>
# <%= error_message_on "post", "title" %>
# # => <div class="formError">can't be empty</div>
#
# <%= error_message_on @post, "title" %> =>
# <div class="formError">can't be empty</div>
# <%= error_message_on @post, "title" %>
# # => <div class="formError">can't be empty</div>
#
# <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %> =>
# <div class="inputError">Title simply can't be empty (or it won't work).</div>
# <%= error_message_on "post", "title", "Title simply ", " (or it won't work).", "inputError" %>
# # => <div class="inputError">Title simply can't be empty (or it won't work).</div>
def error_message_on(object, method, prepend_text = "", append_text = "", css_class = "formError")
if (obj = (object.respond_to?(:errors) ? object : instance_variable_get("@#{object}"))) &&
(errors = obj.errors.on(method))
@ -110,30 +117,37 @@ module ActionView
#
# This <tt>DIV</tt> can be tailored by the following options:
#
# * <tt>header_tag</tt> - Used for the header of the error div (default: h2)
# * <tt>id</tt> - The id of the error div (default: errorExplanation)
# * <tt>class</tt> - The class of the error div (default: errorExplanation)
# * <tt>object</tt> - The object (or array of objects) for which to display errors, if you need to escape the instance variable convention
# * <tt>object_name</tt> - The object name to use in the header, or any text that you prefer. If <tt>object_name</tt> is not set, the name of the first object will be used.
# * <tt>header_message</tt> - The message in the header of the error div. Pass +nil+ or an empty string to avoid the header message altogether. (default: X errors prohibited this object from being saved)
# * <tt>message</tt> - The explanation message after the header message and before the error list. Pass +nil+ or an empty string to avoid the explanation message altogether. (default: There were problems with the following fields:)
# * <tt>:header_tag</tt> - Used for the header of the error div (default: "h2").
# * <tt>:id</tt> - The id of the error div (default: "errorExplanation").
# * <tt>:class</tt> - The class of the error div (default: "errorExplanation").
# * <tt>:object</tt> - The object (or array of objects) for which to display errors,
# if you need to escape the instance variable convention.
# * <tt>:object_name</tt> - The object name to use in the header, or any text that you prefer.
# If <tt>:object_name</tt> is not set, the name of the first object will be used.
# * <tt>:header_message</tt> - The message in the header of the error div. Pass +nil+
# or an empty string to avoid the header message altogether. (Default: "X errors
# prohibited this object from being saved").
# * <tt>:message</tt> - The explanation message after the header message and before
# the error list. Pass +nil+ or an empty string to avoid the explanation message
# altogether. (Default: "There were problems with the following fields:").
#
# To specify the display for one object, you simply provide its name as a parameter. For example, for the +User+ model:
# To specify the display for one object, you simply provide its name as a parameter.
# For example, for the <tt>@user</tt> model:
#
# error_messages_for 'user'
#
# To specify more than one object, you simply list them; optionally, you can add an extra +object_name+ parameter, which
# will be the name used in the header message.
# To specify more than one object, you simply list them; optionally, you can add an extra <tt>:object_name</tt> parameter, which
# will be the name used in the header message:
#
# error_messages_for 'user_common', 'user', :object_name => 'user'
#
# If the objects cannot be located as instance variables, you can add an extra +object+ paremeter which gives the actual
# object (or array of objects to use)
# If the objects cannot be located as instance variables, you can add an extra <tt>:object</tt> paremeter which gives the actual
# object (or array of objects to use):
#
# error_messages_for 'user', :object => @question.user
#
# NOTE: This is a pre-packaged presentation of the errors with embedded strings and a certain HTML structure. If what
# you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors
# you need is significantly different from the default presentation, it makes plenty of sense to access the <tt>object.errors</tt>
# instance yourself and set it up. View the source of this method to see how easy it is.
def error_messages_for(*params)
options = params.extract_options!.symbolize_keys

View file

@ -164,7 +164,7 @@ module ActionView
# current page or you can pass the full path relative to your document
# root. To include the Prototype and Scriptaculous javascript libraries in
# your application, pass <tt>:defaults</tt> as the source. When using
# :defaults, if an <tt>application.js</tt> file exists in your public
# <tt>:defaults</tt>, if an application.js file exists in your public
# javascripts directory, it will be included as well. You can modify the
# html attributes of the script tag by passing a hash as the last argument.
#
@ -332,7 +332,7 @@ module ActionView
# <link href="/stylesheets/random.styles" media="screen" rel="stylesheet" type="text/css" />
# <link href="/css/stylish.css" media="screen" rel="stylesheet" type="text/css" />
#
# You can also include all styles in the stylesheet directory using :all as the source:
# You can also include all styles in the stylesheet directory using <tt>:all</tt> as the source:
#
# stylesheet_link_tag :all # =>
# <link href="/stylesheets/style1.css" media="screen" rel="stylesheet" type="text/css" />

View file

@ -104,17 +104,17 @@ module ActionView
# Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute (identified by
# +method+) on an object assigned to the template (identified by +object+). It's possible to tailor the selects through the +options+ hash,
# which accepts all the keys that each of the individual select builders do (like :use_month_numbers for select_month) as well as a range of
# which accepts all the keys that each of the individual select builders do (like <tt>:use_month_numbers</tt> for select_month) as well as a range of
# discard options. The discard options are <tt>:discard_year</tt>, <tt>:discard_month</tt> and <tt>:discard_day</tt>. Set to true, they'll
# drop the respective select. Discarding the month select will also automatically discard the day select. It's also possible to explicitly
# set the order of the tags using the <tt>:order</tt> option with an array of symbols <tt>:year</tt>, <tt>:month</tt> and <tt>:day</tt> in
# the desired order. Symbols may be omitted and the respective select is not included.
#
# Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of :year, :month, :day, :hour, :minute, and :second.
# Pass the <tt>:default</tt> option to set the default date. Use a Time object or a Hash of <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:minute</tt>, and <tt>:second</tt>.
#
# Passing :disabled => true as part of the +options+ will make elements inaccessible for change.
# Passing <tt>:disabled => true</tt> as part of the +options+ will make elements inaccessible for change.
#
# If anything is passed in the html_options hash it will be applied to every select tag in the set.
# If anything is passed in the +html_options+ hash it will be applied to every select tag in the set.
#
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
#

View file

@ -108,7 +108,7 @@ module ActionView
# Note: This also works for the methods in FormOptionHelper and DateHelper that are designed to work with an object as base,
# like FormOptionHelper#collection_select and DateHelper#datetime_select.
#
# HTML attributes for the form tag can be given as :html => {...}. For example:
# HTML attributes for the form tag can be given as <tt>:html => {...}</tt>. For example:
#
# <% form_for :person, @person, :html => {:id => 'person_form'} do |f| %>
# ...

View file

@ -93,8 +93,8 @@ module ActionView
# This allows the user to submit a form page more than once with the expected results of creating multiple records.
# In addition, this allows a single partial to be used to generate form inputs for both edit and create forms.
#
# By default, post.person_id is the selected option. Specify :selected => value to use a different selection
# or :selected => nil to leave all options unselected.
# By default, <tt>post.person_id</tt> is the selected option. Specify <tt>:selected => value</tt> to use a different selection
# or <tt>:selected => nil</tt> to leave all options unselected.
def select(object, method, choices, options = {}, html_options = {})
InstanceTag.new(object, method, self, nil, options.delete(:object)).to_select_tag(choices, options, html_options)
end

View file

@ -341,8 +341,9 @@ module ActionView
# submit_tag nil, :class => "form_submit"
# # => <input class="form_submit" name="commit" type="submit" />
#
# submit_tag "Edit", :disable_with => "Editing...", :class => 'edit-button'
# # => <input class="edit-button" disable_with="Editing..." name="commit" type="submit" value="Edit" />
# submit_tag "Edit", :disable_with => "Editing...", :class => "edit-button"
# # => <input class="edit-button" onclick="this.disabled=true;this.value='Editing...';this.form.submit();"
# # name="commit" type="submit" value="Edit" />
def submit_tag(value = "Save changes", options = {})
options.stringify_keys!

View file

@ -255,10 +255,10 @@ module ActionView
link_to_function(name, remote_function(options), html_options || options.delete(:html))
end
# Periodically calls the specified url (<tt>options[:url]</tt>) every
# Periodically calls the specified url (<tt>options[:url]</tt>) every
# <tt>options[:frequency]</tt> seconds (default is 10). Usually used to
# update a specified div (<tt>options[:update]</tt>) with the results
# of the remote call. The options for specifying the target with :url
# update a specified div (<tt>options[:update]</tt>) with the results
# of the remote call. The options for specifying the target with <tt>:url</tt>
# and defining callbacks is the same as link_to_remote.
# Examples:
# # Call get_averages and put its results in 'avg' every 10 seconds
@ -291,11 +291,11 @@ module ActionView
# though it's using JavaScript to serialize the form elements, the form
# submission will work just like a regular submission as viewed by the
# receiving side (all elements available in <tt>params</tt>). The options for
# specifying the target with :url and defining callbacks is the same as
# link_to_remote.
# specifying the target with <tt>:url</tt> and defining callbacks is the same as
# +link_to_remote+.
#
# A "fall-through" target for browsers that doesn't do JavaScript can be
# specified with the :action/:method options on :html.
# specified with the <tt>:action</tt>/<tt>:method</tt> options on <tt>:html</tt>.
#
# Example:
# # Generates:
@ -304,11 +304,11 @@ module ActionView
# form_remote_tag :html => { :action =>
# url_for(:controller => "some", :action => "place") }
#
# The Hash passed to the :html key is equivalent to the options (2nd)
# The Hash passed to the <tt>:html</tt> key is equivalent to the options (2nd)
# argument in the FormTagHelper.form_tag method.
#
# By default the fall-through action is the same as the one specified in
# the :url (and the default method is :post).
# the <tt>:url</tt> (and the default method is <tt>:post</tt>).
#
# form_remote_tag also takes a block, like form_tag:
# # Generates:
@ -422,8 +422,8 @@ module ActionView
end
# Returns '<tt>eval(request.responseText)</tt>' which is the JavaScript function
# that form_remote_tag can call in :complete to evaluate a multiple
# update return document using update_element_function calls.
# that +form_remote_tag+ can call in <tt>:complete</tt> to evaluate a multiple
# update return document using +update_element_function+ calls.
def evaluate_remote_response
"eval(request.responseText)"
end

View file

@ -10,7 +10,7 @@ module ActionView
base.extend(ClassMethods)
end
# This #sanitize helper will html encode all tags and strip all attributes that aren't specifically allowed.
# This +sanitize+ helper will html encode all tags and strip all attributes that aren't specifically allowed.
# It also strips href/src tags with invalid protocols, like javascript: especially. It does its best to counter any
# tricks that hackers may use, like throwing in unicode/ascii/hex values to get past the javascript: filters. Check out
# the extensive test suite.
@ -18,7 +18,7 @@ module ActionView
# <%= sanitize @article.body %>
#
# You can add or remove tags/attributes if you want to customize it a bit. See ActionView::Base for full docs on the
# available options. You can add tags/attributes for single uses of #sanitize by passing either the :attributes or :tags options:
# available options. You can add tags/attributes for single uses of +sanitize+ by passing either the <tt>:attributes</tt> or <tt>:tags</tt> options:
#
# Normal Use
#

View file

@ -35,8 +35,8 @@ module ActionView
# This would fade the element that was dropped on the drop receiving
# element.
#
# For toggling visual effects, you can use :toggle_appear, :toggle_slide, and
# :toggle_blind which will alternate between appear/fade, slidedown/slideup, and
# For toggling visual effects, you can use <tt>:toggle_appear</tt>, <tt>:toggle_slide</tt>, and
# <tt>:toggle_blind</tt> which will alternate between appear/fade, slidedown/slideup, and
# blinddown/blindup respectively.
#
# You can change the behaviour with various options, see

View file

@ -16,7 +16,7 @@ module ActionView
# instead of the fully qualified URL like http://example.com/controller/action.
#
# When called from a view, url_for returns an HTML escaped url. If you
# need an unescaped url, pass :escape => false in the +options+.
# need an unescaped url, pass <tt>:escape => false</tt> in the +options+.
#
# ==== Options
# * <tt>:anchor</tt> -- specifies the anchor name to be appended to the path.
@ -25,8 +25,8 @@ module ActionView
# is currently not recommended since it breaks caching.
# * <tt>:host</tt> -- overrides the default (current) host if provided
# * <tt>:protocol</tt> -- overrides the default (current) protocol if provided
# * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if :password is also present)
# * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if :user is also present)
# * <tt>:user</tt> -- Inline HTTP authentication (only plucked out if <tt>:password</tt> is also present)
# * <tt>:password</tt> -- Inline HTTP authentication (only plucked out if <tt>:user</tt> is also present)
# * <tt>:escape</tt> -- Determines whether the returned URL will be HTML escaped or not (<tt>true</tt> by default)
#
# ==== Relying on named routes
@ -102,21 +102,21 @@ module ActionView
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
# in dangerous actions like deleting a record (which search bots can follow
# while spidering your site). Supported verbs are :post, :delete and :put.
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
# Note that if the user has JavaScript disabled, the request will fall back
# to using GET. If you are relying on the POST behavior, you should check
# for it in your controller's action by using the request object's methods
# for post?, delete? or put?.
# for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
# * The +html_options+ will accept a hash of html attributes for the link tag.
#
# Note that if the user has JavaScript disabled, the request will fall back
# to using GET. If :href=>'#' is used and the user has JavaScript disabled
# to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript disabled
# clicking the link will have no effect. If you are relying on the POST
# behavior, your should check for it in your controller's action by using the
# request object's methods for post?, delete? or put?.
# request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
#
# You can mix and match the +html_options+ with the exception of
# :popup and :method which will raise an ActionView::ActionViewError
# <tt>:popup</tt> and <tt>:method</tt> which will raise an ActionView::ActionViewError
# exception.
#
# ==== Examples

View file

@ -100,7 +100,7 @@ module ActionView
# Title: <%= chief.name %>
# </div>
#
# As you can see, the :locals hash is shared between both the partial and its layout.
# As you can see, the <tt>:locals</tt> hash is shared between both the partial and its layout.
module Partials
private
def render_partial(partial_path, object_assigns = nil, local_assigns = {}) #:nodoc:

View file

@ -10,7 +10,7 @@ module ActiveModel
DEFAULT_VALIDATION_OPTIONS = { :on => :save, :allow_nil => false, :allow_blank => false, :message => nil }.freeze
# Adds a validation method or block to the class. This is useful when
# overriding the #validate instance method becomes too unwieldly and
# overriding the +validate+ instance method becomes too unwieldly and
# you're looking for more descriptive declaration of your validations.
#
# This can be done with a symbol pointing to a method:
@ -35,8 +35,8 @@ module ActiveModel
# end
# end
#
# This usage applies to #validate_on_create and #validate_on_update as well.
# This usage applies to +validate_on_create+ and +validate_on_update as well+.
#
# Validates each attribute against a block.
#
# class Person < ActiveRecord::Base
@ -46,14 +46,14 @@ module ActiveModel
# end
#
# Options:
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>allow_nil</tt> - Skip validation if attribute is nil.
# * <tt>allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_each(*attrs)
options = attrs.extract_options!.symbolize_keys

View file

@ -8,22 +8,22 @@ module ActiveModel
# validates_acceptance_of :eula, :message => "must be abided"
# end
#
# If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
# performed only if terms_of_service is not nil and by default on save.
# If the database column does not exist, the <tt>:terms_of_service</tt> attribute is entirely virtual. This check is
# performed only if <tt>:terms_of_service</tt> is not +nil+ and by default on save.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "must be accepted")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
# * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
# makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database
# column, since the attribute is typecast from "1" to <tt>true</tt> before validation.
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "must be accepted")
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+. (default is +true+)
# * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
# makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
# column, since the attribute is typecasted from "1" to +true+ before validation.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# method, proc or string should return or evaluate to a true or false value.
def validates_acceptance_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
configuration.update(attr_names.extract_options!)

View file

@ -21,16 +21,16 @@ module ActiveModel
# ...this would specify a circular dependency and cause infinite recursion.
#
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
# is both present and guaranteed to be valid, you also need to use validates_presence_of.
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is invalid")
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
# * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_associated(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }

View file

@ -15,20 +15,20 @@ module ActiveModel
#
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
# only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
# only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
# check for the confirmation attribute:
#
# validates_presence_of :password_confirmation, :if => :password_changed?
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation")
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# method, proc or string should return or evaluate to a true or false value.
def validates_confirmation_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
configuration.update(attr_names.extract_options!)

View file

@ -10,15 +10,15 @@ module ActiveModel
# end
#
# Configuration options:
# * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
# * <tt>message</tt> - Specifies a custom error message (default is: "is reserved")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved")
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_exclusion_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }

View file

@ -8,21 +8,21 @@ module ActiveModel
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
# end
#
# Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
# A regular expression must be provided or else an exception will be raised.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is invalid")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
# * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!)
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_format_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }

View file

@ -10,15 +10,15 @@ module ActiveModel
# end
#
# Configuration options:
# * <tt>in</tt> - An enumerable object of available items
# * <tt>message</tt> - Specifies a custom error message (default is: "is not included in the list")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:in</tt> - An enumerable object of available items
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list")
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is null (default is: +false+)
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_inclusion_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }

View file

@ -6,35 +6,34 @@ module ActiveModel
# Validates that the specified attribute matches the length restrictions supplied. Only one option can be used at a time:
#
# class Person < ActiveRecord::Base
# validates_length_of :first_name, :maximum=>30
# validates_length_of :last_name, :maximum=>30, :message=>"less than %d if you don't mind"
# validates_length_of :first_name, :maximum => 30
# validates_length_of :last_name, :maximum => 30, :message => "less than %d if you don't mind"
# validates_length_of :fax, :in => 7..32, :allow_nil => true
# validates_length_of :phone, :in => 7..32, :allow_blank => true
# validates_length_of :user_name, :within => 6..20, :too_long => "pick a shorter name", :too_short => "pick a longer name"
# validates_length_of :fav_bra_size, :minimum=>1, :too_short=>"please enter at least %d character"
# validates_length_of :smurf_leader, :is=>4, :message=>"papa is spelled with %d characters... don't play me."
# validates_length_of :fav_bra_size, :minimum => 1, :too_short => "please enter at least %d character"
# validates_length_of :smurf_leader, :is => 4, :message => "papa is spelled with %d characters... don't play me."
# end
#
# Configuration options:
# * <tt>minimum</tt> - The minimum size of the attribute
# * <tt>maximum</tt> - The maximum size of the attribute
# * <tt>is</tt> - The exact size of the attribute
# * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
# * <tt>in</tt> - A synonym(or alias) for :within
# * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
# * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
#
# * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
# * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
# * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
# * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:minimum</tt> - The minimum size of the attribute
# * <tt>:maximum</tt> - The maximum size of the attribute
# * <tt>:is</tt> - The exact size of the attribute
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>:too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# method, proc or string should return or evaluate to a true or false value.
def validates_length_of(*attrs)
# Merge given options with defaults.
options = {

View file

@ -8,29 +8,29 @@ module ActiveModel
# Validates whether the value of the specified attribute is numeric by trying to convert it to
# a float with Kernel.Float (if <tt>integer</tt> is false) or applying it to the regular expression
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is set to true).
# <tt>/\A[\+\-]?\d+\Z/</tt> (if <tt>integer</tt> is true).
#
# class Person < ActiveRecord::Base
# validates_numericality_of :value, :on => :create
# end
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is not a number")
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
# * <tt>allow_nil</tt> Skip validation if attribute is nil (default is false). Notice that for fixnum and float columns empty strings are converted to nil
# * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
# * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
# * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
# * <tt>less_than</tt> Specifies the value must be less than the supplied value
# * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
# * <tt>odd</tt> Specifies the value must be an odd number
# * <tt>even</tt> Specifies the value must be an even number
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is not a number")
# * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is +false+)
# * <tt>:allow_nil</tt> Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+
# * <tt>:greater_than</tt> Specifies the value must be greater than the supplied value
# * <tt>:greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
# * <tt>:equal_to</tt> Specifies the value must be equal to the supplied value
# * <tt>:less_than</tt> Specifies the value must be less than the supplied value
# * <tt>:less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
# * <tt>:odd</tt> Specifies the value must be an odd number
# * <tt>:even</tt> Specifies the value must be an even number
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_numericality_of(*attr_names)
configuration = { :on => :save, :only_integer => false, :allow_nil => false }

View file

@ -7,22 +7,26 @@ module ActiveModel
# validates_presence_of :first_name
# end
#
# The first_name attribute must be in the object and it cannot be blank.
# The +first_name+ attribute must be in the object and it cannot be blank.
#
# If you want to validate the presence of a boolean field (where the real values are true and false),
# you will want to use validates_inclusion_of :field_name, :in => [true, false]
# This is due to the way Object#blank? handles boolean values. false.blank? # => true
# If you want to validate the presence of a boolean field (where the real values are +true+ and +false+),
# you will want to use
#
# validates_inclusion_of :field_name, :in => [true, false]
#
# This is due to the way Object#blank? handles boolean values:
#
# false.blank? # => true
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "can't be blank")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "can't be blank")
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
#
def validates_presence_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:blank], :on => :save }
configuration.update(attr_names.extract_options!)

View file

@ -23,16 +23,16 @@ module ActiveModel
# unique index on the field. See +add_index+ for more information.
#
# Configuration options:
# * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
# * <tt>scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
# * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (false by default).
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken")
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+false+ by default).
# * <tt>:allow_nil</tt> - If set to +true+, skips this validation if the attribute is +nil+ (default is: +false+)
# * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the attribute is blank (default is: +false+)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_uniqueness_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken] }

View file

@ -179,6 +179,16 @@ module ActiveRecord
end
end
# Loads the target if needed and returns it.
#
# This method is abstract in the sense that it relies on +find_target+,
# which is expected to be provided by descendants.
#
# If the target is already loaded it is just returned. Thus, you can call
# +load_target+ unconditionally to get the target.
#
# ActiveRecord::RecordNotFound is rescued within the method, and it is
# not reraised. The proxy is reset and +nil+ is the return value.
def load_target
return nil unless defined?(@loaded)

View file

@ -11,22 +11,18 @@ module ActiveRecord #:nodoc:
class SubclassNotFound < ActiveRecordError #:nodoc:
end
# Raised when object assigned to association is of incorrect type.
# Raised when an object assigned to an association has an incorrect type.
#
# Example:
# class Ticket < ActiveRecord::Base
# has_many :patches
# end
#
# class Ticket < ActiveRecord::Base
# has_many :patches
# end
# class Patch < ActiveRecord::Base
# belongs_to :ticket
# end
#
# class Patch < ActiveRecord::Base
# belongs_to :ticket
# end
#
# and somewhere in the code:
#
# @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
# @ticket.save
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
# @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
class AssociationTypeMismatch < ActiveRecordError
end
@ -59,14 +55,14 @@ module ActiveRecord #:nodoc:
class StatementInvalid < ActiveRecordError
end
# Raised when number of bind variables in statement given to :condition key (for example, when using +find+ method)
# Raised when number of bind variables in statement given to <tt>:condition</tt> key (for example, when using +find+ method)
# does not match number of expected variables.
#
# Example:
# For example, in
#
# Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
# Location.find :all, :conditions => ["lat = ? AND lng = ?", 53.7362]
#
# in example above two placeholders are given but only one variable to fill them.
# two placeholders are given but only one variable to fill them.
class PreparedStatementInvalid < ActiveRecordError
end
@ -97,8 +93,8 @@ module ActiveRecord #:nodoc:
end
# Raised when you've tried to access a column which wasn't
# loaded by your finder. Typically this is because :select
# has been specified
# loaded by your finder. Typically this is because <tt>:select</tt>
# has been specified.
class MissingAttributeError < NoMethodError
end
@ -206,7 +202,7 @@ module ActiveRecord #:nodoc:
# # Uses an integer of seconds to hold the length of the song
#
# def length=(minutes)
# write_attribute(:length, minutes * 60)
# write_attribute(:length, minutes.to_i * 60)
# end
#
# def length
@ -256,7 +252,7 @@ module ActiveRecord #:nodoc:
#
# It's even possible to use all the additional parameters to find. For example, the full interface for Payment.find_all_by_amount
# is actually Payment.find_all_by_amount(amount, options). And the full interface to Person.find_by_user_name is
# actually Person.find_by_user_name(user_name, options). So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
# actually <tt>Person.find_by_user_name(user_name, options)</tt>. So you could call <tt>Payment.find_all_by_amount(50, :order => "created_on")</tt>.
#
# The same dynamic finder style can be used to create the object if it doesn't already exist. This dynamic finder is called with
# <tt>find_or_create_by_</tt> and will return the object if it already exists and otherwise creates it, then returns it. Protected attributes won't be set unless they are given in a block. For example:
@ -457,9 +453,9 @@ module ActiveRecord #:nodoc:
# * <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 rows 0 through 4.
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
# or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s).
# or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
# If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
# Pass :readonly => false to override.
# Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt>: Names associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
# to already defined associations. See eager loading under Associations.
# * <tt>:select</tt>: By default, this is * as in SELECT * FROM, but can be changed if you, for example, want to do a join but not
@ -468,7 +464,7 @@ module ActiveRecord #:nodoc:
# of a database view).
# * <tt>:readonly</tt>: Mark the returned records read-only so they cannot be saved or updated.
# * <tt>:lock</tt>: An SQL fragment like "FOR UPDATE" or "LOCK IN SHARE MODE".
# :lock => true gives connection's default exclusive lock, usually "FOR UPDATE".
# <tt>:lock => true</tt> gives connection's default exclusive lock, usually "FOR UPDATE".
#
# Examples for find by id:
# Person.find(1) # returns the object for ID = 1
@ -478,7 +474,7 @@ module ActiveRecord #:nodoc:
# Person.find(1, :conditions => "administrator = 1", :order => "created_on DESC")
#
# Note that returned records may not be in the same order as the ids you
# provide since database rows are unordered. Give an explicit :order
# provide since database rows are unordered. Give an explicit <tt>:order</tt>
# to ensure the results are sorted.
#
# Examples for find first:
@ -711,7 +707,7 @@ module ActiveRecord #:nodoc:
# +updates+ A String of column and value pairs that will be set on any records that match conditions
# +conditions+ An SQL fragment like "administrator = 1" or [ "user_name = ?", username ].
# See conditions in the intro for more info.
# +options+ Additional options are :limit and/or :order, see the examples for usage.
# +options+ Additional options are <tt>:limit</tt> and/or <tt>:order</tt>, see the examples for usage.
#
# ==== Examples
#
@ -1521,7 +1517,7 @@ module ActiveRecord #:nodoc:
end
end
# The optional scope argument is for the current :find scope.
# The optional scope argument is for the current <tt>:find</tt> scope.
def add_limit!(sql, options, scope = :auto)
scope = scope(:find) if :auto == scope
@ -1533,15 +1529,15 @@ module ActiveRecord #:nodoc:
connection.add_limit_offset!(sql, options)
end
# The optional scope argument is for the current :find scope.
# The :lock option has precedence over a scoped :lock.
# The optional scope argument is for the current <tt>:find</tt> scope.
# The <tt>:lock</tt> option has precedence over a scoped <tt>:lock</tt>.
def add_lock!(sql, options, scope = :auto)
scope = scope(:find) if :auto == scope
options = options.reverse_merge(:lock => scope[:lock]) if scope
connection.add_lock!(sql, options)
end
# The optional scope argument is for the current :find scope.
# The optional scope argument is for the current <tt>:find</tt> scope.
def add_joins!(sql, options, scope = :auto)
scope = scope(:find) if :auto == scope
[(scope && scope[:joins]), options[:joins]].each do |join|
@ -1556,7 +1552,7 @@ module ActiveRecord #:nodoc:
end
# Adds a sanitized version of +conditions+ to the +sql+ string. Note that the passed-in +sql+ string is changed.
# The optional scope argument is for the current :find scope.
# The optional scope argument is for the current <tt>:find</tt> scope.
def add_conditions!(sql, conditions, scope = :auto)
scope = scope(:find) if :auto == scope
conditions = [conditions]
@ -1753,8 +1749,8 @@ module ActiveRecord #:nodoc:
protected
# Scope parameters to method calls within the block. Takes a hash of method_name => parameters hash.
# method_name may be :find or :create. :find parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
# <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. :create parameters are an attributes hash.
# method_name may be <tt>:find</tt> or <tt>:create</tt>. <tt>:find</tt> parameters may include the <tt>:conditions</tt>, <tt>:joins</tt>,
# <tt>:include</tt>, <tt>:offset</tt>, <tt>:limit</tt>, and <tt>:readonly</tt> options. <tt>:create</tt> parameters are an attributes hash.
#
# class Article < ActiveRecord::Base
# def self.create_with_scope
@ -1767,7 +1763,7 @@ module ActiveRecord #:nodoc:
# end
#
# In nested scopings, all previous parameters are overwritten by the innermost rule, with the exception of
# :conditions and :include options in :find, which are merged.
# <tt>:conditions</tt> and <tt>:include</tt> options in <tt>:find</tt>, which are merged.
#
# class Article < ActiveRecord::Base
# def self.find_with_scope
@ -2217,9 +2213,9 @@ module ActiveRecord #:nodoc:
record
end
# Returns an instance of the specified klass with the attributes of the current record. This is mostly useful in relation to
# Returns an instance of the specified +klass+ with the attributes of the current record. This is mostly useful in relation to
# single-table inheritance structures where you want a subclass to appear as the superclass. This can be used along with record
# identification in Action Pack to allow, say, Client < Company to do something like render :partial => @client.becomes(Company)
# identification in Action Pack to allow, say, <tt>Client < Company</tt> to do something like render <tt>:partial => @client.becomes(Company)</tt>
# to render that instance using the companies/company partial instead of clients/client.
#
# Note: The new instance will share a link to the same attributes as the original class. So any change to the attributes in either

View file

@ -9,16 +9,16 @@ module ActiveRecord
# Count operates using three different approaches.
#
# * Count all: By not passing any parameters to count, it will return a count of all the rows for the model.
# * Count using column : By passing a column name to count, it will return a count of all the rows for the model with supplied column present
# * Count using column: By passing a column name to count, it will return a count of all the rows for the model with supplied column present
# * Count using options will find the row count matched by the options used.
#
# The third approach, count using options, accepts an option hash as the only parameter. The options are:
#
# * <tt>:conditions</tt>: An SQL fragment like "administrator = 1" or [ "user_name = ?", username ]. See conditions in the intro.
# * <tt>:joins</tt>: Either an SQL fragment for additional joins like "LEFT JOIN comments ON comments.post_id = id" (rarely needed)
# or named associations in the same form used for the :include option, which will perform an INNER JOIN on the associated table(s).
# or named associations in the same form used for the <tt>:include</tt> option, which will perform an INNER JOIN on the associated table(s).
# If the value is a string, then the records will be returned read-only since they will have attributes that do not correspond to the table's columns.
# Pass :readonly => false to override.
# Pass <tt>:readonly => false</tt> to override.
# * <tt>:include</tt>: Named associations that should be loaded alongside using LEFT OUTER JOINs. The symbols named refer
# to already defined associations. When using named associations, count returns the number of DISTINCT items for the model you're counting.
# See eager loading under Associations.
@ -41,7 +41,7 @@ module ActiveRecord
# Person.count('id', :conditions => "age > 26") # Performs a COUNT(id)
# Person.count(:all, :conditions => "age > 26") # Performs a COUNT(*) (:all is an alias for '*')
#
# Note: Person.count(:all) will not work because it will use :all as the condition. Use Person.count instead.
# Note: <tt>Person.count(:all)</tt> will not work because it will use <tt>:all</tt> as the condition. Use Person.count instead.
def count(*args)
calculate(:count, *construct_count_options_from_args(*args))
end
@ -75,11 +75,11 @@ module ActiveRecord
end
# This calculates aggregate values in the given column. Methods for count, sum, average, minimum, and maximum have been added as shortcuts.
# Options such as :conditions, :order, :group, :having, and :joins can be passed to customize the query.
# Options such as <tt>:conditions</tt>, <tt>:order</tt>, <tt>:group</tt>, <tt>:having</tt>, and <tt>:joins</tt> can be passed to customize the query.
#
# There are two basic forms of output:
# * Single aggregate value: The single value is type cast to Fixnum for COUNT, Float for AVG, and the given column's type for everything else.
# * Grouped values: This returns an ordered hash of the values and groups them by the :group option. It takes either a column name, or the name
# * Grouped values: This returns an ordered hash of the values and groups them by the <tt>:group</tt> option. It takes either a column name, or the name
# of a belongs_to association.
#
# values = Person.maximum(:age, :group => 'last_name')

View file

@ -175,7 +175,7 @@ module ActiveRecord
end
# Establishes the connection to the database. Accepts a hash as input where
# the :adapter key must be specified with the name of a database adapter (in lower-case)
# the <tt>:adapter</tt> key must be specified with the name of a database adapter (in lower-case)
# example for regular databases (MySQL, Postgresql, etc):
#
# ActiveRecord::Base.establish_connection(
@ -194,6 +194,7 @@ module ActiveRecord
# )
#
# Also accepts keys as strings (for parsing from yaml for example):
#
# ActiveRecord::Base.establish_connection(
# "adapter" => "sqlite",
# "database" => "path/to/dbfile"

View file

@ -398,8 +398,8 @@ module ActiveRecord
# TableDefinition#timestamps that'll add created_at and updated_at as datetimes.
#
# TableDefinition#references will add an appropriately-named _id column, plus a corresponding _type
# column if the :polymorphic option is supplied. If :polymorphic is a hash of options, these will be
# used when creating the _type column. So what can be written like this:
# column if the <tt>:polymorphic</tt> option is supplied. If <tt>:polymorphic</tt> is a hash of options, these will be
# used when creating the <tt>_type</tt> column. So what can be written like this:
#
# create_table :taggings do |t|
# t.integer :tag_id, :tagger_id, :taggable_id

View file

@ -45,7 +45,7 @@ module ActiveRecord
# The +options+ hash can include the following keys:
# [<tt>:id</tt>]
# Whether to automatically add a primary key column. Defaults to true.
# Join tables for has_and_belongs_to_many should set :id => false.
# Join tables for +has_and_belongs_to_many+ should set <tt>:id => false</tt>.
# [<tt>:primary_key</tt>]
# The name of the primary key, if one is to be added automatically.
# Defaults to +id+.

View file

@ -365,7 +365,7 @@ module ActiveRecord
create_database(name)
end
# Create a new MySQL database with optional :charset and :collation.
# Create a new MySQL database with optional <tt>:charset</tt> and <tt>:collation</tt>.
# Charset defaults to utf8.
#
# Example:

View file

@ -233,7 +233,7 @@ module ActiveRecord
# * <tt>:username</tt> -- Defaults to nothing
# * <tt>:password</tt> -- Defaults to nothing
# * <tt>:database</tt> -- The name of the database. No default, must be provided.
# * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the :schema_order option.
# * <tt>:schema_search_path</tt> -- An optional schema search path for the connection given as a string of comma-separated schema names. This is backward-compatible with the <tt>:schema_order</tt> option.
# * <tt>:encoding</tt> -- An optional client encoding that is used in a SET client_encoding TO <encoding> call on the connection.
# * <tt>:min_messages</tt> -- An optional client min messages that is used in a SET client_min_messages TO <min_messages> call on the connection.
# * <tt>:allow_concurrency</tt> -- If true, use async query methods so Ruby threads don't deadlock; otherwise, use blocking query methods.
@ -479,9 +479,9 @@ module ActiveRecord
create_database(name)
end
# Create a new PostgreSQL database. Options include :owner, :template,
# :encoding, :tablespace, and :connection_limit (note that MySQL uses
# :charset while PostgreSQL uses :encoding).
# Create a new PostgreSQL database. Options include <tt>:owner</tt>, <tt>:template</tt>,
# <tt>:encoding</tt>, <tt>:tablespace</tt>, and <tt>:connection_limit</tt> (note that MySQL uses
# <tt>:charset</tt> while PostgreSQL uses <tt>:encoding</tt>).
#
# Example:
# create_database config[:database], config

View file

@ -25,12 +25,12 @@ module ActiveRecord
# Locking::Pessimistic provides support for row-level locking using
# SELECT ... FOR UPDATE and other lock types.
#
# Pass :lock => true to ActiveRecord::Base.find to obtain an exclusive
# Pass <tt>:lock => true</tt> to ActiveRecord::Base.find to obtain an exclusive
# lock on the selected rows:
# # select * from accounts where id=1 for update
# Account.find(1, :lock => true)
#
# Pass :lock => 'some locking clause' to give a database-specific locking clause
# Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'.
#
# Example:

View file

@ -76,16 +76,16 @@ module ActiveRecord
# * <tt>rename_table(old_name, new_name)</tt>: Renames the table called +old_name+ to +new_name+.
# * <tt>add_column(table_name, column_name, type, options)</tt>: Adds a new column to the table called +table_name+
# named +column_name+ specified to be one of the following types:
# :string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time,
# :date, :binary, :boolean. A default value can be specified by passing an
# +options+ hash like { :default => 11 }. Other options include :limit and :null (e.g. { :limit => 50, :null => false })
# <tt>:string</tt>, <tt>:text</tt>, <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>,
# <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. A default value can be specified by passing an
# +options+ hash like <tt>{ :default => 11 }</tt>. Other options include <tt>:limit</tt> and <tt>:null</tt> (e.g. <tt>{ :limit => 50, :null => false }</tt>)
# -- see ActiveRecord::ConnectionAdapters::TableDefinition#column for details.
# * <tt>rename_column(table_name, column_name, new_column_name)</tt>: Renames a column but keeps the type and content.
# * <tt>change_column(table_name, column_name, type, options)</tt>: Changes the column to a different type using the same
# parameters as add_column.
# * <tt>remove_column(table_name, column_name)</tt>: Removes the column named +column_name+ from the table called +table_name+.
# * <tt>add_index(table_name, column_names, options)</tt>: Adds a new index with the name of the column. Other options include
# :name and :unique (e.g. { :name => "users_name_index", :unique => true }).
# <tt>:name</tt> and <tt>:unique</tt> (e.g. <tt>{ :name => "users_name_index", :unique => true }</tt>).
# * <tt>remove_index(table_name, index_name)</tt>: Removes the index specified by +index_name+.
#
# == Irreversible transformations

View file

@ -45,7 +45,7 @@ module ActiveRecord
end
# Returns an array of AssociationReflection objects for all the associations in the class. If you only want to reflect on a
# certain association type, pass in the symbol (:has_many, :has_one, :belongs_to) for that as the first parameter.
# certain association type, pass in the symbol (<tt>:has_many</tt>, <tt>:has_one</tt>, <tt>:belongs_to</tt>) for that as the first parameter.
# Example:
#
# Account.reflect_on_all_associations # returns an array of all associations
@ -90,13 +90,12 @@ module ActiveRecord
# Returns the hash of options used for the macro. For example, it would return <tt>{ :class_name => "Money" }</tt> for
# <tt>composed_of :balance, :class_name => 'Money'</tt> or +{}+ for <tt>has_many :clients</tt>.
def options
@options
end
# Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the +Money+
# class and <tt>has_many :clients</tt> returns the +Client+ class.
# Returns the class for the macro. For example, <tt>composed_of :balance, :class_name => 'Money'</tt> returns the Money
# class and <tt>has_many :clients</tt> returns the Client class.
def klass
@klass ||= class_name.constantize
end
@ -158,16 +157,16 @@ module ActiveRecord
@through_reflection ||= options[:through] ? active_record.reflect_on_association(options[:through]) : false
end
# Gets an array of possible :through source reflection names
# Gets an array of possible <tt>:through</tt> source reflection names:
#
# [singularized, pluralized]
# [:singularized, :pluralized]
#
def source_reflection_names
@source_reflection_names ||= (options[:source] ? [options[:source]] : [name.to_s.singularize, name]).collect { |n| n.to_sym }
end
# Gets the source of the through reflection. It checks both a singularized and pluralized form for :belongs_to or :has_many.
# (The :tags association on Tagging below)
# Gets the source of the through reflection. It checks both a singularized and pluralized form for <tt>:belongs_to</tt> or <tt>:has_many</tt>.
# (The <tt>:tags</tt> association on Tagging below.)
#
# class Post
# has_many :tags, :through => :taggings

View file

@ -8,11 +8,11 @@ module ActiveRecord #:nodoc:
end
# To replicate the behavior in ActiveRecord#attributes,
# :except takes precedence over :only. If :only is not set
# <tt>:except</tt> takes precedence over <tt>:only</tt>. If <tt>:only</tt> is not set
# for a N level model but is set for the N+1 level models,
# then because :except is set to a default value, the second
# level model can have both :except and :only set. So if
# :only is set, always delete :except.
# then because <tt>:except</tt> is set to a default value, the second
# level model can have both <tt>:except</tt> and <tt>:only</tt> set. So if
# <tt>:only</tt> is set, always delete <tt>:except</tt>.
def serializable_attribute_names
attribute_names = @record.attribute_names
@ -38,7 +38,7 @@ module ActiveRecord #:nodoc:
serializable_attribute_names + serializable_method_names
end
# Add associations specified via the :includes option.
# Add associations specified via the <tt>:includes</tt> option.
# Expects a block that takes as arguments:
# +association+ - name of the association
# +records+ - the association record(s) to be serialized

View file

@ -16,8 +16,8 @@ module ActiveRecord #:nodoc:
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true}
#
# The :only and :except options can be used to limit the attributes
# included, and work similar to the #attributes method. For example:
# The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the attributes
# included, and work similar to the +attributes+ method. For example:
#
# konata.to_json(:only => [ :id, :name ])
# # => {"id": 1, "name": "Konata Izumi"}
@ -25,14 +25,14 @@ module ActiveRecord #:nodoc:
# konata.to_json(:except => [ :id, :created_at, :age ])
# # => {"name": "Konata Izumi", "awesome": true}
#
# To include any methods on the model, use :methods.
# To include any methods on the model, use <tt>:methods</tt>.
#
# konata.to_json(:methods => :permalink)
# # => {"id": 1, "name": "Konata Izumi", "age": 16,
# "created_at": "2006/08/01", "awesome": true,
# "permalink": "1-konata-izumi"}
#
# To include associations, use :include.
# To include associations, use <tt>:include</tt>.
#
# konata.to_json(:include => :posts)
# # => {"id": 1, "name": "Konata Izumi", "age": 16,

View file

@ -2,7 +2,7 @@ module ActiveRecord #:nodoc:
module Serialization
# Builds an XML document to represent the model. Some configuration is
# available through +options+. However more complicated cases should
# override ActiveRecord's to_xml method.
# override ActiveRecord::Base#to_xml.
#
# By default the generated XML document will include the processing
# instruction and all the object's attributes. For example:
@ -22,12 +22,12 @@ module ActiveRecord #:nodoc:
# <last-read type="date">2004-04-15</last-read>
# </topic>
#
# This behavior can be controlled with :only, :except,
# :skip_instruct, :skip_types and :dasherize. The :only and
# :except options are the same as for the #attributes method.
# The default is to dasherize all column names, to disable this,
# set :dasherize to false. To not have the column type included
# in the XML output, set :skip_types to true.
# This behavior can be controlled with <tt>:only</tt>, <tt>:except</tt>,
# <tt>:skip_instruct</tt>, <tt>:skip_types</tt> and <tt>:dasherize</tt>.
# The <tt>:only</tt> and <tt>:except</tt> options are the same as for the
# +attributes+ method. The default is to dasherize all column names, but you
# can disable this setting <tt>:dasherize</tt> to +false+. To not have the
# column type included in the XML output set <tt>:skip_types</tt> to +true+.
#
# For instance:
#
@ -43,7 +43,7 @@ module ActiveRecord #:nodoc:
# <last-read type="date">2004-04-15</last-read>
# </topic>
#
# To include first level associations use :include
# To include first level associations use <tt>:include</tt>:
#
# firm.to_xml :include => [ :account, :clients ]
#
@ -98,7 +98,7 @@ module ActiveRecord #:nodoc:
# </account>
# </firm>
#
# To include any methods on the object(s) being called use :methods
# To include any methods on the model being called use <tt>:methods</tt>:
#
# firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
#
@ -108,9 +108,8 @@ module ActiveRecord #:nodoc:
# <real-earnings>5</real-earnings>
# </firm>
#
# To call any Procs on the object(s) use :procs. The Procs
# are passed a modified version of the options hash that was
# given to #to_xml.
# To call any additional Procs use <tt>:procs</tt>. The Procs are passed a
# modified version of the options hash that was given to +to_xml+:
#
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
# firm.to_xml :procs => [ proc ]
@ -120,7 +119,7 @@ module ActiveRecord #:nodoc:
# <abc>def</abc>
# </firm>
#
# Alternatively, you can yield the builder object as part of the to_xml call:
# Alternatively, you can yield the builder object as part of the +to_xml+ call:
#
# firm.to_xml do |xml|
# xml.creator do
@ -137,8 +136,9 @@ module ActiveRecord #:nodoc:
# </creator>
# </firm>
#
# You can override the to_xml method in your ActiveRecord::Base
# subclasses if you need to. The general form of doing this is:
# As noted above, you may override +to_xml+ in your ActiveRecord::Base
# subclasses to have complete control about what's generated. The general
# form of doing this is:
#
# class IHaveMyOwnXML < ActiveRecord::Base
# def to_xml(options = {})

View file

@ -201,7 +201,7 @@ module ActiveRecord
alias_method :count, :size
alias_method :length, :size
# Return an XML representation of this error object.
# Returns an XML representation of this error object.
#
# class Company < ActiveRecord::Base
# validates_presence_of :name, :address, :email
@ -266,7 +266,7 @@ module ActiveRecord
# person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
# person.save # => true (and person is now saved in the database)
#
# An +Errors+ object is automatically created for every Active Record.
# An Errors object is automatically created for every Active Record.
#
# Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.
module Validations
@ -286,7 +286,7 @@ module ActiveRecord
# All of the following validations are defined in the class scope of the model that you're interested in validating.
# They offer a more declarative way of specifying when the model is valid and when it is not. It is recommended to use
# these over the low-level calls to validate and validate_on_create when possible.
# these over the low-level calls to +validate+ and +validate_on_create+ when possible.
module ClassMethods
DEFAULT_VALIDATION_OPTIONS = {
:on => :save,
@ -337,14 +337,14 @@ module ActiveRecord
# end
#
# Options:
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>allow_nil</tt> - Skip validation if attribute is nil.
# * <tt>allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_each(*attrs)
options = attrs.extract_options!.symbolize_keys
@ -374,19 +374,19 @@ module ActiveRecord
#
# The added +password_confirmation+ attribute is virtual; it exists only as an in-memory attribute for validating the password.
# To achieve this, the validation adds accessors to the model for the confirmation attribute. NOTE: This check is performed
# only if +password_confirmation+ is not nil, and by default only on save. To require confirmation, make sure to add a presence
# only if +password_confirmation+ is not +nil+, and by default only on save. To require confirmation, make sure to add a presence
# check for the confirmation attribute:
#
# validates_presence_of :password_confirmation, :if => :password_changed?
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "doesn't match confirmation")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "doesn't match confirmation").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_confirmation_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:confirmation], :on => :save }
@ -406,21 +406,21 @@ module ActiveRecord
# validates_acceptance_of :eula, :message => "must be abided"
# end
#
# If the database column does not exist, the terms_of_service attribute is entirely virtual. This check is
# performed only if terms_of_service is not nil and by default on save.
# If the database column does not exist, the +terms_of_service+ attribute is entirely virtual. This check is
# performed only if +terms_of_service+ is not +nil+ and by default on save.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "must be accepted")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>allow_nil</tt> - Skip validation if attribute is nil. (default is true)
# * <tt>accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
# makes it easy to relate to an HTML checkbox. This should be set to 'true' if you are validating a database
# column, since the attribute is typecast from "1" to <tt>true</tt> before validation.
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "must be accepted").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is true).
# * <tt>:accept</tt> - Specifies value that is considered accepted. The default value is a string "1", which
# makes it easy to relate to an HTML checkbox. This should be set to +true+ if you are validating a database
# column, since the attribute is typecast from "1" to +true+ before validation.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_acceptance_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:accepted], :on => :save, :allow_nil => true, :accept => "1" }
@ -452,8 +452,8 @@ module ActiveRecord
# This is due to the way Object#blank? handles boolean values. false.blank? # => true
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "can't be blank")
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>message</tt> - A custom error message (default is: "can't be blank").
# * <tt>on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# method, proc or string should return or evaluate to a true or false value.
@ -485,24 +485,24 @@ module ActiveRecord
# end
#
# Configuration options:
# * <tt>minimum</tt> - The minimum size of the attribute
# * <tt>maximum</tt> - The maximum size of the attribute
# * <tt>is</tt> - The exact size of the attribute
# * <tt>within</tt> - A range specifying the minimum and maximum size of the attribute
# * <tt>in</tt> - A synonym(or alias) for :within
# * <tt>allow_nil</tt> - Attribute may be nil; skip validation.
# * <tt>allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:minimum</tt> - The minimum size of the attribute.
# * <tt>:maximum</tt> - The maximum size of the attribute.
# * <tt>:is</tt> - The exact size of the attribute.
# * <tt>:within</tt> - A range specifying the minimum and maximum size of the attribute.
# * <tt>:in</tt> - A synonym(or alias) for <tt>:within</tt>.
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
#
# * <tt>too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)")
# * <tt>too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)")
# * <tt>wrong_length</tt> - The error message if using the :is method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)")
# * <tt>message</tt> - The error message to use for a :minimum, :maximum, or :is violation. An alias of the appropriate too_long/too_short/wrong_length message
# * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:too_long</tt> - The error message if the attribute goes over the maximum (default is: "is too long (maximum is %d characters)").
# * <tt>:too_short</tt> - The error message if the attribute goes under the minimum (default is: "is too short (min is %d characters)").
# * <tt>:wrong_length</tt> - The error message if using the <tt>:is</tt> method and the attribute is the wrong size (default is: "is the wrong length (should be %d characters)").
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_length_of(*attrs)
# Merge given options with defaults.
@ -584,16 +584,16 @@ module ActiveRecord
# unique index on the field. See +add_index+ for more information.
#
# Configuration options:
# * <tt>message</tt> - Specifies a custom error message (default is: "has already been taken")
# * <tt>scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
# * <tt>case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (true by default).
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - Specifies a custom error message (default is: "has already been taken").
# * <tt>:scope</tt> - One or more columns by which to limit the scope of the uniqueness constraint.
# * <tt>:case_sensitive</tt> - Looks for an exact match. Ignored by non-text columns (+false+ by default).
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_uniqueness_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:taken], :case_sensitive => true }
@ -669,21 +669,21 @@ module ActiveRecord
# validates_format_of :email, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i, :on => :create
# end
#
# Note: use \A and \Z to match the start and end of the string, ^ and $ match the start/end of a line.
# Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
# A regular expression must be provided or else an exception will be raised.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is invalid")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>with</tt> - The regular expression used to validate the format with (note: must be supplied!)
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:with</tt> - The regular expression used to validate the format with (note: must be supplied!).
# * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_format_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
@ -705,15 +705,15 @@ module ActiveRecord
# end
#
# Configuration options:
# * <tt>in</tt> - An enumerable object of available items
# * <tt>message</tt> - Specifies a custom error message (default is: "is not included in the list")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:in</tt> - An enumerable object of available items.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is not included in the list").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_inclusion_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:inclusion], :on => :save }
@ -737,15 +737,15 @@ module ActiveRecord
# end
#
# Configuration options:
# * <tt>in</tt> - An enumerable object of items that the value shouldn't be part of
# * <tt>message</tt> - Specifies a custom error message (default is: "is reserved")
# * <tt>allow_nil</tt> - If set to true, skips this validation if the attribute is null (default is: false)
# * <tt>allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is: false)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't be part of.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is reserved").
# * <tt>:allow_nil</tt> - If set to true, skips this validation if the attribute is +nil+ (default is +false+).
# * <tt>:allow_blank</tt> - If set to true, skips this validation if the attribute is blank (default is +false+).
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_exclusion_of(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:exclusion], :on => :save }
@ -777,19 +777,19 @@ module ActiveRecord
# validates_associated :book
# end
#
# ...this would specify a circular dependency and cause infinite recursion.
# this would specify a circular dependency and cause infinite recursion.
#
# NOTE: This validation will not fail if the association hasn't been assigned. If you want to ensure that the association
# is both present and guaranteed to be valid, you also need to use validates_presence_of.
# is both present and guaranteed to be valid, you also need to use +validates_presence_of+.
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is invalid")
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is invalid")
# * <tt>:on</tt> Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_associated(*attr_names)
configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save }
@ -810,22 +810,22 @@ module ActiveRecord
# end
#
# Configuration options:
# * <tt>message</tt> - A custom error message (default is: "is not a number")
# * <tt>on</tt> Specifies when this validation is active (default is :save, other options :create, :update)
# * <tt>only_integer</tt> Specifies whether the value has to be an integer, e.g. an integral value (default is false)
# * <tt>allow_nil</tt> Skip validation if attribute is nil (default is false). Notice that for fixnum and float columns empty strings are converted to nil
# * <tt>greater_than</tt> Specifies the value must be greater than the supplied value
# * <tt>greater_than_or_equal_to</tt> Specifies the value must be greater than or equal the supplied value
# * <tt>equal_to</tt> Specifies the value must be equal to the supplied value
# * <tt>less_than</tt> Specifies the value must be less than the supplied value
# * <tt>less_than_or_equal_to</tt> Specifies the value must be less than or equal the supplied value
# * <tt>odd</tt> Specifies the value must be an odd number
# * <tt>even</tt> Specifies the value must be an even number
# * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
# * <tt>:message</tt> - A custom error message (default is: "is not a number").
# * <tt>:on</tt> - Specifies when this validation is active (default is <tt>:save</tt>, other options <tt>:create</tt>, <tt>:update</tt>).
# * <tt>:only_integer</tt> - Specifies whether the value has to be an integer, e.g. an integral value (default is +false+).
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is +false+). Notice that for fixnum and float columns empty strings are converted to +nil+.
# * <tt>:greater_than</tt> - Specifies the value must be greater than the supplied value.
# * <tt>:greater_than_or_equal_to</tt> - Specifies the value must be greater than or equal the supplied value.
# * <tt>:equal_to</tt> - Specifies the value must be equal to the supplied value.
# * <tt>:less_than</tt> - Specifies the value must be less than the supplied value.
# * <tt>:less_than_or_equal_to</tt> - Specifies the value must be less than or equal the supplied value.
# * <tt>:odd</tt> - Specifies the value must be an odd number.
# * <tt>:even</tt> - Specifies the value must be an even number.
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if the validation should
# occur (e.g. <tt>:if => :allow_validation</tt>, or <tt>:if => Proc.new { |user| user.signup_step > 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
# * <tt>unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. :unless => :skip_validation, or :unless => Proc.new { |user| user.signup_step <= 2 }). The
# * <tt>:unless</tt> - Specifies a method, proc or string to call to determine if the validation should
# not occur (e.g. <tt>:unless => :skip_validation</tt>, or <tt>:unless => Proc.new { |user| user.signup_step <= 2 }</tt>). The
# method, proc or string should return or evaluate to a true or false value.
def validates_numericality_of(*attr_names)
configuration = { :on => :save, :only_integer => false, :allow_nil => false }
@ -922,7 +922,7 @@ module ActiveRecord
save(false)
end
# Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.
# Runs +validate+ and +validate_on_create+ or +validate_on_update+ and returns true if no errors were added otherwise false.
def valid?
errors.clear
@ -946,7 +946,7 @@ module ActiveRecord
end
protected
# Overwrite this method for validation checks on all saves and use Errors.add(field, msg) for invalid attributes.
# Overwrite this method for validation checks on all saves and use <tt>Errors.add(field, msg)</tt> for invalid attributes.
def validate #:doc:
end

View file

@ -457,13 +457,14 @@ module ActiveResource
# The first argument is considered to be the scope of the query. That is, how many
# resources are returned from the request. It can be one of the following.
#
# +:one+:: Returns a single resource.
# +:first+:: Returns the first resource found.
# +:all+:: Returns every resource that matches the request.
# * <tt>:one</tt>: Returns a single resource.
# * <tt>:first</tt>: Returns the first resource found.
# * <tt>:all</tt>: Returns every resource that matches the request.
#
# ==== Options
# +from+:: Sets the path or custom method that resources will be fetched from.
# +params+:: Sets query and prefix (nested URL) parameters.
#
# * +from+: Sets the path or custom method that resources will be fetched from.
# * +params+: Sets query and prefix (nested URL) parameters.
#
# ==== Examples
# Person.find(1)

View file

@ -128,8 +128,8 @@ module ActiveResource
end
# Execute a HEAD request.
# Used to ...
def head(path, headers= {})
# Used to obtain meta-information about resources, such as whether they exist and their size (via response headers).
def head(path, headers = {})
request(:head, path, build_request_headers(headers))
end

View file

@ -49,7 +49,7 @@ module ActiveSupport
self
end
# Pass :force => true to force a cache miss.
# Pass <tt>:force => true</tt> to force a cache miss.
def fetch(key, options = {})
@logger_off = true
if !options[:force] && value = read(key, options)

View file

@ -67,17 +67,35 @@ module ActiveSupport #:nodoc:
end
end
# Returns a string that represents this array in XML by sending
# <tt>to_xml</tt> to each element.
# Returns a string that represents this array in XML by sending +to_xml+
# to each element. Active Record collections delegate their representation
# in XML to this method.
#
# All elements are expected to respond to <tt>to_xml</tt>, if any of
# them does not an exception is raised.
# All elements are expected to respond to +to_xml+, if any of them does
# not an exception is raised.
#
# The root node reflects the class name of the first element in plural
# if all elements belong to the same type and that's not <tt>Hash</tt>.
# Otherwise the root element is "records".
# if all elements belong to the same type and that's not Hash:
#
# Root children have as node name the one of the root singularized.
# customer.projects.to_xml
#
# <?xml version="1.0" encoding="UTF-8"?>
# <projects type="array">
# <project>
# <amount type="decimal">20000.0</amount>
# <customer-id type="integer">1567</customer-id>
# <deal-date type="date">2008-04-09</deal-date>
# ...
# </project>
# <project>
# <amount type="decimal">57230.0</amount>
# <customer-id type="integer">1567</customer-id>
# <deal-date type="date">2008-04-15</deal-date>
# ...
# </project>
# </projects>
#
# Otherwise the root element is "records":
#
# [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
#
@ -92,9 +110,26 @@ module ActiveSupport #:nodoc:
# </record>
# </records>
#
# If the collection is empty the root element is "nil-classes" by default:
#
# [].to_xml
#
# <?xml version="1.0" encoding="UTF-8"?>
# <nil-classes type="array"/>
#
# To ensure a meaningful root element use the <tt>:root</tt> option:
#
# customer_with_no_projects.projects.to_xml(:root => "projects")
#
# <?xml version="1.0" encoding="UTF-8"?>
# <projects type="array"/>
#
# By default root children have as node name the one of the root
# singularized. You can change it with the <tt>:children</tt> option.
#
# The +options+ hash is passed downwards:
#
# [Message.find(:first)].to_xml(:skip_types => true)
# Message.all.to_xml(:skip_types => true)
#
# <?xml version="1.0" encoding="UTF-8"?>
# <messages>

View file

@ -1,6 +1,12 @@
# Extends the class object with class and instance accessors for class attributes,
# just like the native attr* accessors for instance attributes.
class Class # :nodoc:
#
# class Person
# cattr_accessor :hair_colors
# end
#
# Person.hair_colors = [:brown, :black, :blonde, :red]
class Class
def cattr_reader(*syms)
syms.flatten.each do |sym|
next if sym.is_a?(Hash)

View file

@ -70,7 +70,7 @@ module ActiveSupport #:nodoc:
end
# Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
# any of these keys: :years, :months, :weeks, :days.
# any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
def advance(options)
d = self
d = d >> options.delete(:years) * 12 if options[:years]

View file

@ -42,8 +42,10 @@ module ActiveSupport #:nodoc:
)
end
# Uses Date to provide precise Time calculations for years, months, and days. The +options+ parameter takes a hash with
# any of these keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds.
# Uses Date to provide precise Time calculations for years, months, and days.
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
# <tt>:minutes</tt>, <tt>:seconds</tt>.
def advance(options)
d = to_date.advance(options)
datetime_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)

View file

@ -8,7 +8,7 @@ module Enumerable
# Example:
#
# latest_transcripts.group_by(&:day).each do |day, transcripts|
# p "#{day} -> #{transcripts.map(&:class) * ', '}"
# p "#{day} -> #{transcripts.map(&:class).join(', ')}"
# end
# "2006-03-01 -> Transcript"
# "2006-02-28 -> Transcript"
@ -26,21 +26,22 @@ module Enumerable
# Calculates a sum from the elements. Examples:
#
# payments.sum { |p| p.price * p.tax_rate }
# payments.sum(&:price)
# payments.sum { |p| p.price * p.tax_rate }
# payments.sum(&:price)
#
# This is instead of
# The latter is a shortcut for:
#
# payments.inject { |sum, p| sum + p.price }
# payments.inject { |sum, p| sum + p.price }
#
# Also calculates sums without the use of a block:
# It can also calculate the sum without the use of a block.
#
# [5, 15, 10].sum # => 30
# [5, 15, 10].sum # => 30
# ["foo", "bar"].sum # => "foobar"
# [[1, 2], [3, 1, 5]].sum => [1, 2, 3, 1, 5]
#
# The default identity (sum of an empty list) is zero.
# However, you can override this default:
# The default sum of an empty list is zero. You can override this default:
#
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
# [].sum(Payment.new(0)) { |i| i.amount } # => Payment.new(0)
#
def sum(identity = 0, &block)
return identity unless size > 0

View file

@ -8,7 +8,7 @@ module ActiveSupport #:nodoc:
# options.reverse_merge! :size => 25, :velocity => 10
# end
#
# The default :size and :velocity is only set if the +options+ passed in doesn't already have those keys set.
# The default <tt>:size</tt> and <tt>:velocity</tt> is only set if the +options+ passed in doesn't already have those keys set.
module ReverseMerge
# Performs the opposite of merge, with the keys and values from the first hash taking precedence over the second.
def reverse_merge(other_hash)

View file

@ -1,6 +1,16 @@
# Extends the module object with module and instance accessors for class attributes,
# just like the native attr* accessors for instance attributes.
class Module # :nodoc:
#
# module AppConfiguration
# mattr_accessor :google_api_key
# self.google_api_key = "123456789"
#
# mattr_accessor :paypal_url
# self.paypal_url = "www.sandbox.paypal.com"
# end
#
# AppConfiguration.google_api_key = "overriding the api key!"
class Module
def mattr_reader(*syms)
syms.each do |sym|
next if sym.is_a?(Hash)

View file

@ -1,8 +1,8 @@
class Module
# Provides a delegate class method to easily expose contained objects' methods
# as your own. Pass one or more methods (specified as symbols or strings)
# and the name of the target object as the final :to option (also a symbol
# or string). At least one method and the :to option are required.
# and the name of the target object as the final <tt>:to</tt> option (also a symbol
# or string). At least one method and the <tt>:to</tt> option are required.
#
# Delegation is particularly useful with Active Record associations:
#
@ -20,6 +20,7 @@ class Module
# Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>
#
# Multiple delegates to the same target are allowed:
#
# class Foo < ActiveRecord::Base
# belongs_to :greeter
# delegate :hello, :goodbye, :to => :greeter
@ -28,7 +29,8 @@ class Module
# Foo.new.goodbye # => "goodbye"
#
# Methods can be delegated to instance variables, class variables, or constants
# by providing the variable as a symbol:
# by providing them as a symbols:
#
# class Foo
# CONSTANT_ARRAY = [0,1,2,3]
# @@class_array = [4,5,6,7]

View file

@ -7,6 +7,14 @@ module ActiveSupport #:nodoc:
base.alias_method_chain :include?, :range
end
# Extends the default Range#include? to support range comparisons.
# (1..5).include?(1..5) # => true
# (1..5).include?(2..3) # => true
# (1..5).include?(2..6) # => false
#
# The native Range#include? behavior is untouched.
# ("a".."f").include?("c") # => true
# (5..9).include?(11) # => false
def include_with_range?(value)
if value.is_a?(::Range)
operator = exclude_end? ? :< : :<=

View file

@ -3,6 +3,9 @@ module ActiveSupport #:nodoc:
module Range #:nodoc:
# Check if Ranges overlap.
module Overlaps
# Compare two ranges and see if they overlap eachother
# (1..5).overlaps?(4..6) # => true
# (1..5).overlaps?(7..9) # => false
def overlaps?(other)
include?(other.first) || other.include?(first)
end

View file

@ -46,12 +46,12 @@ module ActiveSupport #:nodoc:
::DateTime.civil(year, month, day, hour, min, sec, offset)
end
# wraps class method time_with_datetime_fallback with utc_or_local == :utc
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>.
def utc_time(*args)
time_with_datetime_fallback(:utc, *args)
end
# wraps class method time_with_datetime_fallback with utc_or_local == :local
# Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>.
def local_time(*args)
time_with_datetime_fallback(:local, *args)
end
@ -78,8 +78,10 @@ module ActiveSupport #:nodoc:
)
end
# Uses Date to provide precise Time calculations for years, months, and days. The +options+ parameter takes a hash with
# any of these keys: :years, :months, :weeks, :days, :hours, :minutes, :seconds.
# Uses Date to provide precise Time calculations for years, months, and days.
# The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>,
# <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>,
# <tt>:minutes</tt>, <tt>:seconds</tt>.
def advance(options)
d = to_date.advance(options)
time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day)

View file

@ -68,8 +68,9 @@ module Inflector
(@uncountables << words).flatten!
end
# Clears the loaded inflections within a given scope (default is :all). Give the scope as a symbol of the inflection type,
# the options are: :plurals, :singulars, :uncountables
# Clears the loaded inflections within a given scope (default is <tt>:all</tt>).
# Give the scope as a symbol of the inflection type, the options are: <tt>:plurals</tt>,
# <tt>:singulars</tt>, <tt>:uncountables</tt>.
#
# Examples:
# clear :all
@ -245,13 +246,23 @@ module Inflector
underscore(demodulize(class_name)) + (separate_class_name_and_id_with_underscore ? "_id" : "id")
end
# Constantize tries to find a declared constant with the name specified
# in the string. It raises a NameError when the name is not in CamelCase
# or is not initialized.
# Tries to find a constant with the name specified in the argument string:
#
# Examples
# "Module".constantize #=> Module
# "Class".constantize #=> Class
# "Module".constantize # => Module
# "Test::Unit".constantize # => Test::Unit
#
# The name is assumed to be the one of a top-level constant, no matter whether
# it starts with "::" or not. No lexical context is taken into account:
#
# C = 'outside'
# module M
# C = 'inside'
# C # => 'inside'
# "C".constantize # => 'outside', same as ::C
# end
#
# NameError is raised when the name is not in CamelCase or the constant is
# unknown.
def constantize(camel_cased_word)
unless /\A(?:::)?([A-Z]\w*(?:::[A-Z]\w*)*)\z/ =~ camel_cased_word
raise NameError, "#{camel_cased_word.inspect} is not a valid constant name!"

View file

@ -284,7 +284,9 @@ module ActiveSupport::Multibyte::Handlers #:nodoc:
# passing strings to databases and validations.
#
# * <tt>str</tt> - The string to perform normalization on.
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following: :c, :kc, :d or :kd.
# * <tt>form</tt> - The form you want to normalize in. Should be one of the following:
# <tt>:c</tt>, <tt>:kc</tt>, <tt>:d</tt>, or <tt>:kd</tt>. Default is
# ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM.
def normalize(str, form=ActiveSupport::Multibyte::DEFAULT_NORMALIZATION_FORM)
# See http://www.unicode.org/reports/tr15, Table 1
codepoints = u_unpack(str)

View file

@ -101,7 +101,8 @@ module ActiveSupport
end
alias_method :rfc822, :rfc2822
# :db format outputs time in UTC; all others output time in local. Uses TimeWithZone's strftime, so %Z and %z work correctly
# <tt>:db</tt> format outputs time in UTC; all others output time in local.
# Uses TimeWithZone's +strftime+, so <tt>%Z</tt> and <tt>%z</tt> work correctly.
def to_s(format = :default)
return utc.to_s(format) if format == :db
if formatter = ::Time::DATE_FORMATS[format]
@ -111,7 +112,7 @@ module ActiveSupport
end
end
# Replaces %Z and %z directives with #zone and #formatted_offset, respectively, before passing to
# Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and +formatted_offset+, respectively, before passing to
# Time#strftime, so that zone information is correct
def strftime(format)
format = format.gsub('%Z', zone).gsub('%z', formatted_offset(false))
@ -138,9 +139,9 @@ module ActiveSupport
result.in_time_zone(time_zone)
end
# If a time-like object is passed in, compare it with #utc
# Else if wrapped #time is a DateTime, use DateTime#ago instead of #-
# Otherwise, just pass on to method missing
# If a time-like object is passed in, compare it with +utc+.
# Else if wrapped +time+ is a DateTime, use DateTime#ago instead of DateTime#-.
# Otherwise, just pass on to +method_missing+.
def -(other)
if other.acts_like?(:time)
utc - other
@ -180,7 +181,7 @@ module ActiveSupport
alias_method :hash, :to_i
alias_method :tv_sec, :to_i
# A TimeWithZone acts like a Time, so just return self
# A TimeWithZone acts like a Time, so just return +self+.
def to_time
self
end

View file

@ -572,11 +572,11 @@ module Rails
attr_accessor :plugin_loader
# Enables or disables plugin reloading. You can get around this setting per plugin.
# If #reload_plugins? == false, add this to your plugin's init.rb to make it reloadable:
# If <tt>reload_plugins?</tt> is false, add this to your plugin's init.rb to make it reloadable:
#
# Dependencies.load_once_paths.delete lib_path
#
# If #reload_plugins? == true, add this to your plugin's init.rb to only load it once:
# If <tt>reload_plugins?</tt> is true, add this to your plugin's init.rb to only load it once:
#
# Dependencies.load_once_paths << lib_path
#