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

Merge branch 'master' of git://github.com/lifo/docrails

Conflicts:
	actionpack/lib/action_view/helpers/date_helper.rb
	railties/lib/rails/generators/rails/app/templates/config/initializers/wrap_parameters.rb.tt
This commit is contained in:
Xavier Noria 2011-05-14 11:21:27 +02:00
commit d491130236
42 changed files with 319 additions and 220 deletions

View file

@ -1,3 +1,9 @@
# Includes +url_for+ into the host class (e.g. an abstract controller or mailer). The class
# has to provide a +RouteSet+ by implementing the <tt>_routes</tt> methods. Otherwise, an
# exception will be raised.
#
# Note that this module is completely decoupled from HTTP - the only requirement is a valid
# <tt>_routes</tt> implementation.
module AbstractController module AbstractController
module UrlFor module UrlFor
extend ActiveSupport::Concern extend ActiveSupport::Concern

View file

@ -1,3 +1,24 @@
# Includes +url_for+ into the host class. The class has to provide a +RouteSet+ by implementing
# the <tt>_routes</tt> method. Otherwise, an exception will be raised.
#
# In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
# url options like the +host+. In order to do so, this module requires the host class
# to implement +env+ and +request+, which need to be a Rack-compatible.
#
# Example:
#
# class RootUrl
# include ActionController::UrlFor
# include Rails.application.routes.url_helpers
#
# delegate :env, :request, :to => :controller
#
# def initialize(controller)
# @controller = controller
# @url = root_path # named route from the application.
# end
# end
# =>
module ActionController module ActionController
module UrlFor module UrlFor
extend ActiveSupport::Concern extend ActiveSupport::Concern

View file

@ -162,7 +162,7 @@ module ActionDispatch
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be # Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>, # returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
# such as 2 to catch <tt>["www"]</tt> instead of <tt>"www.rubyonrails"</tt> # such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
# in "www.rubyonrails.co.uk". # in "www.rubyonrails.co.uk".
def subdomain(tld_length = @@tld_length) def subdomain(tld_length = @@tld_length)
subdomains(tld_length).join(".") subdomains(tld_length).join(".")

View file

@ -49,8 +49,8 @@ module ActionDispatch
# You may wish to organize groups of controllers under a namespace. Most # You may wish to organize groups of controllers under a namespace. Most
# commonly, you might group a number of administrative controllers under # commonly, you might group a number of administrative controllers under
# an +admin+ namespace. You would place these controllers under the # an +admin+ namespace. You would place these controllers under the
# app/controllers/admin directory, and you can group them together in your # <tt>app/controllers/admin</tt> directory, and you can group them together
# router: # in your router:
# #
# namespace "admin" do # namespace "admin" do
# resources :posts, :comments # resources :posts, :comments
@ -152,7 +152,7 @@ module ActionDispatch
# } # }
# end # end
# #
# Using the multiline match modifier will raise an ArgumentError. # Using the multiline match modifier will raise an +ArgumentError+.
# Encoding regular expression modifiers are silently ignored. The # Encoding regular expression modifiers are silently ignored. The
# match will always use the default encoding or ASCII. # match will always use the default encoding or ASCII.
# #

View file

@ -335,7 +335,7 @@ module ActionDispatch
# #
# [:on] # [:on]
# Shorthand for wrapping routes in a specific RESTful context. Valid # Shorthand for wrapping routes in a specific RESTful context. Valid
# values are :member, :collection, and :new. Only use within # values are +:member+, +:collection+, and +:new+. Only use within
# <tt>resource(s)</tt> block. For example: # <tt>resource(s)</tt> block. For example:
# #
# resource :bar do # resource :bar do
@ -352,7 +352,7 @@ module ActionDispatch
# #
# [:constraints] # [:constraints]
# Constrains parameters with a hash of regular expressions or an # Constrains parameters with a hash of regular expressions or an
# object that responds to #matches? # object that responds to <tt>matches?</tt>
# #
# match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ } # match 'path/:id', :constraints => { :id => /[A-Z]\d{5}/ }
# #
@ -373,7 +373,7 @@ module ActionDispatch
# See <tt>Scoping#defaults</tt> for its scope equivalent. # See <tt>Scoping#defaults</tt> for its scope equivalent.
# #
# [:anchor] # [:anchor]
# Boolean to anchor a #match pattern. Default is true. When set to # Boolean to anchor a <tt>match</tt> pattern. Default is true. When set to
# false, the pattern matches any request prefixed with the given path. # false, the pattern matches any request prefixed with the given path.
# #
# # Matches any request starting with 'path' # # Matches any request starting with 'path'
@ -517,15 +517,15 @@ module ActionDispatch
# You may wish to organize groups of controllers under a namespace. # You may wish to organize groups of controllers under a namespace.
# Most commonly, you might group a number of administrative controllers # Most commonly, you might group a number of administrative controllers
# under an +admin+ namespace. You would place these controllers under # under an +admin+ namespace. You would place these controllers under
# the app/controllers/admin directory, and you can group them together # the <tt>app/controllers/admin</tt> directory, and you can group them
# in your router: # together in your router:
# #
# namespace "admin" do # namespace "admin" do
# resources :posts, :comments # resources :posts, :comments
# end # end
# #
# This will create a number of routes for each of the posts and comments # This will create a number of routes for each of the posts and comments
# controller. For Admin::PostsController, Rails will create: # controller. For <tt>Admin::PostsController</tt>, Rails will create:
# #
# GET /admin/posts # GET /admin/posts
# GET /admin/posts/new # GET /admin/posts/new
@ -536,7 +536,7 @@ module ActionDispatch
# DELETE /admin/posts/1 # DELETE /admin/posts/1
# #
# If you want to route /posts (without the prefix /admin) to # If you want to route /posts (without the prefix /admin) to
# Admin::PostsController, you could use # <tt>Admin::PostsController</tt>, you could use
# #
# scope :module => "admin" do # scope :module => "admin" do
# resources :posts # resources :posts
@ -546,7 +546,7 @@ module ActionDispatch
# #
# resources :posts, :module => "admin" # resources :posts, :module => "admin"
# #
# If you want to route /admin/posts to PostsController # If you want to route /admin/posts to +PostsController+
# (without the Admin:: module prefix), you could use # (without the Admin:: module prefix), you could use
# #
# scope "/admin" do # scope "/admin" do
@ -555,11 +555,11 @@ module ActionDispatch
# #
# or, for a single case # or, for a single case
# #
# resources :posts, :path => "/admin" # resources :posts, :path => "/admin/posts"
# #
# In each of these cases, the named routes remain the same as if you did # In each of these cases, the named routes remain the same as if you did
# not use scope. In the last case, the following paths map to # not use scope. In the last case, the following paths map to
# PostsController: # +PostsController+:
# #
# GET /admin/posts # GET /admin/posts
# GET /admin/posts/new # GET /admin/posts/new
@ -587,7 +587,7 @@ module ActionDispatch
# #
# === Examples # === Examples
# #
# # route /posts (without the prefix /admin) to Admin::PostsController # # route /posts (without the prefix /admin) to <tt>Admin::PostsController</tt>
# scope :module => "admin" do # scope :module => "admin" do
# resources :posts # resources :posts
# end # end
@ -597,7 +597,7 @@ module ActionDispatch
# resources :posts # resources :posts
# end # end
# #
# # prefix the routing helper name: sekret_posts_path instead of posts_path # # prefix the routing helper name: +sekret_posts_path+ instead of +posts_path+
# scope :as => "sekret" do # scope :as => "sekret" do
# resources :posts # resources :posts
# end # end
@ -679,12 +679,12 @@ module ActionDispatch
# resources :posts # resources :posts
# end # end
# #
# # maps to Sekret::PostsController rather than Admin::PostsController # # maps to <tt>Sekret::PostsController</tt> rather than <tt>Admin::PostsController</tt>
# namespace :admin, :module => "sekret" do # namespace :admin, :module => "sekret" do
# resources :posts # resources :posts
# end # end
# #
# # generates sekret_posts_path rather than admin_posts_path # # generates +sekret_posts_path+ rather than +admin_posts_path+
# namespace :admin, :as => "sekret" do # namespace :admin, :as => "sekret" do
# resources :posts # resources :posts
# end # end
@ -712,6 +712,7 @@ module ActionDispatch
# constraints(:post_id => /\d+\.\d+) do # constraints(:post_id => /\d+\.\d+) do
# resources :comments # resources :comments
# end # end
# end
# #
# === Restricting based on IP # === Restricting based on IP
# #
@ -846,20 +847,20 @@ module ActionDispatch
# You may wish to organize groups of controllers under a namespace. Most # You may wish to organize groups of controllers under a namespace. Most
# commonly, you might group a number of administrative controllers under # commonly, you might group a number of administrative controllers under
# an +admin+ namespace. You would place these controllers under the # an +admin+ namespace. You would place these controllers under the
# app/controllers/admin directory, and you can group them together in your # <tt>app/controllers/admin</tt> directory, and you can group them together
# router: # in your router:
# #
# namespace "admin" do # namespace "admin" do
# resources :posts, :comments # resources :posts, :comments
# end # end
# #
# By default the :id parameter doesn't accept dots. If you need to # By default the +:id+ parameter doesn't accept dots. If you need to
# use dots as part of the :id parameter add a constraint which # use dots as part of the +:id+ parameter add a constraint which
# overrides this restriction, e.g: # overrides this restriction, e.g:
# #
# resources :articles, :id => /[^\/]+/ # resources :articles, :id => /[^\/]+/
# #
# This allows any character other than a slash as part of your :id. # This allows any character other than a slash as part of your +:id+.
# #
module Resources module Resources
# CANONICAL_ACTIONS holds all actions that does not need a prefix or # CANONICAL_ACTIONS holds all actions that does not need a prefix or
@ -975,7 +976,7 @@ module ActionDispatch
# resource :geocoder # resource :geocoder
# #
# creates six different routes in your application, all mapping to # creates six different routes in your application, all mapping to
# the GeoCoders controller (note that the controller is named after # the +GeoCoders+ controller (note that the controller is named after
# the plural): # the plural):
# #
# GET /geocoder/new # GET /geocoder/new
@ -1024,7 +1025,7 @@ module ActionDispatch
# resources :photos # resources :photos
# #
# creates seven different routes in your application, all mapping to # creates seven different routes in your application, all mapping to
# the Photos controller: # the +Photos+ controller:
# #
# GET /photos/new # GET /photos/new
# POST /photos # POST /photos
@ -1107,11 +1108,11 @@ module ActionDispatch
# #
# === Examples # === Examples
# #
# # routes call Admin::PostsController # # routes call <tt>Admin::PostsController</tt>
# resources :posts, :module => "admin" # resources :posts, :module => "admin"
# #
# # resource actions are at /admin/posts. # # resource actions are at /admin/posts.
# resources :posts, :path => "admin" # resources :posts, :path => "admin/posts"
def resources(*resources, &block) def resources(*resources, &block)
options = resources.extract_options! options = resources.extract_options!
@ -1151,7 +1152,7 @@ module ActionDispatch
# end # end
# #
# This will enable Rails to recognize paths such as <tt>/photos/search</tt> # This will enable Rails to recognize paths such as <tt>/photos/search</tt>
# with GET, and route to the search action of PhotosController. It will also # with GET, and route to the search action of +PhotosController+. It will also
# create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt> # create the <tt>search_photos_url</tt> and <tt>search_photos_path</tt>
# route helpers. # route helpers.
def collection def collection
@ -1175,7 +1176,7 @@ module ActionDispatch
# end # end
# #
# This will recognize <tt>/photos/1/preview</tt> with GET, and route to the # This will recognize <tt>/photos/1/preview</tt> with GET, and route to the
# preview action of PhotosController. It will also create the # preview action of +PhotosController+. It will also create the
# <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers. # <tt>preview_photo_url</tt> and <tt>preview_photo_path</tt> helpers.
def member def member
unless resource_scope? unless resource_scope?

View file

@ -131,10 +131,10 @@ module ActionDispatch
# #
# Examples: # Examples:
# #
# url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :port=>'8080' # => 'http://somehost.org:8080/tasks/testing' # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :port => '8080' # => 'http://somehost.org:8080/tasks/testing'
# url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok' # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :anchor => 'ok', :only_path => true # => '/tasks/testing#ok'
# url_for :controller => 'tasks', :action => 'testing', :trailing_slash=>true # => 'http://somehost.org/tasks/testing/' # url_for :controller => 'tasks', :action => 'testing', :trailing_slash => true # => 'http://somehost.org/tasks/testing/'
# url_for :controller => 'tasks', :action => 'testing', :host=>'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33' # url_for :controller => 'tasks', :action => 'testing', :host => 'somehost.org', :number => '33' # => 'http://somehost.org/tasks/testing?number=33'
def url_for(options = nil) def url_for(options = nil)
case options case options
when String when String

View file

@ -169,7 +169,7 @@ module ActionDispatch
# assert_select "title", "Welcome" # assert_select "title", "Welcome"
# #
# # Page title is "Welcome" and there is only one title element # # Page title is "Welcome" and there is only one title element
# assert_select "title", {:count=>1, :text=>"Welcome"}, # assert_select "title", {:count => 1, :text => "Welcome"},
# "Wrong title or more than one title element" # "Wrong title or more than one title element"
# #
# # Page contains no forms # # Page contains no forms

View file

@ -85,11 +85,11 @@ module ActionView #:nodoc:
# #
# Here are some basic examples: # Here are some basic examples:
# #
# xml.em("emphasized") # => <em>emphasized</em> # xml.em("emphasized") # => <em>emphasized</em>
# xml.em { xml.b("emph & bold") } # => <em><b>emph &amp; bold</b></em> # xml.em { xml.b("emph & bold") } # => <em><b>emph &amp; bold</b></em>
# xml.a("A Link", "href"=>"http://onestepback.org") # => <a href="http://onestepback.org">A Link</a> # xml.a("A Link", "href" => "http://onestepback.org") # => <a href="http://onestepback.org">A Link</a>
# xml.target("name"=>"compile", "option"=>"fast") # => <target option="fast" name="compile"\> # xml.target("name" => "compile", "option" => "fast") # => <target option="fast" name="compile"\>
# # NOTE: order of attributes is not specified. # # NOTE: order of attributes is not specified.
# #
# Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following: # Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
# #

View file

@ -81,8 +81,8 @@ module ActionView
# #
# The Atom spec defines five elements (content rights title subtitle # The Atom spec defines five elements (content rights title subtitle
# summary) which may directly contain xhtml content if :type => 'xhtml' # summary) which may directly contain xhtml content if :type => 'xhtml'
# is specified as an attribute. If so, this helper will take care of # is specified as an attribute. If so, this helper will take care of
# the enclosing div and xhtml namespace declaration. Example usage: # the enclosing div and xhtml namespace declaration. Example usage:
# #
# entry.summary :type => 'xhtml' do |xhtml| # entry.summary :type => 'xhtml' do |xhtml|
# xhtml.p pluralize(order.line_items.count, "line item") # xhtml.p pluralize(order.line_items.count, "line item")
@ -91,8 +91,8 @@ module ActionView
# end # end
# #
# #
# atom_feed yields an AtomFeedBuilder instance. Nested elements yield # <tt>atom_feed</tt> yields an +AtomFeedBuilder+ instance. Nested elements yield
# an AtomBuilder instance. # an +AtomBuilder+ instance.
def atom_feed(options = {}, &block) def atom_feed(options = {}, &block)
if options[:schema_date] if options[:schema_date]
options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime) options[:schema_date] = options[:schema_date].strftime("%Y-%m-%d") if options[:schema_date].respond_to?(:strftime)

View file

@ -3,7 +3,7 @@ module ActionView
module Helpers module Helpers
module CacheHelper module CacheHelper
# This helper exposes a method for caching fragments of a view # This helper exposes a method for caching fragments of a view
# rather than an entire action or page. This technique is useful # rather than an entire action or page. This technique is useful
# caching pieces like menus, lists of newstopics, static HTML # caching pieces like menus, lists of newstopics, static HTML
# fragments, and so on. This method takes a block that contains # fragments, and so on. This method takes a block that contains
# the content you wish to cache. # the content you wish to cache.

View file

@ -12,14 +12,14 @@ module ActionView
# select-type methods share a number of common options that are as follows: # select-type methods share a number of common options that are as follows:
# #
# * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday" # * <tt>:prefix</tt> - overwrites the default prefix of "date" used for the select names. So specifying "birthday"
# would give birthday[month] instead of date[month] if passed to the select_month method. # would give birthday[month] instead of date[month] if passed to the <tt>select_month</tt> method.
# * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date. # * <tt>:include_blank</tt> - set to true if it should be possible to set an empty date.
# * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true, # * <tt>:discard_type</tt> - set to true if you want to discard the type part of the select name. If set to true,
# the select_month method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead of # the <tt>select_month</tt> method would use simply "date" (which can be overwritten using <tt>:prefix</tt>) instead
# "date[month]". # of "date[month]".
module DateHelper module DateHelper
# Reports the approximate distance in time between two Time or Date objects or integers as seconds. # Reports the approximate distance in time between two Time or Date objects or integers as seconds.
# Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs # Set <tt>include_seconds</tt> to true if you want more detailed approximations when distance < 1 min, 29 secs.
# Distances are reported based on the following table: # Distances are reported based on the following table:
# #
# 0 <-> 29 secs # => less than a minute # 0 <-> 29 secs # => less than a minute
@ -119,7 +119,7 @@ module ActionView
end end
end end
# Like distance_of_time_in_words, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>. # Like <tt>distance_of_time_in_words</tt>, but where <tt>to_time</tt> is fixed to <tt>Time.now</tt>.
# #
# ==== Examples # ==== Examples
# time_ago_in_words(3.minutes.from_now) # => 3 minutes # time_ago_in_words(3.minutes.from_now) # => 3 minutes
@ -176,7 +176,7 @@ module ActionView
# NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed. # NOTE: Discarded selects will default to 1. So if no month select is available, January will be assumed.
# #
# ==== Examples # ==== Examples
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute.
# date_select("post", "written_on") # date_select("post", "written_on")
# #
# # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute, # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute,
@ -197,7 +197,7 @@ module ActionView
# # lacking a year field. # # lacking a year field.
# date_select("user", "birthday", :order => [:month, :day]) # date_select("user", "birthday", :order => [:month, :day])
# #
# # Generates a date select that when POSTed is stored in the user variable, in the birthday attribute # # Generates a date select that when POSTed is stored in the post variable, in the written_on attribute
# # which is initially set to the date 3 days from the current date # # which is initially set to the date 3 days from the current date
# date_select("post", "written_on", :default => 3.days.from_now) # date_select("post", "written_on", :default => 3.days.from_now)
# #
@ -205,7 +205,7 @@ module ActionView
# # that will have a default day of 20. # # that will have a default day of 20.
# date_select("credit_card", "bill_due", :default => { :day => 20 }) # date_select("credit_card", "bill_due", :default => { :day => 20 })
# #
# # Generates a date select with custom prompts # # Generates a date select with custom prompts.
# date_select("post", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' }) # date_select("post", "written_on", :prompt => { :day => 'Select day', :month => 'Select month', :year => 'Select year' })
# #
# The selects are prepared for multi-parameter assignment to an Active Record object. # The selects are prepared for multi-parameter assignment to an Active Record object.
@ -222,22 +222,23 @@ module ActionView
# with <tt>:ampm</tt> option. # with <tt>:ampm</tt> option.
# #
# This method will also generate 3 input hidden tags, for the actual year, month and day unless the option # This method will also generate 3 input hidden tags, for the actual year, month and day unless the option
# <tt>:ignore_date</tt> is set to +true+. # <tt>:ignore_date</tt> is set to +true+. If you set the <tt>:ignore_date</tt> to +true+, you must have a
# +date_select+ on the same method within the form otherwise an exception will be raised.
# #
# 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.
# #
# ==== Examples # ==== Examples
# # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute # # Creates a time select tag that, when POSTed, will be stored in the post variable in the sunrise attribute.
# time_select("post", "sunrise") # time_select("post", "sunrise")
# #
# # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in # # Creates a time select tag with a seconds field that, when POSTed, will be stored in the post variables in
# # the sunrise attribute. # # the sunrise attribute.
# time_select("post", "start_time", :include_seconds => true) # time_select("post", "start_time", :include_seconds => true)
# #
# # You can set the :minute_step to 15 which will give you: 00, 15, 30 and 45. # # You can set the <tt>:minute_step</tt> to 15 which will give you: 00, 15, 30 and 45.
# time_select 'game', 'game_time', {:minute_step => 15} # time_select 'game', 'game_time', {:minute_step => 15}
# #
# # Creates a time select tag with a custom prompt. Use :prompt => true for generic prompts. # # Creates a time select tag with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
# time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) # time_select("post", "written_on", :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'})
# time_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours # time_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# time_select("post", "written_on", :prompt => true) # generic prompts for all # time_select("post", "written_on", :prompt => true) # generic prompts for all
@ -261,7 +262,7 @@ module ActionView
# #
# ==== Examples # ==== Examples
# # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on # # Generates a datetime select that, when POSTed, will be stored in the post variable in the written_on
# # attribute # # attribute.
# datetime_select("post", "written_on") # datetime_select("post", "written_on")
# #
# # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the # # Generates a datetime select with a year select that starts at 1995 that, when POSTed, will be stored in the
@ -279,7 +280,7 @@ module ActionView
# # as the written_on attribute. # # as the written_on attribute.
# datetime_select("post", "written_on", :discard_type => true) # datetime_select("post", "written_on", :discard_type => true)
# #
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts. # # Generates a datetime select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
# datetime_select("post", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # datetime_select("post", "written_on", :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# datetime_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours # datetime_select("post", "written_on", :prompt => {:hour => true}) # generic prompt for hours
# datetime_select("post", "written_on", :prompt => true) # generic prompts for all # datetime_select("post", "written_on", :prompt => true) # generic prompts for all
@ -301,7 +302,7 @@ module ActionView
# ==== Examples # ==== Examples
# my_date_time = Time.now + 4.days # my_date_time = Time.now + 4.days
# #
# # Generates a datetime select that defaults to the datetime in my_date_time (four days after today) # # Generates a datetime select that defaults to the datetime in my_date_time (four days after today).
# select_datetime(my_date_time) # select_datetime(my_date_time)
# #
# # Generates a datetime select that defaults to today (no specified datetime) # # Generates a datetime select that defaults to today (no specified datetime)
@ -331,7 +332,7 @@ module ActionView
# # prefixed with 'payday' rather than 'date' # # prefixed with 'payday' rather than 'date'
# select_datetime(my_date_time, :prefix => 'payday') # select_datetime(my_date_time, :prefix => 'payday')
# #
# # Generates a datetime select with a custom prompt. Use :prompt=>true for generic prompts. # # Generates a datetime select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
# select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_datetime(my_date_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours # select_datetime(my_date_time, :prompt => {:hour => true}) # generic prompt for hours
# select_datetime(my_date_time, :prompt => true) # generic prompts for all # select_datetime(my_date_time, :prompt => true) # generic prompts for all
@ -350,10 +351,10 @@ module ActionView
# ==== Examples # ==== Examples
# my_date = Time.today + 6.days # my_date = Time.today + 6.days
# #
# # Generates a date select that defaults to the date in my_date (six days after today) # # Generates a date select that defaults to the date in my_date (six days afteri today).
# select_date(my_date) # select_date(my_date)
# #
# # Generates a date select that defaults to today (no specified date) # # Generates a date select that defaults to today (no specified date).
# select_date() # select_date()
# #
# # Generates a date select that defaults to the date in my_date (six days after today) # # Generates a date select that defaults to the date in my_date (six days after today)
@ -361,18 +362,18 @@ module ActionView
# select_date(my_date, :order => [:year, :month, :day]) # select_date(my_date, :order => [:year, :month, :day])
# #
# # Generates a date select that discards the type of the field and defaults to the date in # # Generates a date select that discards the type of the field and defaults to the date in
# # my_date (six days after today) # # my_date (six days after today).
# select_date(my_date, :discard_type => true) # select_date(my_date, :discard_type => true)
# #
# # Generates a date select that defaults to the date in my_date, # # Generates a date select that defaults to the date in my_date,
# # which has fields separated by '/' # # which has fields separated by '/'.
# select_date(my_date, :date_separator => '/') # select_date(my_date, :date_separator => '/')
# #
# # Generates a date select that defaults to the datetime in my_date (six days after today) # # Generates a date select that defaults to the datetime in my_date (six days after today)
# # prefixed with 'payday' rather than 'date' # # prefixed with 'payday' rather than 'date'.
# select_date(my_date, :prefix => 'payday') # select_date(my_date, :prefix => 'payday')
# #
# # Generates a date select with a custom prompt. Use :prompt=>true for generic prompts. # # Generates a date select with a custom prompt. Use <tt>:prompt => true</tt> for generic prompts.
# select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_date(my_date, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours # select_date(my_date, :prompt => {:hour => true}) # generic prompt for hours
# select_date(my_date, :prompt => true) # generic prompts for all # select_date(my_date, :prompt => true) # generic prompts for all
@ -381,7 +382,7 @@ module ActionView
DateTimeSelector.new(date, options, html_options).select_date DateTimeSelector.new(date, options, html_options).select_date
end end
# Returns a set of html select-tags (one for hour and minute) # Returns a set of html select-tags (one for hour and minute).
# You can set <tt>:time_separator</tt> key to format the output, and # You can set <tt>:time_separator</tt> key to format the output, and
# the <tt>:include_seconds</tt> option to include an input for seconds. # the <tt>:include_seconds</tt> option to include an input for seconds.
# #
@ -390,28 +391,28 @@ module ActionView
# ==== Examples # ==== Examples
# my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds # my_time = Time.now + 5.days + 7.hours + 3.minutes + 14.seconds
# #
# # Generates a time select that defaults to the time in my_time # # Generates a time select that defaults to the time in my_time.
# select_time(my_time) # select_time(my_time)
# #
# # Generates a time select that defaults to the current time (no specified time) # # Generates a time select that defaults to the current time (no specified time).
# select_time() # select_time()
# #
# # Generates a time select that defaults to the time in my_time, # # Generates a time select that defaults to the time in my_time,
# # which has fields separated by ':' # # which has fields separated by ':'.
# select_time(my_time, :time_separator => ':') # select_time(my_time, :time_separator => ':')
# #
# # Generates a time select that defaults to the time in my_time, # # Generates a time select that defaults to the time in my_time,
# # that also includes an input for seconds # # that also includes an input for seconds.
# select_time(my_time, :include_seconds => true) # select_time(my_time, :include_seconds => true)
# #
# # Generates a time select that defaults to the time in my_time, that has fields # # Generates a time select that defaults to the time in my_time, that has fields
# # separated by ':' and includes an input for seconds # # separated by ':' and includes an input for seconds.
# select_time(my_time, :time_separator => ':', :include_seconds => true) # select_time(my_time, :time_separator => ':', :include_seconds => true)
# #
# # Generate a time select field with hours in the AM/PM format # # Generate a time select field with hours in the AM/PM format
# select_time(my_time, :ampm => true) # select_time(my_time, :ampm => true)
# #
# # Generates a time select with a custom prompt. Use :prompt=>true for generic prompts. # # Generates a time select with a custom prompt. Use <tt>:prompt</tt> to true for generic prompts.
# select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'}) # select_time(my_time, :prompt => {:day => 'Choose day', :month => 'Choose month', :year => 'Choose year'})
# select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours # select_time(my_time, :prompt => {:hour => true}) # generic prompt for hours
# select_time(my_time, :prompt => true) # generic prompts for all # select_time(my_time, :prompt => true) # generic prompts for all
@ -427,17 +428,17 @@ module ActionView
# ==== Examples # ==== Examples
# my_time = Time.now + 16.minutes # my_time = Time.now + 16.minutes
# #
# # Generates a select field for seconds that defaults to the seconds for the time in my_time # # Generates a select field for seconds that defaults to the seconds for the time in my_time.
# select_second(my_time) # select_second(my_time)
# #
# # Generates a select field for seconds that defaults to the number given # # Generates a select field for seconds that defaults to the number given.
# select_second(33) # select_second(33)
# #
# # Generates a select field for seconds that defaults to the seconds for the time in my_time # # Generates a select field for seconds that defaults to the seconds for the time in my_time
# # that is named 'interval' rather than 'second' # # that is named 'interval' rather than 'second'.
# select_second(my_time, :field_name => 'interval') # select_second(my_time, :field_name => 'interval')
# #
# # Generates a select field for seconds with a custom prompt. Use :prompt=>true for a # # Generates a select field for seconds with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_minute(14, :prompt => 'Choose seconds') # select_minute(14, :prompt => 'Choose seconds')
# #
@ -453,17 +454,17 @@ module ActionView
# ==== Examples # ==== Examples
# my_time = Time.now + 6.hours # my_time = Time.now + 6.hours
# #
# # Generates a select field for minutes that defaults to the minutes for the time in my_time # # Generates a select field for minutes that defaults to the minutes for the time in my_tiime.
# select_minute(my_time) # select_minute(my_time)
# #
# # Generates a select field for minutes that defaults to the number given # # Generates a select field for minutes that defaults to the number given.
# select_minute(14) # select_minute(14)
# #
# # Generates a select field for minutes that defaults to the minutes for the time in my_time # # Generates a select field for minutes that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second' # # that is named 'stride' rather than 'second'.
# select_minute(my_time, :field_name => 'stride') # select_minute(my_time, :field_name => 'stride')
# #
# # Generates a select field for minutes with a custom prompt. Use :prompt=>true for a # # Generates a select field for minutes with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_minute(14, :prompt => 'Choose minutes') # select_minute(14, :prompt => 'Choose minutes')
# #
@ -478,17 +479,17 @@ module ActionView
# ==== Examples # ==== Examples
# my_time = Time.now + 6.hours # my_time = Time.now + 6.hours
# #
# # Generates a select field for hours that defaults to the hour for the time in my_time # # Generates a select field for hours that defaults to the hour for the time in my_time.
# select_hour(my_time) # select_hour(my_time)
# #
# # Generates a select field for hours that defaults to the number given # # Generates a select field for hours that defaults to the number given.
# select_hour(13) # select_hour(13)
# #
# # Generates a select field for hours that defaults to the minutes for the time in my_time # # Generates a select field for hours that defaults to the minutes for the time in my_time
# # that is named 'stride' rather than 'second' # # that is named 'stride' rather than 'second'.
# select_hour(my_time, :field_name => 'stride') # select_hour(my_time, :field_name => 'stride')
# #
# # Generates a select field for hours with a custom prompt. Use :prompt => true for a # # Generates a select field for hours with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_hour(13, :prompt => 'Choose hour') # select_hour(13, :prompt => 'Choose hour')
# #
@ -506,17 +507,17 @@ module ActionView
# ==== Examples # ==== Examples
# my_date = Time.today + 2.days # my_date = Time.today + 2.days
# #
# # Generates a select field for days that defaults to the day for the date in my_date # # Generates a select field for days that defaults to the day for the date in my_date.
# select_day(my_time) # select_day(my_time)
# #
# # Generates a select field for days that defaults to the number given # # Generates a select field for days that defaults to the number given.
# select_day(5) # select_day(5)
# #
# # Generates a select field for days that defaults to the day for the date in my_date # # Generates a select field for days that defaults to the day for the date in my_date
# # that is named 'due' rather than 'day' # # that is named 'due' rather than 'day'.
# select_day(my_time, :field_name => 'due') # select_day(my_time, :field_name => 'due')
# #
# # Generates a select field for days with a custom prompt. Use :prompt => true for a # # Generates a select field for days with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_day(5, :prompt => 'Choose day') # select_day(5, :prompt => 'Choose day')
# #
@ -539,7 +540,7 @@ module ActionView
# select_month(Date.today) # select_month(Date.today)
# #
# # Generates a select field for months that defaults to the current month that # # Generates a select field for months that defaults to the current month that
# # is named "start" rather than "month" # # is named "start" rather than "month".
# select_month(Date.today, :field_name => 'start') # select_month(Date.today, :field_name => 'start')
# #
# # Generates a select field for months that defaults to the current month that # # Generates a select field for months that defaults to the current month that
@ -558,7 +559,7 @@ module ActionView
# # will use keys like "Januar", "Marts." # # will use keys like "Januar", "Marts."
# select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...)) # select_month(Date.today, :use_month_names => %w(Januar Februar Marts ...))
# #
# # Generates a select field for months with a custom prompt. Use :prompt => true for a # # Generates a select field for months with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_month(14, :prompt => 'Choose month') # select_month(14, :prompt => 'Choose month')
# #
@ -574,22 +575,22 @@ module ActionView
# #
# ==== Examples # ==== Examples
# # Generates a select field for years that defaults to the current year that # # Generates a select field for years that defaults to the current year that
# # has ascending year values # # has ascending year values.
# select_year(Date.today, :start_year => 1992, :end_year => 2007) # select_year(Date.today, :start_year => 1992, :end_year => 2007)
# #
# # Generates a select field for years that defaults to the current year that # # Generates a select field for years that defaults to the current year that
# # is named 'birth' rather than 'year' # # is named 'birth' rather than 'year'.
# select_year(Date.today, :field_name => 'birth') # select_year(Date.today, :field_name => 'birth')
# #
# # Generates a select field for years that defaults to the current year that # # Generates a select field for years that defaults to the current year that
# # has descending year values # # has descending year values.
# select_year(Date.today, :start_year => 2005, :end_year => 1900) # select_year(Date.today, :start_year => 2005, :end_year => 1900)
# #
# # Generates a select field for years that defaults to the year 2006 that # # Generates a select field for years that defaults to the year 2006 that
# # has ascending year values # # has ascending year values.
# select_year(2006, :start_year => 2000, :end_year => 2010) # select_year(2006, :start_year => 2000, :end_year => 2010)
# #
# # Generates a select field for years with a custom prompt. Use :prompt => true for a # # Generates a select field for years with a custom prompt. Use <tt>:prompt => true</tt> for a
# # generic prompt. # # generic prompt.
# select_year(14, :prompt => 'Choose year') # select_year(14, :prompt => 'Choose year')
# #
@ -783,7 +784,7 @@ module ActionView
end end
# Returns translated month names, but also ensures that a custom month # Returns translated month names, but also ensures that a custom month
# name array has a leading nil element # name array has a leading nil element.
def month_names def month_names
month_names = @options[:use_month_names] || translated_month_names month_names = @options[:use_month_names] || translated_month_names
month_names.unshift(nil) if month_names.size < 13 month_names.unshift(nil) if month_names.size < 13
@ -791,13 +792,13 @@ module ActionView
end end
memoize :month_names memoize :month_names
# Returns translated month names # Returns translated month names.
# => [nil, "January", "February", "March", # => [nil, "January", "February", "March",
# "April", "May", "June", "July", # "April", "May", "June", "July",
# "August", "September", "October", # "August", "September", "October",
# "November", "December"] # "November", "December"]
# #
# If :use_short_month option is set # If <tt>:use_short_month</tt> option is set
# => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", # => [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
# "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] # "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
def translated_month_names def translated_month_names
@ -805,13 +806,13 @@ module ActionView
I18n.translate(key, :locale => @options[:locale]) I18n.translate(key, :locale => @options[:locale])
end end
# Lookup month name for number # Lookup month name for number.
# month_name(1) => "January" # month_name(1) => "January"
# #
# If :use_month_numbers option is passed # If <tt>:use_month_numbers</tt> option is passed
# month_name(1) => 1 # month_name(1) => 1
# #
# If :add_month_numbers option is passed # If <tt>:add_month_numbers</tt> option is passed
# month_name(1) => "1 - January" # month_name(1) => "1 - January"
def month_name(number) def month_name(number)
if @options[:use_month_numbers] if @options[:use_month_numbers]
@ -832,16 +833,22 @@ module ActionView
I18n.translate(:'date.order', :locale => @options[:locale]) || [] I18n.translate(:'date.order', :locale => @options[:locale]) || []
end end
# Build full select tag from date type and options # Build full select tag from date type and options.
def build_options_and_select(type, selected, options = {}) def build_options_and_select(type, selected, options = {})
build_select(type, build_options(selected, options)) build_select(type, build_options(selected, options))
end end
# Build select option html from date value and options # Build select option html from date value and options.
# build_options(15, :start => 1, :end => 31) # build_options(15, :start => 1, :end => 31)
# => "<option value="1">1</option> # => "<option value="1">1</option>
# <option value=\"2\">2</option> # <option value=\"2\">2</option>
# <option value=\"3\">3</option>..." # <option value=\"3\">3</option>..."
#
# If <tt>:step</tt> options is passed
# build_options(15, :start => 1, :end => 31, :step => 2)
# => "<option value="1">1</option>
# <option value=\"3\">3</option>
# <option value=\"5\">5</option>..."
def build_options(selected, options = {}) def build_options(selected, options = {})
start = options.delete(:start) || 0 start = options.delete(:start) || 0
stop = options.delete(:end) || 59 stop = options.delete(:end) || 59
@ -860,7 +867,7 @@ module ActionView
(select_options.join("\n") + "\n").html_safe (select_options.join("\n") + "\n").html_safe
end end
# Builds select tag from date type and html select options # Builds select tag from date type and html select options.
# build_select(:month, "<option value="1">January</option>...") # build_select(:month, "<option value="1">January</option>...")
# => "<select id="post_written_on_2i" name="post[written_on(2i)]"> # => "<select id="post_written_on_2i" name="post[written_on(2i)]">
# <option value="1">January</option>... # <option value="1">January</option>...
@ -880,7 +887,7 @@ module ActionView
(content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe (content_tag(:select, select_html.html_safe, select_options) + "\n").html_safe
end end
# Builds a prompt option tag with supplied options or from default options # Builds a prompt option tag with supplied options or from default options.
# prompt_option_tag(:month, :prompt => 'Select month') # prompt_option_tag(:month, :prompt => 'Select month')
# => "<option value="">Select month</option>" # => "<option value="">Select month</option>"
def prompt_option_tag(type, options) def prompt_option_tag(type, options)
@ -897,7 +904,7 @@ module ActionView
prompt ? content_tag(:option, prompt, :value => '') : '' prompt ? content_tag(:option, prompt, :value => '') : ''
end end
# Builds hidden input tag for date part and value # Builds hidden input tag for date part and value.
# build_hidden(:year, 2008) # build_hidden(:year, 2008)
# => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />" # => "<input id="post_written_on_1i" name="post[written_on(1i)]" type="hidden" value="2008" />"
def build_hidden(type, value) def build_hidden(type, value)
@ -909,7 +916,7 @@ module ActionView
}.merge(@html_options.slice(:disabled))) + "\n").html_safe }.merge(@html_options.slice(:disabled))) + "\n").html_safe
end end
# Returns the name attribute for the input tag # Returns the name attribute for the input tag.
# => post[written_on(1i)] # => post[written_on(1i)]
def input_name_from_type(type) def input_name_from_type(type)
prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX prefix = @options[:prefix] || ActionView::Helpers::DateTimeSelector::DEFAULT_PREFIX
@ -923,7 +930,7 @@ module ActionView
@options[:discard_type] ? prefix : "#{prefix}[#{field_name}]" @options[:discard_type] ? prefix : "#{prefix}[#{field_name}]"
end end
# Returns the id attribute for the input tag # Returns the id attribute for the input tag.
# => "post_written_on_1i" # => "post_written_on_1i"
def input_id_from_type(type) def input_id_from_type(type)
input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '') input_name_from_type(type).gsub(/([\[\(])|(\]\[)/, '_').gsub(/[\]\)]/, '')
@ -940,7 +947,7 @@ module ActionView
select.html_safe select.html_safe
end end
# Returns the separator for a given datetime component # Returns the separator for a given datetime component.
def separator(type) def separator(type)
case type case type
when :year when :year

View file

@ -274,10 +274,10 @@ module ActionView
# You can optionally provide html attributes as the last element of the array. # You can optionally provide html attributes as the last element of the array.
# #
# Examples: # Examples:
# options_for_select([ "Denmark", ["USA", {:class=>'bold'}], "Sweden" ], ["USA", "Sweden"]) # options_for_select([ "Denmark", ["USA", {:class => 'bold'}], "Sweden" ], ["USA", "Sweden"])
# <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option> # <option value="Denmark">Denmark</option>\n<option value="USA" class="bold" selected="selected">USA</option>\n<option value="Sweden" selected="selected">Sweden</option>
# #
# options_for_select([["Dollar", "$", {:class=>"bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]]) # options_for_select([["Dollar", "$", {:class => "bold"}], ["Kroner", "DKK", {:onclick => "alert('HI');"}]])
# <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option> # <option value="$" class="bold">Dollar</option>\n<option value="DKK" onclick="alert('HI');">Kroner</option>
# #
# If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value # If you wish to specify disabled option tags, set +selected+ to be a hash, with <tt>:disabled</tt> being either a value

View file

@ -82,22 +82,22 @@ module ActionView
# select_tag "people", options_from_collection_for_select(@people, "id", "name") # select_tag "people", options_from_collection_for_select(@people, "id", "name")
# # <select id="people" name="people"><option value="1">David</option></select> # # <select id="people" name="people"><option value="1">David</option></select>
# #
# select_tag "people", "<option>David</option>" # select_tag "people", "<option>David</option>".html_safe
# # => <select id="people" name="people"><option>David</option></select> # # => <select id="people" name="people"><option>David</option></select>
# #
# select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>" # select_tag "count", "<option>1</option><option>2</option><option>3</option><option>4</option>".html_safe
# # => <select id="count" name="count"><option>1</option><option>2</option> # # => <select id="count" name="count"><option>1</option><option>2</option>
# # <option>3</option><option>4</option></select> # # <option>3</option><option>4</option></select>
# #
# select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>", :multiple => true # select_tag "colors", "<option>Red</option><option>Green</option><option>Blue</option>".html_safe, :multiple => true
# # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option> # # => <select id="colors" multiple="multiple" name="colors[]"><option>Red</option>
# # <option>Green</option><option>Blue</option></select> # # <option>Green</option><option>Blue</option></select>
# #
# select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>" # select_tag "locations", "<option>Home</option><option selected="selected">Work</option><option>Out</option>".html_safe
# # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option> # # => <select id="locations" name="locations"><option>Home</option><option selected='selected'>Work</option>
# # <option>Out</option></select> # # <option>Out</option></select>
# #
# select_tag "access", "<option>Read</option><option>Write</option>", :multiple => true, :class => 'form_input' # select_tag "access", "<option>Read</option><option>Write</option>".html_safe, :multiple => true, :class => 'form_input'
# # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option> # # => <select class="form_input" id="access" multiple="multiple" name="access[]"><option>Read</option>
# # <option>Write</option></select> # # <option>Write</option></select>
# #
@ -107,7 +107,7 @@ module ActionView
# select_tag "people", options_from_collection_for_select(@people, "id", "name"), :prompt => "Select something" # select_tag "people", options_from_collection_for_select(@people, "id", "name"), :prompt => "Select something"
# # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select> # # => <select id="people" name="people"><option value="">Select something</option><option value="1">David</option></select>
# #
# select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>", :disabled => true # select_tag "destination", "<option>NYC</option><option>Paris</option><option>Rome</option>".html_safe, :disabled => true
# # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option> # # => <select disabled="disabled" id="destination" name="destination"><option>NYC</option>
# # <option>Paris</option><option>Rome</option></select> # # <option>Paris</option><option>Rome</option></select>
def select_tag(name, option_tags = nil, options = {}) def select_tag(name, option_tags = nil, options = {})

View file

@ -15,10 +15,10 @@ module ActionView
# = Action View Translation Helpers # = Action View Translation Helpers
module Helpers module Helpers
module TranslationHelper module TranslationHelper
# Delegates to I18n#translate but also performs three additional functions. # Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
# #
# First, it'll pass the :rescue_format => :html option to I18n so that any # First, it'll pass the <tt>:rescue_format => :html</tt> option to I18n so that any
# thrown MissingTranslation messages will be turned into inline spans that # thrown +MissingTranslation+ messages will be turned into inline spans that
# #
# * have a "translation-missing" class set, # * have a "translation-missing" class set,
# * contain the missing key as a title attribute and # * contain the missing key as a title attribute and
@ -54,7 +54,7 @@ module ActionView
end end
alias :t :translate alias :t :translate
# Delegates to I18n.localize with no additional functionality. # Delegates to <tt>I18n.localize</tt> with no additional functionality.
def localize(*args) def localize(*args)
I18n.localize(*args) I18n.localize(*args)
end end

View file

@ -420,7 +420,7 @@ module ActionView
end end
# Creates a link tag of the given +name+ using a URL created by the set of # Creates a link tag of the given +name+ using a URL created by the set of
# +options+ if +condition+ is true, in which case only the name is # +options+ if +condition+ is true, otherwise only the name is
# returned. To specialize the default behavior, you can pass a block that # returned. To specialize the default behavior, you can pass a block that
# accepts the name or the full argument list for +link_to_unless+ (see the examples # accepts the name or the full argument list for +link_to_unless+ (see the examples
# in +link_to_unless+). # in +link_to_unless+).

View file

@ -79,9 +79,9 @@ module ActionView
# you are handling out-of-band metadata, you are # you are handling out-of-band metadata, you are
# also responsible for alerting the user to any # also responsible for alerting the user to any
# problems with converting the user's data to # problems with converting the user's data to
# the default_internal. # the <tt>default_internal</tt>.
# #
# To do so, simply raise the raise WrongEncodingError # To do so, simply raise the raise +WrongEncodingError+
# as follows: # as follows:
# #
# raise WrongEncodingError.new( # raise WrongEncodingError.new(
@ -198,7 +198,7 @@ module ActionView
# Among other things, this method is responsible for properly setting # Among other things, this method is responsible for properly setting
# the encoding of the source. Until this point, we assume that the # the encoding of the source. Until this point, we assume that the
# source is BINARY data. If no additional information is supplied, # source is BINARY data. If no additional information is supplied,
# we assume the encoding is the same as Encoding.default_external. # we assume the encoding is the same as <tt>Encoding.default_external</tt>.
# #
# The user can also specify the encoding via a comment on the first # The user can also specify the encoding via a comment on the first
# line of the template (# encoding: NAME-OF-ENCODING). This will work # line of the template (# encoding: NAME-OF-ENCODING). This will work
@ -212,8 +212,8 @@ module ActionView
# specifying the encoding. For instance, ERB supports <%# encoding: %> # specifying the encoding. For instance, ERB supports <%# encoding: %>
# #
# Otherwise, after we figure out the correct encoding, we then # Otherwise, after we figure out the correct encoding, we then
# encode the source into Encoding.default_internal. In general, # encode the source into <tt>Encoding.default_internal</tt>.
# this means that templates will be UTF-8 inside of Rails, # In general, this means that templates will be UTF-8 inside of Rails,
# regardless of the original source encoding. # regardless of the original source encoding.
def compile(view, mod) #:nodoc: def compile(view, mod) #:nodoc:
method_name = self.method_name method_name = self.method_name

View file

@ -21,8 +21,8 @@ module ActiveModel
# #
module Conversion module Conversion
# If your object is already designed to implement all of the Active Model # If your object is already designed to implement all of the Active Model
# you can use the default to_model implementation, which simply returns # you can use the default <tt>:to_model</tt> implementation, which simply
# self. # returns self.
# #
# If your model does not act like an Active Model object, then you should # If your model does not act like an Active Model object, then you should
# define <tt>:to_model</tt> yourself returning a proxy object that wraps # define <tt>:to_model</tt> yourself returning a proxy object that wraps
@ -35,13 +35,13 @@ module ActiveModel
# if the object is persisted or not. # if the object is persisted or not.
# #
# Note the default implementation uses persisted? just because all objects # Note the default implementation uses persisted? just because all objects
# in Ruby 1.8.x responds to :id. # in Ruby 1.8.x responds to <tt>:id</tt>.
def to_key def to_key
persisted? ? [id] : nil persisted? ? [id] : nil
end end
# Returns a string representing the object's key suitable for use in URLs, # Returns a string representing the object's key suitable for use in URLs,
# or nil if persisted? is false # or nil if <tt>persisted?</tt> is false.
def to_param def to_param
persisted? ? to_key.join('-') : nil persisted? ? to_key.join('-') : nil
end end

View file

@ -1379,7 +1379,7 @@ module ActiveRecord
# [:touch] # [:touch]
# If true, the associated object will be touched (the updated_at/on attributes set to now) # If true, the associated object will be touched (the updated_at/on attributes set to now)
# when this record is either saved or destroyed. If you specify a symbol, that attribute # when this record is either saved or destroyed. If you specify a symbol, that attribute
# will be updated with the current time instead of the updated_at/on attribute. # will be updated with the current time in addition to the updated_at/on attribute.
# [:inverse_of] # [:inverse_of]
# Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated # Specifies the name of the <tt>has_one</tt> or <tt>has_many</tt> association on the associated
# object that is the inverse of this <tt>belongs_to</tt> association. Does not work in # object that is the inverse of this <tt>belongs_to</tt> association. Does not work in

View file

@ -37,12 +37,12 @@ class Array
# Converts a collection of elements into a formatted string by calling # Converts a collection of elements into a formatted string by calling
# <tt>to_s</tt> on all elements and joining them: # <tt>to_s</tt> on all elements and joining them:
# #
# Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post" # Blog.all.to_formatted_s # => "First PostSecond PostThird Post"
# #
# Adding in the <tt>:db</tt> argument as the format yields a prettier # Adding in the <tt>:db</tt> argument as the format yields a prettier
# output: # output:
# #
# Blog.find(:all).to_formatted_s(:db) # => "First Post,Second Post,Third Post" # Blog.all.to_formatted_s(:db) # => "First Post,Second Post,Third Post"
def to_formatted_s(format = :default) def to_formatted_s(format = :default)
case format case format
when :db when :db

View file

@ -7,7 +7,7 @@ class Array
# #
# [1,2,3,4,5,6].sample # => 4 # [1,2,3,4,5,6].sample # => 4
# [1,2,3,4,5,6].sample(3) # => [2, 4, 5] # [1,2,3,4,5,6].sample(3) # => [2, 4, 5]
# [1,2,3,4,5,6].sample(-3) # => ArgumentError: negative sample number # [1,2,3,4,5,6].sample(-3) # => ArgumentError: negative array size
# [].sample # => nil # [].sample # => nil
# [].sample(3) # => [] # [].sample(3) # => []
def sample(n=nil) def sample(n=nil)

View file

@ -1,8 +1,7 @@
class Array class Array
# Return an unique array based on the criteria given as a proc. # Returns an unique array based on the criteria given as a +Proc+.
# #
# [1, 2, 3, 4].uniq_by { |i| i.odd? } # [1, 2, 3, 4].uniq_by { |i| i.odd? } # => [1, 2]
# # => [1, 2]
# #
def uniq_by def uniq_by
hash, array = {}, [] hash, array = {}, []

View file

@ -51,25 +51,25 @@ class DateTime
utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon) utc? && alternate_utc_string || ActiveSupport::TimeZone.seconds_to_utc_offset(utc_offset, colon)
end end
# Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000" # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005 14:30:00 +0000".
def readable_inspect def readable_inspect
to_s(:rfc822) to_s(:rfc822)
end end
alias_method :default_inspect, :inspect alias_method :default_inspect, :inspect
alias_method :inspect, :readable_inspect alias_method :inspect, :readable_inspect
# Converts self to a Ruby Date object; time portion is discarded # Converts self to a Ruby Date object; time portion is discarded.
def to_date def to_date
::Date.new(year, month, day) ::Date.new(year, month, day)
end unless instance_methods(false).include?(:to_date) end unless instance_methods(false).include?(:to_date)
# Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class # Attempts to convert self to a Ruby Time object; returns self if out of range of Ruby Time class.
# If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time # If self has an offset other than 0, self will just be returned unaltered, since there's no clean way to map it to a Time.
def to_time def to_time
self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self self.offset == 0 ? ::Time.utc_time(year, month, day, hour, min, sec, sec_fraction * (RUBY_VERSION < '1.9' ? 86400000000 : 1000000)) : self
end end
# To be able to keep Times, Dates and DateTimes interchangeable on conversions # To be able to keep Times, Dates and DateTimes interchangeable on conversions.
def to_datetime def to_datetime
self self
end unless instance_methods(false).include?(:to_datetime) end unless instance_methods(false).include?(:to_datetime)
@ -79,17 +79,17 @@ class DateTime
civil(year, month, day, hour, min, sec, offset) civil(year, month, day, hour, min, sec, offset)
end end
# Converts datetime to an appropriate format for use in XML # Converts datetime to an appropriate format for use in XML.
def xmlschema def xmlschema
strftime("%Y-%m-%dT%H:%M:%S%Z") strftime("%Y-%m-%dT%H:%M:%S%Z")
end unless instance_methods(false).include?(:xmlschema) end unless instance_methods(false).include?(:xmlschema)
# Converts self to a floating-point number of seconds since the Unix epoch # Converts self to a floating-point number of seconds since the Unix epoch.
def to_f def to_f
seconds_since_unix_epoch.to_f seconds_since_unix_epoch.to_f
end end
# Converts self to an integer number of seconds since the Unix epoch # Converts self to an integer number of seconds since the Unix epoch.
def to_i def to_i
seconds_since_unix_epoch.to_i seconds_since_unix_epoch.to_i
end end

View file

@ -21,7 +21,7 @@ class Hash
# Replaces the hash with only the given keys. # Replaces the hash with only the given keys.
# Returns a hash contained the removed key/value pairs # Returns a hash contained the removed key/value pairs
# {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d =>4} # {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b) # => {:c => 3, :d => 4}
def slice!(*keys) def slice!(*keys)
keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key) keys = keys.map! { |key| convert_key(key) } if respond_to?(:convert_key)
omit = slice(*self.keys - keys) omit = slice(*self.keys - keys)

View file

@ -4,10 +4,13 @@ class Integer
# Ordinalize turns a number into an ordinal string used to denote the # Ordinalize turns a number into an ordinal string used to denote the
# position in an ordered sequence such as 1st, 2nd, 3rd, 4th. # position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
# #
# 1.ordinalize # => "1st" # 1.ordinalize # => "1st"
# 2.ordinalize # => "2nd" # 2.ordinalize # => "2nd"
# 1002.ordinalize # => "1002nd" # 1002.ordinalize # => "1002nd"
# 1003.ordinalize # => "1003rd" # 1003.ordinalize # => "1003rd"
# -11.ordinalize # => "-11th"
# -1001.ordinalize # => "-1001st"
#
def ordinalize def ordinalize
ActiveSupport::Inflector.ordinalize(self) ActiveSupport::Inflector.ordinalize(self)
end end

View file

@ -1,14 +1,14 @@
class Object class Object
# An object is blank if it's false, empty, or a whitespace string. # An object is blank if it's false, empty, or a whitespace string.
# For example, "", " ", +nil+, [], and {} are blank. # For example, "", " ", +nil+, [], and {} are all blank.
# #
# This simplifies: # This simplifies:
# #
# if !address.nil? && !address.empty? # if address.nil? || address.empty?
# #
# ...to: # ...to:
# #
# if !address.blank? # if address.blank?
def blank? def blank?
respond_to?(:empty?) ? empty? : !self respond_to?(:empty?) ? empty? : !self
end end

View file

@ -7,7 +7,7 @@ class Object
# provided. Each method called on the block variable must take an options # provided. Each method called on the block variable must take an options
# hash as its final argument. # hash as its final argument.
# #
# Without with_options, this code contains duplication: # Without <tt>with_options></tt>, this code contains duplication:
# #
# class Account < ActiveRecord::Base # class Account < ActiveRecord::Base
# has_many :customers, :dependent => :destroy # has_many :customers, :dependent => :destroy
@ -16,7 +16,7 @@ class Object
# has_many :expenses, :dependent => :destroy # has_many :expenses, :dependent => :destroy
# end # end
# #
# Using with_options, we can remove the duplication: # Using <tt>with_options</tt>, we can remove the duplication:
# #
# class Account < ActiveRecord::Base # class Account < ActiveRecord::Base
# with_options :dependent => :destroy do |assoc| # with_options :dependent => :destroy do |assoc|
@ -29,11 +29,14 @@ class Object
# #
# It can also be used with an explicit receiver: # It can also be used with an explicit receiver:
# #
# map.with_options :controller => "people" do |people| # I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
# people.connect "/people", :action => "index" # subject i18n.t :subject
# people.connect "/people/:id", :action => "show" # body i18n.t :body, :user_name => user.name
# end # end
# #
# <tt>with_options</tt> can also be nested since the call is forwarded to its receiver.
# Each nesting level will merge inherited defaults in addition to their own.
#
def with_options(options) def with_options(options)
yield ActiveSupport::OptionMerger.new(self, options) yield ActiveSupport::OptionMerger.new(self, options)
end end

View file

@ -1,6 +1,5 @@
class String class String
# Enable more predictable duck-typing on String-like classes. See # Enable more predictable duck-typing on String-like classes. See <tt>Object#acts_like?</tt>.
# Object#acts_like?.
def acts_like_string? def acts_like_string?
true true
end end

View file

@ -1,5 +1,5 @@
class String class String
# The inverse of String#include?. Returns true if the string does not include the other string. # The inverse of <tt>String#include?</tt>. Returns true if the string does not include the other string.
def exclude?(string) def exclude?(string)
!include?(string) !include?(string)
end end

View file

@ -1,7 +1,7 @@
require 'active_support/string_inquirer' require 'active_support/string_inquirer'
class String class String
# Wraps the current string in the ActiveSupport::StringInquirer class, # Wraps the current string in the <tt>ActiveSupport::StringInquirer</tt> class,
# which gives you a prettier way to test for equality. Example: # which gives you a prettier way to test for equality. Example:
# #
# env = "production".inquiry # env = "production".inquiry

View file

@ -38,9 +38,10 @@
# Note that if you are working on a guide generation will by default process # Note that if you are working on a guide generation will by default process
# only that one, so ONLY is rarely used nowadays. # only that one, so ONLY is rarely used nowadays.
# #
# LANGUAGE # GUIDES_LANGUAGE
# Use LANGUAGE when you want to generate translated guides in <tt>source/<LANGUAGE></tt> # Use GUIDES_LANGUAGE when you want to generate translated guides in
# folder (such as <tt>source/es</tt>). Ignore it when generating English guides. # <tt>source/<GUIDES_LANGUAGE></tt> folder (such as <tt>source/es</tt>).
# Ignore it when generating English guides.
# #
# EDGE # EDGE
# Set to "1" to indicate generated guides should be marked as edge. This # Set to "1" to indicate generated guides should be marked as edge. This
@ -67,7 +68,7 @@ module RailsGuides
GUIDES_RE = /\.(?:textile|html\.erb)$/ GUIDES_RE = /\.(?:textile|html\.erb)$/
def initialize(output=nil) def initialize(output=nil)
@lang = ENV['LANGUAGE'] @lang = ENV['GUIDES_LANGUAGE']
initialize_dirs(output) initialize_dirs(output)
create_output_dir_if_needed create_output_dir_if_needed
set_flags_from_environment set_flags_from_environment

View file

@ -110,6 +110,32 @@ When this form is submitted, the value of +params[:client]+ will be <tt>{"name"
Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys. Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.
h4. JSON/XML parameters
If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into +params+ hash, which you'll be able to access like you would normally do with form data.
So for example, if you are sending this JSON parameter:
<pre>
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
</pre>
You'll get <tt>params[:company]</tt> as <tt>{ :name => "acme", "address" => "123 Carrot Street" }</tt>.
Also, if you've turned on +config.wrap_parameters+ in your initializer or calling +wrap_parameters+ in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as:
<pre>
{ "name": "acme", "address": "123 Carrot Street" }
</pre>
And assume that you're sending the data to +CompaniesController+, it would then be wrapped in +:company+ key like this:
<ruby>
{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }}
</ruby>
You can customize the name of the key or specific parameters you want to wrap by consulting the "API documentation":http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html
h4. Routing Parameters h4. Routing Parameters
The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL: The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL:

View file

@ -1841,6 +1841,8 @@ The method +ordinalize+ returns the ordinal string corresponding to the receiver
2.ordinalize # => "2nd" 2.ordinalize # => "2nd"
53.ordinalize # => "53rd" 53.ordinalize # => "53rd"
2009.ordinalize # => "2009th" 2009.ordinalize # => "2009th"
-21.ordinalize # => "-21st"
-134.ordinalize # => "-134th"
</ruby> </ruby>
NOTE: Defined in +active_support/core_ext/integer/inflections.rb+. NOTE: Defined in +active_support/core_ext/integer/inflections.rb+.

View file

@ -342,9 +342,9 @@ In designing a data model, you will sometimes find a model that should have a re
<ruby> <ruby>
class Employee < ActiveRecord::Base class Employee < ActiveRecord::Base
has_many :subordinates, :class_name => "Employee", has_many :subordinates, :class_name => "Employee"
belongs_to :manager, :class_name => "Employee",
:foreign_key => "manager_id" :foreign_key => "manager_id"
belongs_to :manager, :class_name => "Employee"
end end
</ruby> </ruby>

View file

@ -98,7 +98,7 @@ You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the act
You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance. You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.
Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store. Finally, if you are using memcached or Ehcache, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store.
INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job. INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
@ -304,6 +304,35 @@ The +write+ and +fetch+ methods on this cache accept two additional options that
ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" ActionController::Base.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
</ruby> </ruby>
h4. ActiveSupport::Cache::EhcacheStore
If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
<ruby>
ActionController::Base.cache_store = :ehcache_store
</ruby>
When initializing the cache, you may use the +:ehcache_config+ option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
In addition to the standard +:expires_in+ option, the +write+ method on this cache can also accept the additional +:unless_exist+ option, which will cause the cache store to use Ehcache's +putIfAbsent+ method instead of +put+, and therefore will not overwrite an existing entry. Additionally, the +write+ method supports all of the properties exposed by the "Ehcache Element class":http://ehcache.org/apidocs/net/sf/ehcache/Element.html , including:
|_. Property |_. Argument Type |_. Description |
| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
| eternal | boolean | Sets whether the element is eternal. |
| timeToIdle, tti | int | Sets time to idle |
| timeToLive, ttl, expires_in | int | Sets time to Live |
| version | long | Sets the version attribute of the ElementAttributes object. |
These options are passed to the +write+ method as Hash options using either camelCase or underscore notation, as in the following examples:
<ruby>
Rails.cache.write('key', 'value', :time_to_idle => 60.seconds, :timeToLive => 600.seconds)
caches_action :index, :expires_in => 60.seconds, :unless_exist => true
</ruby>
For more information about Ehcache, see "http://ehcache.org/":http://ehcache.org/ .
For more information about Ehcache for JRuby and Rails, see "http://ehcache.org/documentation/jruby.html":http://ehcache.org/documentation/jruby.html
h4. Custom Cache Stores h4. Custom Cache Stores
You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application. You can create your own custom cache store by simply extending +ActiveSupport::Cache::Store+ and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.

View file

@ -232,11 +232,11 @@ You can also help out by examining pull requests that have been submitted to Rub
$ git checkout -b testing_branch $ git checkout -b testing_branch
</shell> </shell>
Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to the master branch located at https://github.com/JohnSmith/rails. Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to the topic branch located at https://github.com/JohnSmith/rails.
<shell> <shell>
$ git remote add JohnSmith git://github.com/JohnSmith/rails.git $ git remote add JohnSmith git://github.com/JohnSmith/rails.git
$ git pull JohnSmith master $ git pull JohnSmith topic
</shell> </shell>
After applying their branch, test it out! Here are some things to think about: After applying their branch, test it out! Here are some things to think about:
@ -300,10 +300,16 @@ h4. Follow the Coding Conventions
Rails follows a simple set of coding style conventions. Rails follows a simple set of coding style conventions.
* Two spaces, no tabs * Two spaces, no tabs.
* Prefer +&amp;&amp;+/+||+ over +and+/+or+ * No trailing whitespace. Blank lines should not have any space.
* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+ * Indent after private/protected.
* Follow the conventions you see used in the source already * Prefer +&amp;&amp;+/+||+ over +and+/+or+.
* Prefer class << self block over self.method for class methods.
* +MyClass.my_method(my_arg)+ not +my_method( my_arg )+ or +my_method my_arg+.
* a = b and not a=b.
* Follow the conventions you see used in the source already.
These are some guidelines and please use your best judgement in using them.
h4. Sanity Check h4. Sanity Check
@ -344,20 +350,22 @@ Navigate to the Rails "GitHub repository":https://github.com/rails/rails and pre
Add the new remote to your local repository on your local machine: Add the new remote to your local repository on your local machine:
<shell> <shell>
$ git remote add mine https://&lt;your user name&gt;@github.com/&lt;your user name&gt;/rails.git $ git remote add mine https://<your user name>@github.com/<your user name>/rails.git
</shell> </shell>
Push to your remote: Push to your remote:
<shell> <shell>
$ git push mine master $ git push mine my_new_branch
</shell> </shell>
h4. Issue a Pull Request h4. Issue a Pull Request
Navigate to the Rails repository you just pushed to (e.g. https://github.com/&lt;your user name&gt;/rails) and press "Pull Request" in the upper right hand corner. Navigate to the Rails repository you just pushed to (e.g. https://github.com/<your user name>/rails) and press "Pull Request" in the upper right hand corner.
Ensure the changesets you introduced are included in the "Commits" tab and that the "Files Changed" incorporate all of your changes. Write your branch name in branch field (is filled with master by default) and press "Update Commit Range"
Ensure the changesets you introduced are included in the "Commits" tab and that the "Files Changed" incorporate all of your changes.
Fill in some details about your potential patch including a meaningful title. When finished, press "Send pull request." Rails Core will be notified about your submission. Fill in some details about your potential patch including a meaningful title. When finished, press "Send pull request." Rails Core will be notified about your submission.
@ -377,6 +385,7 @@ All contributions, either via master or docrails, get credit in "Rails Contribut
h3. Changelog h3. Changelog
* May 12, 2011: Modified to prefer topic branches instead of master branch for users contributions by "Guillermo Iguaran":http://quillarb.org
* April 29, 2011: Reflect GitHub Issues and Pull Request workflow by "Dan Pickett":http://www.enlightsolutions.com * April 29, 2011: Reflect GitHub Issues and Pull Request workflow by "Dan Pickett":http://www.enlightsolutions.com
* April 14, 2011: Modified Contributing to the Rails Code section to add '[#ticket_number state:commited]' on patches commit messages by "Sebastian Martinez":http://wyeworks.com * April 14, 2011: Modified Contributing to the Rails Code section to add '[#ticket_number state:commited]' on patches commit messages by "Sebastian Martinez":http://wyeworks.com
* December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn * December 28, 2010: Complete revision by "Xavier Noria":credits.html#fxn

View file

@ -111,7 +111,6 @@ In order to understand what a generator template means, let's create the file +l
<ruby> <ruby>
# Add initialization content here # Add initialization content here
</ruby> </ruby>
And now let's change the generator to copy this template when invoked: And now let's change the generator to copy this template when invoked:
@ -286,8 +285,8 @@ end
Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add: Now, when the helper generator is invoked and TestUnit is configured as the test framework, it will try to invoke both +Rails::TestUnitGenerator+ and +TestUnit::MyHelperGenerator+. Since none of those are defined, we can tell our generator to invoke +TestUnit::Generators::HelperGenerator+ instead, which is defined since it's a Rails generator. To do that, we just need to add:
<ruby> <ruby>
# Search for :helper instead of :my_helper # Search for :helper instead of :my_helper
hook_for :test_framework, :as => :helper hook_for :test_framework, :as => :helper
</ruby> </ruby>
And now you can re-run scaffold for another resource and see it generating tests as well! And now you can re-run scaffold for another resource and see it generating tests as well!
@ -412,7 +411,7 @@ h4. +plugin+
+plugin+ will install a plugin into the current application. +plugin+ will install a plugin into the current application.
<ruby> <ruby>
plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git") plugin("dynamic-form", :git => "git://github.com/rails/dynamic-form.git")
</ruby> </ruby>
Available options are: Available options are:
@ -441,13 +440,13 @@ Available options are:
Any additional options passed to this method are put on the end of the line: Any additional options passed to this method are put on the end of the line:
<ruby> <ruby>
gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master") gem("devise", :git => "git://github.com/plataformatec/devise", :branch => "master")
</ruby> </ruby>
The above code will put the following line into +Gemfile+: The above code will put the following line into +Gemfile+:
<ruby> <ruby>
gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master" gem "devise", :git => "git://github.com/plataformatec/devise", :branch => "master"
</ruby> </ruby>
@ -456,7 +455,7 @@ h4. +add_source+
Adds a specified source to +Gemfile+: Adds a specified source to +Gemfile+:
<ruby> <ruby>
add_source "http://gems.github.com" add_source "http://gems.github.com"
</ruby> </ruby>
h4. +application+ h4. +application+
@ -464,7 +463,7 @@ h4. +application+
Adds a line to +config/application.rb+ directly after the application class definition. Adds a line to +config/application.rb+ directly after the application class definition.
<ruby> <ruby>
application "config.asset_host = 'http://example.com'" application "config.asset_host = 'http://example.com'"
</ruby> </ruby>
This method can also take a block: This method can also take a block:
@ -490,10 +489,10 @@ h4. +git+
Runs the specified git command: Runs the specified git command:
<ruby> <ruby>
git :init git :init
git :add => "." git :add => "."
git :commit => "-m First commit!" git :commit => "-m First commit!"
git :add => "onefile.rb", :rm => "badfile.cxx" git :add => "onefile.rb", :rm => "badfile.cxx"
</ruby> </ruby>
The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in. The values of the hash here being the arguments or options passed to the specific git command. As per the final example shown here, multiple git commands can be specified at a time, but the order of their running is not guaranteed to be the same as the order that they were specified in.
@ -503,15 +502,15 @@ h4. +vendor+
Places a file into +vendor+ which contains the specified code. Places a file into +vendor+ which contains the specified code.
<ruby> <ruby>
vendor("sekrit.rb", '#top secret stuff') vendor("sekrit.rb", '#top secret stuff')
</ruby> </ruby>
This method also takes a block: This method also takes a block:
<ruby> <ruby>
vendor("seeds.rb") do vendor("seeds.rb") do
"puts 'in ur app, seeding ur database'" "puts 'in ur app, seeding ur database'"
end end
</ruby> </ruby>
h4. +lib+ h4. +lib+
@ -519,7 +518,7 @@ h4. +lib+
Places a file into +lib+ which contains the specified code. Places a file into +lib+ which contains the specified code.
<ruby> <ruby>
lib("special.rb", 'p Rails.root') lib("special.rb", 'p Rails.root')
</ruby> </ruby>
This method also takes a block: This method also takes a block:
@ -535,7 +534,7 @@ h4. +rakefile+
Creates a Rake file in the +lib/tasks+ directory of the application. Creates a Rake file in the +lib/tasks+ directory of the application.
<ruby> <ruby>
rakefile("test.rake", 'hello there') rakefile("test.rake", 'hello there')
</ruby> </ruby>
This method also takes a block: This method also takes a block:
@ -555,7 +554,7 @@ h4. +initializer+
Creates an initializer in the +config/initializers+ directory of the application: Creates an initializer in the +config/initializers+ directory of the application:
<ruby> <ruby>
initializer("begin.rb", "puts 'this is the beginning'") initializer("begin.rb", "puts 'this is the beginning'")
</ruby> </ruby>
This method also takes a block: This method also takes a block:
@ -571,7 +570,7 @@ h4. +generate+
Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator. Runs the specified generator where the first argument is the generator name and the remaining arguments are passed directly to the generator.
<ruby> <ruby>
generate("scaffold", "forums title:string description:text") generate("scaffold", "forums title:string description:text")
</ruby> </ruby>
@ -580,7 +579,7 @@ h4. +rake+
Runs the specified Rake task. Runs the specified Rake task.
<ruby> <ruby>
rake("db:migrate") rake("db:migrate")
</ruby> </ruby>
Available options are: Available options are:
@ -593,7 +592,7 @@ h4. +capify!+
Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration. Runs the +capify+ command from Capistrano at the root of the application which generates Capistrano configuration.
<ruby> <ruby>
capify! capify!
</ruby> </ruby>
h4. +route+ h4. +route+
@ -601,7 +600,7 @@ h4. +route+
Adds text to the +config/routes.rb+ file: Adds text to the +config/routes.rb+ file:
<ruby> <ruby>
route("resources :people") route("resources :people")
</ruby> </ruby>
h4. +readme+ h4. +readme+
@ -609,7 +608,7 @@ h4. +readme+
Output the contents of a file in the template's +source_path+, usually a README. Output the contents of a file in the template's +source_path+, usually a README.
<ruby> <ruby>
readme("README") readme("README")
</ruby> </ruby>
h3. Changelog h3. Changelog

View file

@ -117,8 +117,6 @@ You can add a new middleware to the middleware stack using any of the following
* +config.middleware.insert_after(existing_middleware, new_middleware, args)+ - Adds the new middleware after the specified existing middleware in the middleware stack. * +config.middleware.insert_after(existing_middleware, new_middleware, args)+ - Adds the new middleware after the specified existing middleware in the middleware stack.
<strong>Example:</strong>
<ruby> <ruby>
# config/environment.rb # config/environment.rb
@ -134,8 +132,6 @@ h5. Swapping a Middleware
You can swap an existing middleware in the middleware stack using +config.middleware.swap+. You can swap an existing middleware in the middleware stack using +config.middleware.swap+.
<strong>Example:</strong>
<ruby> <ruby>
# config/environment.rb # config/environment.rb
@ -173,8 +169,6 @@ h4. Customizing Internal Middleware Stack
It's possible to replace the entire middleware stack with a custom stack using +ActionController::Dispatcher.middleware=+. It's possible to replace the entire middleware stack with a custom stack using +ActionController::Dispatcher.middleware=+.
<strong>Example:</strong>
Put the following in an initializer: Put the following in an initializer:
<ruby> <ruby>

View file

@ -38,7 +38,7 @@ When you do end up destroying your testing database (and it will happen, trust m
h4. Rails Sets up for Testing from the Word Go h4. Rails Sets up for Testing from the Word Go
Rails creates a +test+ folder for you as soon as you create a Rails project using +rails _application_name_+. If you list the contents of this folder then you shall see: Rails creates a +test+ folder for you as soon as you create a Rails project using +rails new+ _application_name_. If you list the contents of this folder then you shall see:
<shell> <shell>
$ ls -F test/ $ ls -F test/

View file

@ -117,8 +117,8 @@ module Rails
# #
# ==== Switches # ==== Switches
# #
# All hooks come with switches for user interface. If the user don't want # All hooks come with switches for user interface. If you do not want
# to use any test framework, he can do: # to use any test framework, you can do:
# #
# rails generate controller Account --skip-test-framework # rails generate controller Account --skip-test-framework
# #

View file

@ -30,7 +30,7 @@ module Rails
# generator. # generator.
# #
# This allows you to override entire operations, like the creation of the # This allows you to override entire operations, like the creation of the
# Gemfile, README, or javascript files, without needing to know exactly # Gemfile, README, or JavaScript files, without needing to know exactly
# what those operations do so you can create another template action. # what those operations do so you can create another template action.
class AppBuilder class AppBuilder
def rakefile def rakefile

View file

@ -31,7 +31,7 @@
# Use a different cache store in production # Use a different cache store in production
# config.cache_store = :mem_cache_store # config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and javascripts from an asset server # Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com" # config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)

View file

@ -1,8 +1,8 @@
Description: Description:
Stubs out a new asset placeholders. Pass the asset name, either CamelCased Stubs out new asset placeholders. Pass the asset name, either CamelCased
or under_scored. or under_scored.
To create assets within a folder, specify the assets name as a To create an asset within a folder, specify the asset's name as a
path like 'parent/name'. path like 'parent/name'.
This generates a JavaScript stub in app/assets/javascripts and a stylesheet This generates a JavaScript stub in app/assets/javascripts and a stylesheet
@ -15,6 +15,6 @@ Example:
`rails generate assets posts` `rails generate assets posts`
Posts assets. Posts assets.
Javascript: app/assets/javascripts/posts.js JavaScript: app/assets/javascripts/posts.js
Stylesheet: app/assets/stylesheets/posts.css Stylesheet: app/assets/stylesheets/posts.css