Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge docrails

  • Loading branch information...
commit e033b5d037c303a34e0c5aec2b38ec6270f00f86 1 parent 0c68d23
@lifo lifo authored
Showing with 1,765 additions and 607 deletions.
  1. +1 −1  actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb
  2. +1 −1  actionpack/lib/action_controller/base/http_authentication.rb
  3. +1 −2  actionpack/lib/action_controller/base/request_forgery_protection.rb
  4. +1 −1  actionpack/lib/action_controller/routing.rb
  5. +1 −1  actionpack/lib/action_controller/routing/generation/url_rewriter.rb
  6. +1 −1  actionpack/lib/action_controller/routing/route_set.rb
  7. +2 −2 actionpack/lib/action_controller/testing/test_case.rb
  8. +5 −5 actionpack/lib/action_view/helpers/date_helper.rb
  9. +21 −21 actionpack/lib/action_view/helpers/form_options_helper.rb
  10. +2 −2 actionpack/lib/action_view/helpers/text_helper.rb
  11. +48 −49 actionpack/lib/action_view/helpers/url_helper.rb
  12. +1 −1  activerecord/lib/active_record.rb
  13. +2 −2 activerecord/lib/active_record/association_preload.rb
  14. +71 −5 activerecord/lib/active_record/associations.rb
  15. +2 −2 activerecord/lib/active_record/associations/association_collection.rb
  16. +39 −3 activerecord/lib/active_record/base.rb
  17. +17 −1 activerecord/lib/active_record/callbacks.rb
  18. +1 −1  activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
  19. +8 −0 activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
  20. +1 −1  activerecord/lib/active_record/fixtures.rb
  21. +3 −3 activerecord/lib/active_record/migration.rb
  22. +1 −1  activerecord/lib/active_record/nested_attributes.rb
  23. +1 −1  activerecord/lib/active_record/validations.rb
  24. +4 −0 activesupport/lib/active_support/buffered_logger.rb
  25. +3 −3 activesupport/lib/active_support/cache/mem_cache_store.rb
  26. +1 −1  activesupport/lib/active_support/callbacks.rb
  27. +1 −1  activesupport/lib/active_support/core_ext/array/conversions.rb
  28. +1 −1  activesupport/lib/active_support/core_ext/enumerable.rb
  29. +1 −1  activesupport/lib/active_support/core_ext/object/duplicable.rb
  30. +1 −1  activesupport/lib/active_support/core_ext/time/marshal_with_utc_flag.rb
  31. +3 −3 activesupport/lib/active_support/inflector.rb
  32. +1 −1  activesupport/lib/active_support/xml_mini/jdom.rb
  33. +1 −1  activesupport/lib/active_support/xml_mini/nokogiri.rb
  34. +1 −1  activesupport/lib/active_support/xml_mini/rexml.rb
  35. +45 −46 railties/README
  36. +1 −1  railties/configs/seeds.rb
  37. +0 −1  railties/guides/files/javascripts/guides.js
  38. BIN  railties/guides/images/fxn.jpg
  39. BIN  railties/guides/images/fxn.png
  40. +20 −13 railties/guides/source/action_controller_overview.textile
  41. +16 −14 railties/guides/source/action_mailer_basics.textile
  42. +3 −3 railties/guides/source/active_record_basics.textile
  43. +5 −12 railties/guides/source/active_record_querying.textile
  44. +818 −0 railties/guides/source/active_support_overview.textile
  45. +4 −4 railties/guides/source/activerecord_validations_callbacks.textile
  46. +94 −0 railties/guides/source/ajax_on_rails.textile
  47. +44 −9 railties/guides/source/association_basics.textile
  48. +66 −196 railties/guides/source/caching_with_rails.textile
  49. +1 −1  railties/guides/source/configuring.textile
  50. +1 −1  railties/guides/source/contribute.textile
  51. +10 −1 railties/guides/source/contributing_to_rails.textile
  52. +3 −3 railties/guides/source/credits.erb.textile
  53. +1 −1  railties/guides/source/debugging_rails_applications.textile
  54. +15 −13 railties/guides/source/form_helpers.textile
  55. +71 −58 railties/guides/source/getting_started.textile
  56. +25 −58 railties/guides/source/i18n.textile
  57. +1 −1  railties/guides/source/index.erb.textile
  58. +19 −19 railties/guides/source/layouts_and_rendering.textile
  59. +6 −6 railties/guides/source/migrations.textile
  60. +1 −1  railties/guides/source/performance_testing.textile
  61. +1 −1  railties/guides/source/plugins.textile
  62. +226 −6 railties/guides/source/rails_application_templates.textile
  63. +2 −2 railties/guides/source/rails_on_rack.textile
  64. +4 −4 railties/guides/source/routing.textile
  65. +3 −3 railties/guides/source/security.textile
  66. +10 −8 railties/guides/source/testing.textile
View
2  actionmailer/lib/action_mailer/vendor/tmail-1.2.3/tmail/obsolete.rb
@@ -1,6 +1,6 @@
=begin rdoc
-= Obsolete methods that are depriciated
+= Obsolete methods that are deprecated
If you really want to see them, go to lib/tmail/obsolete.rb and view to your
heart's content.
View
2  actionpack/lib/action_controller/base/http_authentication.rb
@@ -276,7 +276,7 @@ def authentication_request(controller, realm, message = nil)
#
# The nonce is opaque to the client. Composed of Time, and hash of Time with secret
# key from the Rails session secret generated upon creation of project. Ensures
- # the time cannot be modifed by client.
+ # the time cannot be modified by client.
def nonce(time = Time.now)
t = time.to_i
hashed = [t, secret_key]
View
3  actionpack/lib/action_controller/base/request_forgery_protection.rb
@@ -106,8 +106,7 @@ def verifiable_request_format?
!request.content_type.nil? && request.content_type.verify_request?
end
- # Sets the token value for the current session. Pass a <tt>:secret</tt> option
- # in +protect_from_forgery+ to add a custom salt to the hash.
+ # Sets the token value for the current session.
def form_authenticity_token
session[:_csrf_token] ||= ActiveSupport::SecureRandom.base64(32)
end
View
2  actionpack/lib/action_controller/routing.rb
@@ -139,7 +139,7 @@ module ActionController
# # In routes.rb
# map.with_options :controller => 'blog' do |blog|
# blog.show '', :action => 'list'
- # blog.delete 'delete/:id', :action => 'delete',
+ # blog.delete 'delete/:id', :action => 'delete'
# blog.edit 'edit/:id', :action => 'edit'
# end
#
View
2  actionpack/lib/action_controller/routing/generation/url_rewriter.rb
@@ -93,7 +93,7 @@ def self.included(base) #:nodoc:
#
# * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
- # * <tt>:host</tt> - Specifies the host the link should be targetted at.
+ # * <tt>:host</tt> - Specifies the host the link should be targeted at.
# If <tt>:only_path</tt> is false, this option must be
# provided either explicitly, or via +default_url_options+.
# * <tt>:port</tt> - Optionally specify the port to connect to.
View
2  actionpack/lib/action_controller/routing/route_set.rb
@@ -155,7 +155,7 @@ def #{selector}(options = nil) # def hash_f
def define_url_helper(route, name, kind, options)
selector = url_helper_name(name, kind)
- # The segment keys used for positional paramters
+ # The segment keys used for positional parameters
hash_access_method = hash_access_name(name, kind)
View
4 actionpack/lib/action_controller/testing/test_case.rb
@@ -56,7 +56,7 @@ module ActionController
#
# ActionController::TestCase will automatically infer the controller under test
# from the test class name. If the controller cannot be inferred from the test
- # class name, you can explicity set it with +tests+.
+ # class name, you can explicitly set it with +tests+.
#
# class SpecialEdgeCaseWidgetsControllerTest < ActionController::TestCase
# tests WidgetController
@@ -182,7 +182,7 @@ def setup_controller_request_and_response
@controller.send(:initialize_current_url)
end
end
-
+
# Cause the action to be rescued according to the regular rules for rescue_action when the visitor is not local
def rescue_action_in_public!
@request.remote_addr = '208.77.188.166' # example.com
View
10 actionpack/lib/action_view/helpers/date_helper.rb
@@ -112,12 +112,12 @@ def time_ago_in_words(from_time, include_seconds = false)
# ==== Options
# * <tt>:use_month_numbers</tt> - Set to true if you want to use month numbers rather than month names (e.g.
# "2" instead of "February").
- # * <tt>:use_short_month</tt> - Set to true if you want to use the abbreviated month name instead of the full
- # name (e.g. "Feb" instead of "February").
- # * <tt>:add_month_number</tt> - Set to true if you want to show both, the month's number and name (e.g.
+ # * <tt>:use_short_month</tt> - Set to true if you want to use abbreviated month names instead of full
+ # month names (e.g. "Feb" instead of "February").
+ # * <tt>:add_month_numbers</tt> - Set to true if you want to use both month numbers and month names (e.g.
# "2 - February" instead of "February").
# * <tt>:use_month_names</tt> - Set to an array with 12 month names if you want to customize month names.
- # Note: You can also use Rails' new i18n functionality for this.
+ # Note: You can also use Rails' i18n functionality for this.
# * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing).
# * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Time.now.year - 5</tt>.
# * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Time.now.year + 5</tt>.
@@ -128,7 +128,7 @@ def time_ago_in_words(from_time, include_seconds = false)
# as a hidden field instead of showing a select field. Also note that this implicitly sets :discard_day to true.
# * <tt>:discard_year</tt> - Set to true if you don't want to show a year select. This includes the year
# as a hidden field instead of showing a select field.
- # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> do
+ # * <tt>:order</tt> - Set to an array containing <tt>:day</tt>, <tt>:month</tt> and <tt>:year</tt> to
# customize the order in which the select fields are shown. If you leave out any of the symbols, the respective
# select will not be shown (like when you set <tt>:discard_xxx => true</tt>. Defaults to the order defined in
# the respective locale (e.g. [:year, :month, :day] in the en locale that ships with Rails).
View
42 actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -167,31 +167,31 @@ def collection_select(object, method, collection, value_method, text_method, opt
#
# In addition to the <tt>:include_blank</tt> option documented above,
# this method also supports a <tt>:model</tt> option, which defaults
- # to TimeZone. This may be used by users to specify a different time
- # zone model object. (See +time_zone_options_for_select+ for more
- # information.)
+ # to ActiveSupport::TimeZone. This may be used by users to specify a
+ # different time zone model object. (See +time_zone_options_for_select+
+ # for more information.)
#
- # You can also supply an array of TimeZone objects
+ # You can also supply an array of ActiveSupport::TimeZone objects
# as +priority_zones+, so that they will be listed above the rest of the
- # (long) list. (You can use TimeZone.us_zones as a convenience for
- # obtaining a list of the US time zones, or a Regexp to select the zones
+ # (long) list. (You can use ActiveSupport::TimeZone.us_zones as a convenience
+ # for obtaining a list of the US time zones, or a Regexp to select the zones
# of your choice)
#
# Finally, this method supports a <tt>:default</tt> option, which selects
- # a default TimeZone if the object's time zone is +nil+.
+ # a default ActiveSupport::TimeZone if the object's time zone is +nil+.
#
# Examples:
# time_zone_select( "user", "time_zone", nil, :include_blank => true)
#
# time_zone_select( "user", "time_zone", nil, :default => "Pacific Time (US & Canada)" )
#
- # time_zone_select( "user", 'time_zone', TimeZone.us_zones, :default => "Pacific Time (US & Canada)")
+ # time_zone_select( "user", 'time_zone', ActiveSupport::TimeZone.us_zones, :default => "Pacific Time (US & Canada)")
#
- # time_zone_select( "user", 'time_zone', [ TimeZone['Alaska'], TimeZone['Hawaii'] ])
+ # time_zone_select( "user", 'time_zone', [ ActiveSupport::TimeZone['Alaska'], ActiveSupport::TimeZone['Hawaii'] ])
#
# time_zone_select( "user", 'time_zone', /Australia/)
#
- # time_zone_select( "user", "time_zone", TZInfo::Timezone.all.sort, :model => TZInfo::Timezone)
+ # time_zone_select( "user", "time_zone", ActiveSupport::Timezone.all.sort, :model => ActiveSupport::Timezone)
def time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
InstanceTag.new(object, method, self, options.delete(:object)).to_time_zone_select_tag(priority_zones, options, html_options)
end
@@ -393,20 +393,20 @@ def grouped_options_for_select(grouped_options, selected_key = nil, prompt = nil
end
# Returns a string of option tags for pretty much any time zone in the
- # world. Supply a TimeZone name as +selected+ to have it marked as the
- # selected option tag. You can also supply an array of TimeZone objects
- # as +priority_zones+, so that they will be listed above the rest of the
- # (long) list. (You can use TimeZone.us_zones as a convenience for
- # obtaining a list of the US time zones, or a Regexp to select the zones
- # of your choice)
+ # world. Supply a ActiveSupport::TimeZone name as +selected+ to have it
+ # marked as the selected option tag. You can also supply an array of
+ # ActiveSupport::TimeZone objects as +priority_zones+, so that they will
+ # be listed above the rest of the (long) list. (You can use
+ # ActiveSupport::TimeZone.us_zones as a convenience for obtaining a list
+ # of the US time zones, or a Regexp to select the zones of your choice)
#
# The +selected+ parameter must be either +nil+, or a string that names
- # a TimeZone.
+ # a ActiveSupport::TimeZone.
#
- # By default, +model+ is the TimeZone constant (which can be obtained
- # in Active Record as a value object). The only requirement is that the
- # +model+ parameter be an object that responds to +all+, and returns
- # an array of objects that represent time zones.
+ # By default, +model+ is the ActiveSupport::TimeZone constant (which can
+ # be obtained in Active Record as a value object). The only requirement
+ # is that the +model+ parameter be an object that responds to +all+, and
+ # returns an array of objects that represent time zones.
#
# NOTE: Only the option tags are returned, you have to wrap this call in
# a regular HTML select tag.
View
4 actionpack/lib/action_view/helpers/text_helper.rb
@@ -436,7 +436,7 @@ def cycle(first_value, *values)
end
# Returns the current cycle string after a cycle has been started. Useful
- # for complex table highlighing or any other design need which requires
+ # for complex table highlighting or any other design need which requires
# the current cycle string in more than one place.
#
# ==== Example
@@ -544,7 +544,7 @@ def auto_link_urls(text, html_options = {})
left, right = $`, $'
# detect already linked URLs and URLs in the middle of a tag
if left =~ /<[^>]+$/ && right =~ /^[^>]*>/
- # do not change string; URL is alreay linked
+ # do not change string; URL is already linked
href
else
# don't include trailing punctuation character as part of the URL
View
97 actionpack/lib/action_view/helpers/url_helper.rb
@@ -12,11 +12,11 @@ module UrlHelper
# Returns the URL for the set of +options+ provided. This takes the
# same options as +url_for+ in Action Controller (see the
- # documentation for ActionController::Base#url_for). Note that by default
- # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative /controller/action
- # instead of the fully qualified URL like http://example.com/controller/action.
+ # documentation for <tt>ActionController::Base#url_for</tt>). Note that by default
+ # <tt>:only_path</tt> is <tt>true</tt> so you'll get the relative "/controller/action"
+ # instead of the fully qualified URL like "http://example.com/controller/action".
#
- # When called from a view, url_for returns an HTML escaped url. If you
+ # When called from a view, +url_for+ returns an HTML escaped url. If you
# need an unescaped url, pass <tt>:escape => false</tt> in the +options+.
#
# ==== Options
@@ -34,8 +34,8 @@ module UrlHelper
#
# If you instead of a hash pass a record (like an Active Record or Active Resource) as the options parameter,
# you'll trigger the named route for that record. The lookup will happen on the name of the class. So passing
- # a Workshop object will attempt to use the workshop_path route. If you have a nested route, such as
- # admin_workshop_path you'll have to call that explicitly (it's impossible for url_for to guess that route).
+ # a Workshop object will attempt to use the +workshop_path+ route. If you have a nested route, such as
+ # +admin_workshop_path+ you'll have to call that explicitly (it's impossible for +url_for+ to guess that route).
#
# ==== Examples
# <%= url_for(:action => 'index') %>
@@ -97,10 +97,10 @@ def url_for(options = {})
# Creates a link tag of the given +name+ using a URL created by the set
# of +options+. See the valid options in the documentation for
- # url_for. It's also possible to pass a string instead
+ # +url_for+. It's also possible to pass a string instead
# of an options hash to get a link tag that uses the value of the string as the
# href for the link, or use <tt>:back</tt> to link to the referrer - a JavaScript back
- # link will be used in place of a referrer if none exists. If nil is passed as
+ # link will be used in place of a referrer if none exists. If +nil+ is passed as
# a name, the link itself will become the name.
#
# ==== Signatures
@@ -117,27 +117,22 @@ def url_for(options = {})
# * <tt>:popup => true || array of window options</tt> - This will force the
# link to open in a popup window. By passing true, a default browser window
# will be opened with the URL. You can also specify an array of options
- # that are passed-thru to JavaScripts window.open method.
+ # that are passed to the <tt>window.open</tt> JavaScript call.
# * <tt>:method => symbol of HTTP verb</tt> - This modifier will dynamically
# create an HTML form and immediately submit the form for processing using
# the HTTP verb specified. Useful for having links perform a POST operation
# in dangerous actions like deleting a record (which search bots can follow
# while spidering your site). Supported verbs are <tt>:post</tt>, <tt>:delete</tt> and <tt>:put</tt>.
# Note that if the user has JavaScript disabled, the request will fall back
- # to using GET. If you are relying on the POST behavior, you should check
- # for it in your controller's action by using the request object's methods
- # for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
+ # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript
+ # disabled clicking the link will have no effect. If you are relying on the
+ # POST behavior, you should check for it in your controller's action by using
+ # the request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
# * The +html_options+ will accept a hash of html attributes for the link tag.
#
- # Note that if the user has JavaScript disabled, the request will fall back
- # to using GET. If <tt>:href => '#'</tt> is used and the user has JavaScript disabled
- # clicking the link will have no effect. If you are relying on the POST
- # behavior, your should check for it in your controller's action by using the
- # request object's methods for <tt>post?</tt>, <tt>delete?</tt> or <tt>put?</tt>.
- #
# You can mix and match the +html_options+ with the exception of
- # <tt>:popup</tt> and <tt>:method</tt> which will raise an ActionView::ActionViewError
- # exception.
+ # <tt>:popup</tt> and <tt>:method</tt> which will raise an
+ # <tt>ActionView::ActionViewError</tt> exception.
#
# ==== Examples
# Because it relies on +url_for+, +link_to+ supports both older-style controller/action/id arguments
@@ -170,9 +165,11 @@ def url_for(options = {})
# You can use a block as well if your link target is hard to fit into the name parameter. ERb example:
#
# <% link_to(@profile) do %>
- # <strong><%= @profile.name %></strong> -- <span>Check it out!!</span>
+ # <strong><%= @profile.name %></strong> -- <span>Check it out!</span>
# <% end %>
- # # => <a href="/profiles/1"><strong>David</strong> -- <span>Check it out!!</span></a>
+ # # => <a href="/profiles/1">
+ # <strong>David</strong> -- <span>Check it out!</span>
+ # </a>
#
# Classes and ids for CSS are easy to produce:
#
@@ -215,7 +212,9 @@ def url_for(options = {})
# # => <a href="/images/9" onclick="if (confirm('Are you sure?')) { var f = document.createElement('form');
# f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
# var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
- # m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete Image</a>
+ # m.setAttribute('value', 'delete');var s = document.createElement('input'); s.setAttribute('type', 'hidden');
+ # s.setAttribute('name', 'authenticity_token'); s.setAttribute('value', 'Q/ttlxPYZ6R77B+vZ1sBkhj21G2isO9dpE6UtOHBApg=');
+ # f.appendChild(s)f.appendChild(m);f.submit(); };return false;">Delete Image</a>
def link_to(*args, &block)
if block_given?
options = args.first || {}
@@ -246,21 +245,21 @@ def link_to(*args, &block)
# by the set of +options+. This is the safest method to ensure links that
# cause changes to your data are not triggered by search bots or accelerators.
# If the HTML button does not work with your layout, you can also consider
- # using the link_to method with the <tt>:method</tt> modifier as described in
- # the link_to documentation.
+ # using the +link_to+ method with the <tt>:method</tt> modifier as described in
+ # the +link_to+ documentation.
#
- # The generated FORM element has a class name of <tt>button-to</tt>
+ # The generated form element has a class name of <tt>button-to</tt>
# to allow styling of the form itself and its children. You can control
# the form submission and input element behavior using +html_options+.
# This method accepts the <tt>:method</tt> and <tt>:confirm</tt> modifiers
- # described in the link_to documentation. If no <tt>:method</tt> modifier
+ # described in the +link_to+ documentation. If no <tt>:method</tt> modifier
# is given, it will default to performing a POST operation. You can also
# disable the button by passing <tt>:disabled => true</tt> in +html_options+.
# If you are using RESTful routes, you can pass the <tt>:method</tt>
# to change the HTTP verb used to submit the form.
#
# ==== Options
- # The +options+ hash accepts the same options at url_for.
+ # The +options+ hash accepts the same options as url_for.
#
# There are a few special +html_options+:
# * <tt>:method</tt> - Specifies the anchor name to be appended to the path.
@@ -317,7 +316,7 @@ def button_to(name, options = {}, html_options = {})
# Creates a link tag of the given +name+ using a URL created by the set of
# +options+ unless the current request URI is the same as the links, in
# which case only the name is returned (or the given block is yielded, if
- # one exists). You can give link_to_unless_current a block which will
+ # one exists). You can give +link_to_unless_current+ a block which will
# specialize the default behavior (e.g., show a "Start Here" link rather
# than the link's text).
#
@@ -343,7 +342,7 @@ def button_to(name, options = {}, html_options = {})
# <li><a href="/controller/about">About Us</a></li>
# </ul>
#
- # The implicit block given to link_to_unless_current is evaluated if the current
+ # The implicit block given to +link_to_unless_current+ is evaluated if the current
# action is the action given. So, if we had a comments page and wanted to render a
# "Go Back" link instead of a link to the comments page, we could do something like this...
#
@@ -360,7 +359,7 @@ def link_to_unless_current(name, options = {}, html_options = {}, &block)
# +options+ unless +condition+ is true, in which case only the name is
# returned. To specialize the default behavior (i.e., show a login link rather
# than just the plaintext link text), you can pass a block that
- # accepts the name or the full argument list for link_to_unless.
+ # accepts the name or the full argument list for +link_to_unless+.
#
# ==== Examples
# <%= link_to_unless(@current_user.nil?, "Reply", { :action => "reply" }) %>
@@ -391,8 +390,8 @@ def link_to_unless(condition, name, options = {}, html_options = {}, &block)
# 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
# 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
- # in link_to_unless).
+ # accepts the name or the full argument list for +link_to_unless+ (see the examples
+ # in +link_to_unless+).
#
# ==== Examples
# <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
@@ -416,27 +415,27 @@ def link_to_if(condition, name, options = {}, html_options = {}, &block)
# also used as the name of the link unless +name+ is specified. Additional
# HTML attributes for the link can be passed in +html_options+.
#
- # mail_to has several methods for hindering email harvesters and customizing
+ # +mail_to+ has several methods for hindering email harvesters and customizing
# the email itself by passing special keys to +html_options+.
#
# ==== Options
- # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
- # Passing "javascript" will dynamically create and encode the mailto: link then
+ # * <tt>:encode</tt> - This key will accept the strings "javascript" or "hex".
+ # Passing "javascript" will dynamically create and encode the mailto link then
# eval it into the DOM of the page. This method will not show the link on
# the page if the user has JavaScript disabled. Passing "hex" will hex
- # encode the +email_address+ before outputting the mailto: link.
- # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
+ # encode the +email_address+ before outputting the mailto link.
+ # * <tt>:replace_at</tt> - When the link +name+ isn't provided, the
# +email_address+ is used for the link label. You can use this option to
# obfuscate the +email_address+ by substituting the @ sign with the string
# given as the value.
- # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
+ # * <tt>:replace_dot</tt> - When the link +name+ isn't provided, the
# +email_address+ is used for the link label. You can use this option to
# obfuscate the +email_address+ by substituting the . in the email with the
# string given as the value.
- # * <tt>:subject</tt> - Preset the subject line of the email.
+ # * <tt>:subject</tt> - Preset the subject line of the email.
# * <tt>:body</tt> - Preset the body of the email.
- # * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
- # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
+ # * <tt>:cc</tt> - Carbon Copy addition recipients on the email.
+ # * <tt>:bcc</tt> - Blind Carbon Copy additional recipients on the email.
#
# ==== Examples
# mail_to "me@domain.com"
@@ -607,23 +606,23 @@ def method_javascript_function(method, url = '', href = nil)
submit_function << "f.submit();"
end
- # Processes the _html_options_ hash, converting the boolean
+ # Processes the +html_options+ hash, converting the boolean
# attributes from true/false form into the form required by
# HTML/XHTML. (An attribute is considered to be boolean if
- # its name is listed in the given _bool_attrs_ array.)
+ # its name is listed in the given +bool_attrs+ array.)
#
- # More specifically, for each boolean attribute in _html_options_
+ # More specifically, for each boolean attribute in +html_options+
# given as:
#
- # "attr" => bool_value
+ # "attr" => bool_value
#
- # if the associated _bool_value_ evaluates to true, it is
+ # if the associated +bool_value+ evaluates to true, it is
# replaced with the attribute's name; otherwise the attribute is
- # removed from the _html_options_ hash. (See the XHTML 1.0 spec,
+ # removed from the +html_options+ hash. (See the XHTML 1.0 spec,
# section 4.5 "Attribute Minimization" for more:
# http://www.w3.org/TR/xhtml1/#h-4.5)
#
- # Returns the updated _html_options_ hash, which is also modified
+ # Returns the updated +html_options+ hash, which is also modified
# in place.
#
# Example:
View
2  activerecord/lib/active_record.rb
@@ -33,7 +33,7 @@
end
module ActiveRecord
- # TODO: Review explicit loads to see if they will automatically be handled by the initilizer.
+ # TODO: Review explicit loads to see if they will automatically be handled by the initializer.
def self.load_all!
[Base, DynamicFinderMatch, ConnectionAdapters::AbstractAdapter]
end
View
4 activerecord/lib/active_record/association_preload.rb
@@ -28,7 +28,7 @@ module AssociationPreload #:nodoc:
# 'books' table is useful; the joined 'authors' data is just redundant, and
# processing this redundant data takes memory and CPU time. The problem
# quickly becomes worse and worse as the level of eager loading increases
- # (i.e. if ActiveRecord is to eager load the associations' assocations as
+ # (i.e. if ActiveRecord is to eager load the associations' associations as
# well).
#
# The second strategy is to use multiple database queries, one for each
@@ -58,7 +58,7 @@ module ClassMethods
# +associations+ specifies one or more associations that you want to
# preload. It may be:
# - a Symbol or a String which specifies a single association name. For
- # example, specifiying +:books+ allows this method to preload all books
+ # example, specifying +:books+ allows this method to preload all books
# for an Author.
# - an Array which specifies multiple association names. This array
# is processed recursively. For example, specifying <tt>[:avatar, :books]</tt>
View
76 activerecord/lib/active_record/associations.rb
@@ -519,13 +519,13 @@ def association_instance_set(name, association)
#
# Post.find(:all, :include => [ :author, :comments ], :conditions => ['comments.approved = ?', true])
#
- # will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
+ # This will result in a single SQL query with joins along the lines of: <tt>LEFT OUTER JOIN comments ON comments.post_id = posts.id</tt> and
# <tt>LEFT OUTER JOIN authors ON authors.id = posts.author_id</tt>. Note that using conditions like this can have unintended consequences.
# In the above example posts with no approved comments are not returned at all, because the conditions apply to the SQL statement as a whole
# and not just to the association. You must disambiguate column references for this fallback to happen, for example
# <tt>:order => "author.name DESC"</tt> will work but <tt>:order => "name DESC"</tt> will not.
#
- # If you do want eagerload only some members of an association it is usually more natural to <tt>:include</tt> an association
+ # If you do want eager load only some members of an association it is usually more natural to <tt>:include</tt> an association
# which has conditions defined on it:
#
# class Post < ActiveRecord::Base
@@ -534,7 +534,7 @@ def association_instance_set(name, association)
#
# Post.find(:all, :include => :approved_comments)
#
- # will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved.
+ # This will load posts and eager load the +approved_comments+ association, which contains only those comments that have been approved.
#
# If you eager load an association with a specified <tt>:limit</tt> option, it will be ignored, returning all the associated objects:
#
@@ -557,7 +557,7 @@ def association_instance_set(name, association)
#
# Address.find(:all, :include => :addressable)
#
- # will execute one query to load the addresses and load the addressables with one query per addressable type.
+ # This will execute one query to load the addresses and load the addressables with one query per addressable type.
# For example if all the addressables are either of class Person or Company then a total of 3 queries will be executed. The list of
# addressable types to load is determined on the back of the addresses loaded. This is not supported if Active Record has to fallback
# to the previous implementation of eager loading and will raise ActiveRecord::EagerLoadPolymorphicError. The reason is that the parent
@@ -641,6 +641,60 @@ def association_instance_set(name, association)
# end
# end
#
+ # == Bi-directional associations
+ #
+ # When you specify an association there is usually an association on the associated model that specifies the same
+ # relationship in reverse. For example, with the following models:
+ #
+ # class Dungeon < ActiveRecord::Base
+ # has_many :traps
+ # has_one :evil_wizard
+ # end
+ #
+ # class Trap < ActiveRecord::Base
+ # belongs_to :dungeon
+ # end
+ #
+ # class EvilWizard < ActiveRecord::Base
+ # belongs_to :dungeon
+ # end
+ #
+ # The +traps+ association on +Dungeon+ and the the +dungeon+ association on +Trap+ are the inverse of each other and the
+ # inverse of the +dungeon+ association on +EvilWizard+ is the +evil_wizard+ association on +Dungeon+ (and vice-versa). By default,
+ # +ActiveRecord+ doesn't do know anything about these inverse relationships and so no object loading optimisation is possible. For example:
+ #
+ # d = Dungeon.first
+ # t = d.traps.first
+ # d.level == t.dungeon.level # => true
+ # d.level = 10
+ # d.level == t.dungeon.level # => false
+ #
+ # The +Dungeon+ instances +d+ and <tt>t.dungeon</tt> in the above example refer to the same object data from the database, but are
+ # actually different in-memory copies of that data. Specifying the <tt>:inverse_of</tt> option on associations lets you tell
+ # +ActiveRecord+ about inverse relationships and it will optimise object loading. For example, if we changed our model definitions to:
+ #
+ # class Dungeon < ActiveRecord::Base
+ # has_many :traps, :inverse_of => :dungeon
+ # has_one :evil_wizard, :inverse_of => :dungeon
+ # end
+ #
+ # class Trap < ActiveRecord::Base
+ # belongs_to :dungeon, :inverse_of => :traps
+ # end
+ #
+ # class EvilWizard < ActiveRecord::Base
+ # belongs_to :dungeon, :inverse_of => :evil_wizard
+ # end
+ #
+ # Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same in-memory instance and our final <tt>d.level == t.dungeon.level</tt>
+ # will return +true+.
+ #
+ # There are limitations to <tt>:inverse_of</tt> support:
+ #
+ # * does not work with <tt>:through</tt> associations.
+ # * does not work with <tt>:polymorphic</tt> associations.
+ # * for +belongs_to+ associations +has_many+ inverse associations are ignored.
+ #
# == Type safety with <tt>ActiveRecord::AssociationTypeMismatch</tt>
#
# If you attempt to assign an object to an association that doesn't match the inferred or specified <tt>:class_name</tt>, you'll
@@ -781,6 +835,10 @@ module ClassMethods
# If false, don't validate the associated objects when saving the parent object. true by default.
# [:autosave]
# If true, always save any loaded members and destroy members marked for destruction, when saving the parent object. Off by default.
+ # [:inverse_of]
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_many</tt>
+ # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
#
# Option examples:
# has_many :comments, :order => "posted_on"
@@ -890,6 +948,10 @@ def has_many(association_id, options = {}, &extension)
# If false, don't validate the associated object when saving the parent object. +false+ by default.
# [:autosave]
# If true, always save the associated object or destroy it if marked for destruction, when saving the parent object. Off by default.
+ # [:inverse_of]
+ # Specifies the name of the <tt>belongs_to</tt> association on the associated object that is the inverse of this <tt>has_one</tt>
+ # association. Does not work in combination with <tt>:through</tt> or <tt>:as</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
#
# Option examples:
# has_one :credit_card, :dependent => :destroy # destroys the associated credit card
@@ -992,6 +1054,10 @@ def has_one(association_id, options = {})
# [:touch]
# 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 will be updated with the current time instead of the updated_at/on attribute.
+ # [:inverse_of]
+ # 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 combination with the <tt>:polymorphic</tt> options.
+ # See ActiveRecord::Associations::ClassMethods's overview on Bi-directional assocations for more detail.
#
# Option examples:
# belongs_to :firm, :foreign_key => "client_of"
@@ -1201,7 +1267,7 @@ def destroy_without_callbacks # def destroy_without_c
private
# Generates a join table name from two provided table names.
- # The names in the join table namesme end up in lexicographic order.
+ # The names in the join table names end up in lexicographic order.
#
# join_table_name("members", "clubs") # => "clubs_members"
# join_table_name("members", "special_clubs") # => "members_special_clubs"
View
4 activerecord/lib/active_record/associations/association_collection.rb
@@ -11,7 +11,7 @@ module Associations
# ones created with +build+ are added to the target. So, the target may be
# non-empty and still lack children waiting to be read from the database.
# If you look directly to the database you cannot assume that's the entire
- # collection because new records may have beed added to the target, etc.
+ # collection because new records may have been added to the target, etc.
#
# If you need to work on all current children, new and existing records,
# +load_target+ and the +loaded+ flag are your friends.
@@ -228,7 +228,7 @@ def clear
self
end
- # Destory all the records from this association.
+ # Destroy all the records from this association.
#
# See destroy for more info.
def destroy_all
View
42 activerecord/lib/active_record/base.rb
@@ -256,6 +256,12 @@ def initialize(errors)
#
# Student.find(:all, :conditions => { :grade => [9,11,12] })
#
+ # When joining tables, nested hashes or keys written in the form 'table_name.column_name' can be used to qualify the table name of a
+ # particular condition. For instance:
+ #
+ # Student.find(:all, :conditions => { :schools => { :type => 'public' }}, :joins => :schools)
+ # Student.find(:all, :conditions => { 'schools.type' => 'public' }, :joins => :schools)
+ #
# == Overwriting default accessors
#
# All column values are automatically available through basic accessors on the Active Record object, but sometimes you
@@ -854,7 +860,7 @@ def destroy(id)
# Book.update_all "author = 'David'", "title LIKE '%Rails%'"
#
# # Update all avatars migrated more than a week ago
- # Avatar.update_all ['migrated_at = ?, Time.now.utc], ['migrated_at > ?', 1.week.ago]
+ # Avatar.update_all ['migrated_at = ?', Time.now.utc], ['migrated_at > ?', 1.week.ago]
#
# # Update all books that match our conditions, but limit it to 5 ordered by date
# Book.update_all "author = 'David'", "title LIKE '%Rails%'", :order => 'created_at', :limit => 5
@@ -1055,6 +1061,21 @@ def decrement_counter(counter_name, id)
#
# To start from an all-closed default and enable attributes as needed,
# have a look at +attr_accessible+.
+ #
+ # If the access logic of your application is richer you can use <tt>Hash#except</tt>
+ # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
+ # passed to Active Record.
+ #
+ # For example, it could be the case that the list of protected attributes
+ # for a given model depends on the role of the user:
+ #
+ # # Assumes plan_id is not protected because it depends on the role.
+ # params[:account] = params[:account].except(:plan_id) unless admin?
+ # @account.update_attributes(params[:account])
+ #
+ # Note that +attr_protected+ is still applied to the received hash. Thus,
+ # with this technique you can at most _extend_ the list of protected
+ # attributes for a particular mass-assignment call.
def attr_protected(*attributes)
write_inheritable_attribute(:attr_protected, Set.new(attributes.map {|a| a.to_s}) + (protected_attributes || []))
end
@@ -1088,6 +1109,21 @@ def protected_attributes # :nodoc:
#
# customer.credit_rating = "Average"
# customer.credit_rating # => "Average"
+ #
+ # If the access logic of your application is richer you can use <tt>Hash#except</tt>
+ # or <tt>Hash#slice</tt> to sanitize the hash of parameters before they are
+ # passed to Active Record.
+ #
+ # For example, it could be the case that the list of accessible attributes
+ # for a given model depends on the role of the user:
+ #
+ # # Assumes plan_id is accessible because it depends on the role.
+ # params[:account] = params[:account].except(:plan_id) unless admin?
+ # @account.update_attributes(params[:account])
+ #
+ # Note that +attr_accessible+ is still applied to the received hash. Thus,
+ # with this technique you can at most _narrow_ the list of accessible
+ # attributes for a particular mass-assignment call.
def attr_accessible(*attributes)
write_inheritable_attribute(:attr_accessible, Set.new(attributes.map(&:to_s)) + (accessible_attributes || []))
end
@@ -1382,14 +1418,14 @@ def self_and_descendants_from_active_record#nodoc:
classes
rescue
# OPTIMIZE this rescue is to fix this test: ./test/cases/reflection_test.rb:56:in `test_human_name_for_column'
- # Appearantly the method base_class causes some trouble.
+ # Apparently the method base_class causes some trouble.
# It now works for sure.
[self]
end
# Transforms attribute key names into a more humane format, such as "First name" instead of "first_name". Example:
# Person.human_attribute_name("first_name") # => "First name"
- # This used to be depricated in favor of humanize, but is now preferred, because it automatically uses the I18n
+ # This used to be deprecated in favor of humanize, but is now preferred, because it automatically uses the I18n
# module now.
# Specify +options+ with additional translating options.
def human_attribute_name(attribute_key_name, options = {})
View
18 activerecord/lib/active_record/callbacks.rb
@@ -22,7 +22,7 @@ module ActiveRecord
# * (8) <tt>after_save</tt>
#
# That's a total of eight callbacks, which gives you immense power to react and prepare for each state in the
- # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> an existing record is similar, except that each
+ # Active Record lifecycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar, except that each
# <tt>_on_create</tt> callback is replaced by the corresponding <tt>_on_update</tt> callback.
#
# Examples:
@@ -262,6 +262,10 @@ def before_create() end
# Is called _after_ <tt>Base.save</tt> on new objects that haven't been saved yet (no record exists).
# Note that this callback is still wrapped in the transaction around +save+. For example, if you
# invoke an external indexer at this point it won't see the changes in the database.
+ #
+ # class Contact < ActiveRecord::Base
+ # after_create { |record| logger.info( "Contact #{record.id} was created." ) }
+ # end
def after_create() end
def create_with_callbacks #:nodoc:
return false if callback(:before_create) == false
@@ -272,11 +276,19 @@ def create_with_callbacks #:nodoc:
private :create_with_callbacks
# Is called _before_ <tt>Base.save</tt> on existing objects that have a record.
+ #
+ # class Contact < ActiveRecord::Base
+ # before_update { |record| logger.info( "Contact #{record.id} is about to be updated." ) }
+ # end
def before_update() end
# Is called _after_ <tt>Base.save</tt> on existing objects that have a record.
# Note that this callback is still wrapped in the transaction around +save+. For example, if you
# invoke an external indexer at this point it won't see the changes in the database.
+ #
+ # class Contact < ActiveRecord::Base
+ # after_update { |record| logger.info( "Contact #{record.id} was updated." ) }
+ # end
def after_update() end
def update_with_callbacks(*args) #:nodoc:
@@ -326,6 +338,10 @@ def valid_with_callbacks? #:nodoc:
#
# Note: If you need to _destroy_ or _nullify_ associated records first,
# use the <tt>:dependent</tt> option on your associations.
+ #
+ # class Contact < ActiveRecord::Base
+ # after_destroy { |record| logger.info( "Contact #{record.id} is about to be destroyed." ) }
+ # end
def before_destroy() end
# Is called _after_ <tt>Base.destroy</tt> (and all the attributes have been frozen).
View
2  activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
@@ -362,7 +362,7 @@ def initialize(app)
def call(env)
@app.call(env)
ensure
- # Don't return connection (and peform implicit rollback) if
+ # Don't return connection (and perform implicit rollback) if
# this request is a part of integration test
unless env.key?("rack.test")
ActiveRecord::Base.clear_active_connections!
View
8 activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -41,11 +41,19 @@ def columns(table_name, name = nil) end
# # create_table() passes a TableDefinition object to the block.
# # This form will not only create the table, but also columns for the
# # table.
+ #
# create_table(:suppliers) do |t|
# t.column :name, :string, :limit => 60
# # Other fields here
# end
#
+ # === Block form, with shorthand
+ # # You can also use the column types as method calls, rather than calling the column method.
+ # create_table(:suppliers) do |t|
+ # t.string :name, :limit => 60
+ # # Other fields here
+ # end
+ #
# === Regular form
# # Creates a table called 'suppliers' with no columns.
# create_table(:suppliers)
View
2  activerecord/lib/active_record/fixtures.rb
@@ -409,7 +409,7 @@ class FixtureClassNotFound < StandardError #:nodoc:
# subdomain: $LABEL
#
# Also, sometimes (like when porting older join table fixtures) you'll need
-# to be able to get ahold of the identifier for a given label. ERB
+# to be able to get a hold of the identifier for a given label. ERB
# to the rescue:
#
# george_reginald:
View
6 activerecord/lib/active_record/migration.rb
@@ -109,8 +109,8 @@ def initialize(name)
# script/generate migration MyNewMigration
#
# where MyNewMigration is the name of your migration. The generator will
- # create an empty migration file <tt>nnn_my_new_migration.rb</tt> in the <tt>db/migrate/</tt>
- # directory where <tt>nnn</tt> is the next largest migration number.
+ # create an empty migration file <tt>timestamp_my_new_migration.rb</tt> in the <tt>db/migrate/</tt>
+ # directory where <tt>timestamp</tt> is the UTC formatted date and time that the migration was generated.
#
# You may then edit the <tt>self.up</tt> and <tt>self.down</tt> methods of
# MyNewMigration.
@@ -118,7 +118,7 @@ def initialize(name)
# There is a special syntactic shortcut to generate migrations that add fields to a table.
# script/generate migration add_fieldname_to_tablename fieldname:string
#
- # This will generate the file <tt>nnn_add_fieldname_to_tablename</tt>, which will look like this:
+ # This will generate the file <tt>timestamp_add_fieldname_to_tablename</tt>, which will look like this:
# class AddFieldnameToTablename < ActiveRecord::Migration
# def self.up
# add_column :tablenames, :fieldname, :string
View
2  activerecord/lib/active_record/nested_attributes.rb
@@ -284,7 +284,7 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
# })
#
# Will update the name of the Person with ID 1, build a new associated
- # person with the name `John', and mark the associatied Person with ID 2
+ # person with the name `John', and mark the associated Person with ID 2
# for destruction.
#
# Also accepts an Array of attribute hashes:
View
2  activerecord/lib/active_record/validations.rb
@@ -63,7 +63,7 @@ def full_messages(options = {})
# default message (e.g. <tt>activerecord.errors.messages.MESSAGE</tt>). The translated model name,
# translated attribute name and the value are available for interpolation.
#
- # When using inheritence in your models, it will check all the inherited models too, but only if the model itself
+ # When using inheritance in your models, it will check all the inherited models too, but only if the model itself
# hasn't been found. Say you have <tt>class Admin < User; end</tt> and you wanted the translation for the <tt>:blank</tt>
# error +message+ for the <tt>title</tt> +attribute+, it looks for these translations:
#
View
4 activesupport/lib/active_support/buffered_logger.rb
@@ -68,6 +68,10 @@ def add(severity, message = nil, progname = nil, &block)
message
end
+ # Dynamically add methods such as:
+ # def info
+ # def warn
+ # def debug
for severity in Severity.constants
class_eval <<-EOT, __FILE__, __LINE__ + 1
def #{severity.downcase}(message = nil, progname = nil, &block) # def debug(message = nil, progname = nil, &block)
View
6 activesupport/lib/active_support/cache/mem_cache_store.rb
@@ -12,7 +12,7 @@ module Cache
# and MemCacheStore will load balance between all available servers. If a
# server goes down, then MemCacheStore will ignore it until it goes back
# online.
- # - Time-based expiry support. See #write and the +:expires_in+ option.
+ # - Time-based expiry support. See #write and the <tt>:expires_in</tt> option.
# - Per-request in memory cache for all communication with the MemCache server(s).
class MemCacheStore < Store
module Response # :nodoc:
@@ -64,9 +64,9 @@ def read(key, options = nil) # :nodoc:
# Writes a value to the cache.
#
# Possible options:
- # - +:unless_exist+ - set to true if you don't want to update the cache
+ # - <tt>:unless_exist</tt> - set to true if you don't want to update the cache
# if the key is already set.
- # - +:expires_in+ - the number of seconds that this value may stay in
+ # - <tt>:expires_in</tt> - the number of seconds that this value may stay in
# the cache. See ActiveSupport::Cache::Store#write for an example.
def write(key, value, options = nil)
super
View
2  activesupport/lib/active_support/callbacks.rb
@@ -237,7 +237,7 @@ def self.#{callback}_callback_chain # def self.be
# * the result from the callback
# * the object which has the callback
#
- # If the result from the block evaluates to false, the callback chain is stopped.
+ # If the result from the block evaluates to +true+, the callback chain is stopped.
#
# Example:
# class Storage
View
2  activesupport/lib/active_support/core_ext/array/conversions.rb
@@ -12,7 +12,7 @@ def to_sentence(options = {})
default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale])
default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
- # Try to emulate to_senteces previous to 2.3
+ # Try to emulate to_sentences previous to 2.3
if options.has_key?(:connector) || options.has_key?(:skip_last_comma)
::ActiveSupport::Deprecation.warn(":connector has been deprecated. Use :words_connector instead", caller) if options.has_key? :connector
::ActiveSupport::Deprecation.warn(":skip_last_comma has been deprecated. Use :last_word_connector instead", caller) if options.has_key? :skip_last_comma
View
2  activesupport/lib/active_support/core_ext/enumerable.rb
@@ -42,7 +42,7 @@ def group_by
#
# The latter is a shortcut for:
#
- # payments.inject { |sum, p| sum + p.price }
+ # payments.inject(0) { |sum, p| sum + p.price }
#
# It can also calculate the sum without the use of a block.
#
View
2  activesupport/lib/active_support/core_ext/object/duplicable.rb
@@ -1,6 +1,6 @@
class Object
# Can you safely .dup this object?
- # False for nil, false, true, symbols, and numbers; true otherwise.
+ # False for nil, false, true, symbols, numbers, and class objects; true otherwise.
def duplicable?
true
end
View
2  activesupport/lib/active_support/core_ext/time/marshal_with_utc_flag.rb
@@ -1,5 +1,5 @@
# Pre-1.9 versions of Ruby have a bug with marshaling Time instances, where utc instances are
-# unmarshaled in the local zone, instead of utc. We're layering behavior on the _dump and _load
+# unmarshalled in the local zone, instead of utc. We're layering behavior on the _dump and _load
# methods so that utc instances can be flagged on dump, and coerced back to utc on load.
if RUBY_VERSION < '1.9'
class Time
View
6 activesupport/lib/active_support/inflector.rb
@@ -155,7 +155,7 @@ def pluralize(word)
# Examples:
# "posts".singularize # => "post"
# "octopi".singularize # => "octopus"
- # "sheep".singluarize # => "sheep"
+ # "sheep".singularize # => "sheep"
# "word".singularize # => "word"
# "CamelOctopi".singularize # => "CamelOctopus"
def singularize(word)
@@ -261,9 +261,9 @@ def demodulize(class_name_in_module)
# <%= link_to(@person.name, person_path(@person)) %>
# # => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>
def parameterize(string, sep = '-')
- # replace accented chars with ther ascii equivalents
+ # replace accented chars with their ascii equivalents
parameterized_string = transliterate(string)
- # Turn unwanted chars into the seperator
+ # Turn unwanted chars into the separator
parameterized_string.gsub!(/[^a-z0-9\-_\+]+/i, sep)
unless sep.blank?
re_sep = Regexp.escape(sep)
View
2  activesupport/lib/active_support/xml_mini/jdom.rb
@@ -78,7 +78,7 @@ def collapse(element)
# Merge all the texts of an element into the hash
#
# hash::
- # Hash to add the converted emement to.
+ # Hash to add the converted element to.
# element::
# XML element whose texts are to me merged into the hash
def merge_texts!(hash, element)
View
2  activesupport/lib/active_support/xml_mini/nokogiri.rb
@@ -59,7 +59,7 @@ def to_hash(hash = {})
memo[name] = child_hash
end
- # Recusively walk children
+ # Recursively walk children
child.children.each { |c|
callback.call(child_hash, child, c, callback)
}
View
2  activesupport/lib/active_support/xml_mini/rexml.rb
@@ -60,7 +60,7 @@ def collapse(element)
# Merge all the texts of an element into the hash
#
# hash::
- # Hash to add the converted emement to.
+ # Hash to add the converted element to.
# element::
# XML element whose texts are to me merged into the hash
def merge_texts!(hash, element)
View
91 railties/README
@@ -28,7 +28,7 @@ link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the <tt>rails</tt> command
- and your application name. Ex: rails myapp
+ and your application name. Ex: <tt>rails myapp</tt>
2. Change directory into myapp and start the web server: <tt>script/server</tt> (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You're riding the Rails!"
4. Follow the guidelines to start developing your application
@@ -36,61 +36,60 @@ link:files/vendor/rails/actionpack/README.html.
== Web Servers
-By default, Rails will try to use Mongrel if it's are installed when started with script/server, otherwise Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails
-with a variety of other web servers.
+By default, Rails will try to use Mongrel if it's installed when started with script/server, otherwise
+Rails will use WEBrick, the webserver that ships with Ruby. But you can also use Rails with a variety of
+other web servers.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: <tt>gem install mongrel</tt>.
More info at: http://mongrel.rubyforge.org
-Say other Ruby web servers like Thin and Ebb or regular web servers like Apache or LiteSpeed or
-Lighttpd or IIS. The Ruby web servers are run through Rack and the latter can either be setup to use
-FCGI or proxy to a pack of Mongrels/Thin/Ebb servers.
+Other ruby web servers exist which can run your rails application, however script/server does
+not search for them or start them. These include Thin, Ebb, and Apache with mod_rails.
+
+For production use, often a web/proxy server such as Apache, LiteSpeed, Lighttpd or IIS is
+deployed as the front-end server, with the chosen ruby web server running in the back-end
+and receiving the proxied requests via one of several protocols (HTTP, CGI, FCGI).
+
== Apache .htaccess example for FCGI/CGI
-# General Apache options
-AddHandler fastcgi-script .fcgi
-AddHandler cgi-script .cgi
-Options +FollowSymLinks +ExecCGI
-
-# If you don't want Rails to look in certain directories,
-# use the following rewrite rules so that Apache won't rewrite certain requests
-#
-# Example:
-# RewriteCond %{REQUEST_URI} ^/notrails.*
-# RewriteRule .* - [L]
-
-# Redirect all requests not available on the filesystem to Rails
-# By default the cgi dispatcher is used which is very slow
-#
-# For better performance replace the dispatcher with the fastcgi one
-#
-# Example:
-# RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
-RewriteEngine On
-
-# If your Rails application is accessed via an Alias directive,
-# then you MUST also set the RewriteBase in this htaccess file.
-#
-# Example:
-# Alias /myrailsapp /path/to/myrailsapp/public
-# RewriteBase /myrailsapp
-
-RewriteRule ^$ index.html [QSA]
-RewriteRule ^([^.]+)$ $1.html [QSA]
-RewriteCond %{REQUEST_FILENAME} !-f
-RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
-
-# In case Rails experiences terminal errors
-# Instead of displaying this message you can supply a file here which will be rendered instead
-#
-# Example:
-# ErrorDocument 500 /500.html
-
-ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
+General Apache options
+
+ AddHandler fastcgi-script .fcgi
+ AddHandler cgi-script .cgi
+ Options +FollowSymLinks +ExecCGI
+
+If you don't want Rails to look in certain directories, use the following
+rewrite rules so that Apache won't rewrite certain requests.
+
+ RewriteCond %{REQUEST_URI} ^/notrails.*
+ RewriteRule .* - [L]
+
+Redirect all requests not available on the filesystem to Rails. By default the
+cgi dispatcher is used which is very slow, for better performance replace the
+dispatcher with the fastcgi one.
+
+ RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
+ RewriteEngine On
+
+If your Rails application is accessed via an Alias directive, then you MUST also
+set the RewriteBase in this htaccess file.
+
+ Alias /myrailsapp /path/to/myrailsapp/public
+ RewriteBase /myrailsapp
+
+ RewriteRule ^$ index.html [QSA]
+ RewriteRule ^([^.]+)$ $1.html [QSA]
+ RewriteCond %{REQUEST_FILENAME} !-f
+ RewriteRule ^(.*)$ dispatch.cgi [QSA,L]
+
+Incase Rails experiences terminal errors instead of displaying those messages you
+can supply a file here which will be rendered instead.
+ ErrorDocument 500 /500.html
+ ErrorDocument 500 "<h2>Application error</h2>Rails application failed to start properly"
== Debugging Rails
View
2  railties/configs/seeds.rb
@@ -4,4 +4,4 @@
# Examples:
#
# cities = City.create([{ :name => 'Chicago' }, { :name => 'Copenhagen' }])
-# Major.create(:name => 'Daley', :city => cities.first)
+# Mayor.create(:name => 'Daley', :city => cities.first)
View
1  railties/guides/files/javascripts/guides.js
@@ -1,5 +1,4 @@
function guideMenu(){
-
if (document.getElementById('guides').style.display == "none") {
document.getElementById('guides').style.display = "block";
} else {
View
BIN  railties/guides/images/fxn.jpg
Deleted file not rendered
View
BIN  railties/guides/images/fxn.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
33 railties/guides/source/action_controller_overview.textile
@@ -41,7 +41,7 @@ def new
end
</ruby>
-The "Layouts & rendering guide":layouts_and_rendering.html explains this in more detail.
+The "Layouts & Rendering Guide":layouts_and_rendering.html explains this in more detail.
+ApplicationController+ inherits from +ActionController::Base+, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the API documentation or in the source itself.
@@ -191,7 +191,7 @@ Session values are stored using key/value pairs like a hash:
<ruby>
class ApplicationController < ActionController::Base
-private
+ private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
@@ -350,7 +350,8 @@ Before filters may halt the request cycle. A common before filter is one which r
class ApplicationController < ActionController::Base
before_filter :require_login
-private
+ private
+
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
@@ -374,7 +375,7 @@ The method simply stores an error message in the flash and redirects to the logi
In this example the filter is added to +ApplicationController+ and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with +skip_before_filter+:
<ruby>
-class LoginsController < Application
+class LoginsController < ApplicationController
skip_before_filter :require_login, :only => [:new, :create]
end
</ruby>
@@ -390,10 +391,11 @@ Around filters are responsible for running the action, but they can choose not t
<ruby>
# Example taken from the Rails API filter documentation:
# http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html
-class ApplicationController < Application
+class ApplicationController < ActionController::Base
around_filter :catch_exceptions
-private
+ private
+
def catch_exceptions
yield
rescue => exception
@@ -442,7 +444,7 @@ The Rails API documentation has "more information on using filters":http://api.r
h3. Verification
-Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHTTPRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
+Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the +params+, +session+ or +flash+ hashes or that a certain HTTP method was used or that the request was made using +XMLHttpRequest+ (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the "API documentation":http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html as "essentially a special kind of before_filter".
Here's an example of using verification to make sure the user supplies a username and a password in order to log in:
@@ -575,7 +577,8 @@ class AdminController < ApplicationController
before_filter :authenticate
-private
+ private
+
def authenticate
authenticate_or_request_with_http_basic do |username, password|
username == USERNAME &&
@@ -597,7 +600,8 @@ class AdminController < ApplicationController
before_filter :authenticate
-private
+ private
+
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
@@ -626,7 +630,7 @@ class ClientsController < ApplicationController
:type => "application/pdf")
end
-private
+ private
def generate_pdf(client)
Prawn::Document.new do
@@ -728,7 +732,8 @@ Here's how you can use +rescue_from+ to intercept all +ActiveRecord::RecordNotFo
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
-private
+ private
+
def record_not_found
render :text => "404 Not Found", :status => 404
end
@@ -741,7 +746,8 @@ Of course, this example is anything but elaborate and doesn't improve on the def
class ApplicationController < ActionController::Base
rescue_from User::NotAuthorized, :with => :user_not_authorized
-private
+ private
+
def user_not_authorized
flash[:error] = "You don't have access to this section."
redirect_to :back
@@ -757,7 +763,8 @@ class ClientsController < ApplicationController
@client = Client.find(params[:id])
end
-private
+ private
+
# If the user is not authorized, just throw the exception.
def check_authorization
raise User::NotAuthorized unless current_user.admin?
View
30 railties/guides/source/action_mailer_basics.textile
@@ -46,7 +46,7 @@ class UserMailer < ActionMailer::Base
from "My Awesome Site Notifications <notifications@example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
- body {:user => user, :url => "http://example.com/login"}
+ body( {:user => user, :url => "http://example.com/login"})
end
end
</ruby>
@@ -137,9 +137,9 @@ Hence, if the method name starts with +deliver_+ followed by any combination of
h4. Complete List of Action Mailer User-Settable Attributes
-|bcc| The BCC addresses of the email|
+|bcc| The BCC addresses of the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|body| The body of the email. This is either a hash (in which case it specifies the variables to pass to the template when it is rendered), or a string, in which case it specifies the actual body of the message|
-|cc| The CC addresses for the email|
+|cc| The CC addresses for the email, either as a string (for a single address) or an array of strings (for multiple addresses)|
|charset| The charset to use for the email. This defaults to the +default_charset+ specified for ActionMailer::Base.|
|content_type| The content type for the email. This defaults to "text/plain" but the filename may specify it|
|from| The from address of the email|
@@ -165,10 +165,11 @@ class UserMailer < ActionMailer::Base
from "My Awesome Site Notifications<notifications@example.com>"
subject "Welcome to My Awesome Site"
sent_on Time.now
- body {:user => user, :url => "http://example.com/login"}
+ body( {:user => user, :url => "http://example.com/login"})
content_type "text/html"
# use some_other_template.text.(html|plain).erb instead
template "some_other_template"
+ end
end
</ruby>
@@ -264,9 +265,9 @@ end
h4. Sending Multipart Emails with Attachments
-Once you use the +attachment+ method, ActionMailer will no longer automagically use the correct template based on the filename. You must declare which template you are using for each content type via the +part+ method.
+Once you use the +attachment+ method, ActionMailer will no longer automagically use the correct template based on the filename, nor will it properly order the alternative parts. You must declare which template you are using for each content type via the +part+ method. And you must declare these templates in the proper order.
-In the following example, there would be two template files, +welcome_email_html.erb+ and +welcome_email_plain.erb+ in the +app/views/user_mailer+ folder.
+In the following example, there would be two template files, +welcome_email_html.erb+ and +welcome_email_plain.erb+ in the +app/views/user_mailer+ folder. The +text/plain+ part must be listed first for full compatibility with email clients. If +text/plain+ is listed after +text/html+, some clients may display both the HTML and plain text versions of the email. The text alternatives alone must be enclosed in a +multipart/alternative+ part. Do not set the entire message's +content_type+ to +multipart/alternative+ or some email clients may ignore the display of attachments such as PDF's.
<ruby>
class UserMailer < ActionMailer::Base
@@ -274,14 +275,15 @@ class UserMailer < ActionMailer::Base
recipients user.email_address
subject "New account information"
from "system@example.com"
- content_type "multipart/alternative"
- part "text/html" do |p|
- p.body = render_message("welcome_email_html", :message => "<h1>HTML content</h1>")
- end
+ part "multipart/alternative" do |pt|
+ pt.part "text/plain" do |p|
+ p.body = render_message("welcome_email_plain", :message => "text content")
+ end
- part "text/plain" do |p|
- p.body = render_message("welcome_email_plain", :message => "text content")
+ pt.part "text/html" do |p|
+ p.body = render_message("welcome_email_html", :message => "<h1>HTML content</h1>")
+ end
end
attachment :content_type => "image/jpeg",
@@ -369,9 +371,9 @@ ActionMailer::Base.default_charset = "iso-8859-1"
h4. Action Mailer Configuration for GMail
-Instructions copied from http://http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html
+Instructions copied from "this blog entry":http://www.fromjavatoruby.com/2008/11/actionmailer-with-gmail-must-issue.html by Robert Zotter.
-First you must install the +action_mailer_tls+ plugin from http://code.openrain.com/rails/action_mailer_tls/, then all you have to do is configure action mailer.
+First you must install the "action_mailer_tls":http://github.com/openrain/action_mailer_tls plugin, then all you have to do is configure Action Mailer:
<ruby>
ActionMailer::Base.smtp_settings = {
View
6 railties/guides/source/active_record_basics.textile
@@ -69,7 +69,7 @@ h4. Schema Conventions
ActiveRecord uses naming conventions for the columns in database tables, depending on the purpose of these columns.
* *Foreign keys* - These fields should be named following the pattern table_id i.e. (item_id, order_id). These are the fields that ActiveRecord will look for when you create associations between your models.
-* *Primary keys* - By default, ActiveRecord will use a integer column named "id" as the table's primary key. When using "Rails Migrations":http://guides.rails.info/migrations.html to create your tables, this column will be automatically created.
+* *Primary keys* - By default, ActiveRecord will use an integer column named "id" as the table's primary key. When using "Rails Migrations":migrations.html to create your tables, this column will be automatically created.
There are also some optional column names that will create additional features to ActiveRecord instances:
@@ -127,9 +127,9 @@ end
h3. Validations
-ActiveRecord gives the ability to validate the state of your models before they get recorded into the database. There are several methods that you can use to hook into the life-cycle of your models and validate that an attribute value is not empty or follow a specific format and so on. You can learn more about validations in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_overview_of_activerecord_validation.
+ActiveRecord gives the ability to validate the state of your models before they get recorded into the database. There are several methods that you can use to hook into the life-cycle of your models and validate that an attribute value is not empty or follow a specific format and so on. You can learn more about validations in the "Active Record Validations and Callbacks guide":activerecord_validations_callbacks.html#validations-overview.
h3. Callbacks
-ActiveRecord callbacks allow you to attach code to certain events in the life-cycle of your models. This way you can add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":http://guides.rails.info/activerecord_validations_callbacks.html#_callbacks.
+ActiveRecord callbacks allow you to attach code to certain events in the life-cycle of your models. This way you can add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the "Active Record Validations and Callbacks guide":activerecord_validations_callbacks.html#callbacks-overview.
View
17 railties/guides/source/active_record_querying.textile
@@ -6,7 +6,6 @@ This guide covers different ways to retrieve data from the database using Active
* Specify the order, retrieved attributes, grouping, and other properties of the found records
* Use eager loading to reduce the number of database queries needed for data retrieval
* Use dynamic finders methods
-* Create named scopes to add custom finding behavior to your models
* Check for the existence of particular records
* Perform various calculations on Active Record models
@@ -23,7 +22,6 @@ TIP: All of the following models uses +id+ as the primary key, unless specified
<ruby>
class Client < ActiveRecord::Base
has_one :address
- has_one :mailing_address
has_many :orders
has_and_belongs_to_many :roles
end
@@ -36,11 +34,6 @@ end
</ruby>
<ruby>
-class MailingAddress < Address
-end
-</ruby>
-
-<ruby>
class Order < ActiveRecord::Base
belongs_to :client, :counter_cache => true
end
@@ -245,7 +238,7 @@ WARNING: Building your own conditions as pure strings can leave you vulnerable t
h4. Array Conditions
-Now what if that number could vary, say as a argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like:
+Now what if that number could vary, say as an argument from somewhere, or perhaps from the user's level status somewhere? The find then becomes something like:
<ruby>
Client.first(:conditions => ["orders_count = ?", params[:orders]])
@@ -465,7 +458,7 @@ Be careful because this also means you're initializing a model object with only
ActiveRecord::MissingAttributeError: missing attribute: <attribute>
</shell>
-Where +<attribute>+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
+Where +&lt;attribute&gt;+ is the attribute you asked for. The +id+ method will not raise the +ActiveRecord::MissingAttributeError+, so just be careful when working with associations because they need the +id+ method to function properly.
You can also call SQL functions within the select option. For example, if you would like to only grab a single record per unique value in a certain field by using the +DISTINCT+ function you can do it like this:
@@ -539,7 +532,7 @@ This will return single order objects for each day, but only for the last month.
h4. Readonly Objects
-To explicitly disallow modification/destroyal of the matching records returned by +Model.find+, you could specify the +:readonly+ option as +true+ to the find call.
+To explicitly disallow modification/destruction of the matching records returned by +Model.find+, you could specify the +:readonly+ option as +true+ to the find call.
Any attempt to alter or destroy the readonly records will not succeed, raising an +ActiveRecord::ReadOnlyRecord+ exception. To set this option, specify it like this:
@@ -807,12 +800,12 @@ For every field (also known as an attribute) you define in your table, Active Re
You can do +find_last_by_*+ methods too which will find the last record matching your argument.
-You can specify an exclamation point (!) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
+You can specify an exclamation point (<tt>!</tt>) on the end of the dynamic finders to get them to raise an +ActiveRecord::RecordNotFound+ error if they do not return any records, like +Client.find_by_name!("Ryan")+
If you want to find both by name and locked, you can chain these finders together by simply typing +and+ between the fields for example +Client.find_by_name_and_locked("Ryan", true)+.
-There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns nil. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+:
+There's another set of dynamic finders that let you find or create/initialize objects if they aren't found. These work in a similar fashion to the other finders and can be used like +find_or_create_by_name(params[:name])+. Using this will firstly perform a find and then create if the find returns +nil+. The SQL looks like this for +Client.find_or_create_by_name("Ryan")+:
<sql>
SELECT * FROM clients WHERE (clients.name = 'Ryan') LIMIT 1
View
818 railties/guides/source/active_support_overview.textile
@@ -0,0 +1,818 @@
+h2. Active Support Overview
+
+Active Support is the Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff. It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Rails itself.
+
+By referring to this guide you will learn:
+
+* The extensions to the Ruby core modules and classes provided by Rails.
+* The rest of fundamental libraries available in Rails.
+
+endprologue.
+
+h3. Extensions to All Objects
+
+h4. +blank?+ and +present?+
+
+The following values are considered to be blank in a Rails application:
+
+* +nil+ and +false+,
+
+* strings composed only of whitespace, i.e. matching +/\A\s*\z/+,
+
+* empty arrays and hashes, and
+
+* any other object that responds to +empty?+ and it is empty.
+
+WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
+
+For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot:
+
+<ruby>
+def charset
+ charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
+ charset.blank? ? nil : charset.strip.split("=")[1]
+end
+</ruby>
+
+That's a typical use case for +blank?+.
+
+Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none:
+
+<ruby>
+def instantiate_observers
+ return if @observers.blank?
+ # ...
+end
+</ruby>
+
+The method +present?+ is equivalent to +!blank?+:
+
+<ruby>
+assert @response.body.present? # same as !@response.body.blank?
+</ruby>
+
+h4. +duplicable?+
+
+A few fundamental objects in Ruby are singletons. For example, in the whole live of a program the integer 1 refers always to the same instance:
+
+<ruby>
+1.object_id # => 3
+Math.cos(0).to_i.object_id # => 3
+</ruby>
+
+Hence, there's no way these objects can be duplicated through +dup+ or +clone+:
+
+<ruby>
+true.dup # => TypeError: can't dup TrueClass
+</ruby>
+
+Some numbers which are not singletons are not duplicable either:
+
+<ruby>
+0.0.clone # => allocator undefined for Float
+(2**1024).clone # => allocator undefined for Bignum
+</ruby>
+
+Active Support provides +duplicable?+ to programmatically query an object about this property:
+
+<ruby>
+"".duplicable? # => true
+false.duplicable? # => false
+</ruby>
+
+By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects.
+
+WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded list. Classes have means to disallow duplication like removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell.
+
+h4. +returning+
+
+The method +returning+ yields its argument to a block and returns it. You tipically use it with a mutable object that gets modified in the block:
+
+<ruby>
+def html_options_for_form(url_for_options, options, *parameters_for_url)
+ returning options.stringify_keys do |html_options|
+ html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
+ html_options["action"] = url_for(url_for_options, *parameters_for_url)
+ end
+end
+</ruby>
+
+See also "+Object#tap+":#tap.
+
+h4. +tap+
+
++Object#tap+ exists in Ruby 1.8.7 and 1.9, and it is defined by Active Support for previous versions. This method yields its receiver to a block and returns it.
+
+For example, the following class method from +ActionDispatch::TestResponse+ creates, initializes, and returns a new test response using +tap+:
+
+<ruby>
+def self.from_response(response)
+ new.tap do |resp|
+ resp.status = response.status
+ resp.headers = response.headers
+ resp.body = response.body
+ end
+end
+</ruby>
+
+See also "+Object#returning+":#returning.
+
+h4. +try+
+
+Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first.
+
+For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+:
+
+<ruby>
+def log_info(sql, name, ms)
+ if @logger && @logger.debug?
+ name = '%s (%.1fms)' % [name || 'SQL', ms]
+ @logger.debug(format_log_entry(name, sql.squeeze(' ')))
+ end
+end
+</ruby>
+
+You can shorten that using +Object#try+. This method is a synonim for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as:
+
+<ruby>
+def log_info(sql, name, ms)
+ if @logger.try(:debug?)
+ name = '%s (%.1fms)' % [name || 'SQL', ms]
+ @logger.debug(format_log_entry(name, sql.squeeze(' ')))
+ end
+end
+</ruby>
+
+h4. +metaclass+
+
+The method +metaclass+ returns the singleton class on any object:
+
+<ruby>
+String.metaclass # => #<Class:String>
+String.new.metaclass # => #<Class:#<String:0x17a1d1c>>
+</ruby>
+
+h4. +class_eval(*args, &block)+
+
+You can evaluate code in the context of any object's singleton class using +class_eval+:
+
+<ruby>
+class Proc
+ def bind(object)
+ block, time = self, Time.now
+ object.class_eval do
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
+ define_method(method_name, &block)
+ method = instance_method(method_name)
+ remove_method(method_name)
+ method
+ end.bind(object)
+ end
+end
+</ruby>
+
+h4. +acts_like?(duck)+
+
+The method +acts_like+ provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as +String+ defines
+
+<ruby>
+def acts_like_string?
+end
+</ruby>
+
+which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:
+
+<ruby>
+some_klass.acts_like?(:string)
+</ruby>
+
+Rails has classes that act like +Date+ or +Time+ and follow this contract.
+
+h4. +to_param+
+
+All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as a URL fragments.
+
+By default +to_param+ just calls +to_s+:
+
+<ruby>
+7.to_param # => "7"
+</ruby>
+
+The return value of +to_param+ should *not* be escaped:
+
+<ruby>
+"Tom & Jerry".to_param # => "Tom & Jerry"
+</ruby>
+
+Several classes in Rails overwrite this method.
+
+For example +nil+, +true+, and +false+ return themselves. +Array#to_param+ calls +to_param+ on the elements and joins the result with "/":
+
+<ruby>
+[0, true, String].to_param # => "0/true/String"
+</ruby>
+
+Notably, the Rails routing system calls +to_param+ on models to get a value for the +:id+ placeholder. +ActiveRecord::Base#to_param+ returns the +id+ of a model, but you can redefine that method in your models. For example, given
+
+<ruby>
+class User
+ def to_param
+ "#{id}-#{name.parameterize}"
+ end
+end
+</ruby>
+
+we get:
+
+<ruby>
+user_path(@user) # => "/users/357-john-smith"
+</ruby>
+
+WARNING. Controllers need to be aware of any redifinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+.
+
+h4. +to_query+
+
+Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given
+
+<ruby>
+class User
+ def to_param
+ "#{id}-#{name.parameterize}"
+ end
+end
+</ruby>
+
+we get:
+
+<ruby>
+current_user.to_query('user') # => user=357-john-smith
+</ruby>
+
+This method escapes whatever is needed, both for the key and the value:
+
+<ruby>
+account.to_query('company[name]')
+# => "company%5Bname%5D=Johnson+%26+Johnson"
+</ruby>
+
+so its output is ready to be used in a query string.
+
+Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "/":
+
+<ruby>
+[3.4, -45.6].to_query('sample')
+# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
+</ruby>
+
+Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value assigments calling +to_query(key)+ on its values. Then it joins the result with "&":
+
+<ruby>
+{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
+</ruby>
+
+The method +Hash#to_query+ accepts an optional namespace for the keys:
+
+<ruby>
+{:id => 89, :name => "John Smith"}.to_query('user')
+# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
+</ruby>
+
+h4. +with_options+
+
+The method +with_options+ provides a way to factor out common options in a series of method calls.
+
+Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
+
+<ruby>
+class Account < ActiveRecord::Base
+ has_many :customers, :dependent => :destroy
+ has_many :products, :dependent => :destroy
+ has_many :invoices, :dependent => :destroy
+ has_many :expenses, :dependent => :destroy
+end
+</ruby>
+
+this way:
+
+<ruby>
+class Account < ActiveRecord::Base
+ with_options :dependent => :destroy do |assoc|
+ assoc.has_many :customers
+ assoc.has_many :products
+ assoc.has_many :invoices
+ assoc.has_many :expenses
+ end
+end
+</ruby>
+
+That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
+
+<ruby>
+I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
+ subject i18n.t :subject
+ body i18n.t :body, :user_name => user.name
+end
+</ruby>
+
+TIP: Since +with_options+ forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
+
+h4. Instance Variables
+
+Active Support provides several methods to ease access to instance variables.
+
+h5. +instance_variable_defined?+
+
+The method +instance_variable_defined?+ exists in Ruby 1.8.6 and later, and it is defined for previous versions anyway:
+
+<ruby>
+class C
+ def initialize
+ @a = 1
+ end
+
+ def m
+ @b = 2
+ end
+end
+
+c = C.new
+
+c.instance_variable_defined?("@a") # => true
+c.instance_variable_defined?(:@a) # => true
+c.instance_variable_defined?("a") # => NameError: `a' is not allowed as an instance variable name
+
+c.instance_variable_defined?("@b") # => false
+c.m
+c.instance_variable_defined?("@b") # => true
+</ruby>
+
+h5. +instance_variable_names+
+
+Ruby 1.8 and 1.9 have a method called +instance_variables+ that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines +instance_variable_names+ as a portable way to obtain them as strings:
+
+<ruby>
+class C
+ def initialize(x, y)
+ @x, @y = x, y
+ end
+end
+
+C.new(0, 1).instance_variable_names # => ["@y", "@x"]
+</ruby>
+
+WARNING: The order in which the names are returned is unespecified, and it indeed depends on the version of the interpreter.
+
+h5. +instance_values+
+
+The method +instance_values+ returns a hash that maps instance variable names without "@" to their
+corresponding values. Keys are strings both in Ruby 1.8 and 1.9:
+
+<ruby>
+class C
+ def initialize(x, y)
+ @x, @y = x, y
+ end
+end
+
+C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
+</ruby>
+
+h5. +copy_instance_variables_from(object, exclude = [])+
+
+Copies the instance variables of +object+ into +self+.
+
+Instance variable names in the +exclude+ array are ignored. If +object+
+responds to +protected_instance_variables+ the ones returned are
+also ignored. For example, Rails controllers implement that method.
+
+In both arrays strings and symbols are understood, and they have to include
+the at sign.
+
+<ruby>
+class C
+ def initialize(x, y, z)
+ @x, @y, @z = x, y, z
+ end
+
+ def protected_instance_variables
+ %w(@z)
+ end
+end
+
+a = C.new(0, 1, 2)
+b = C.new(3, 4, 5)
+
+a.copy_instance_variables_from(b, [:@y])
+# a is now: @x = 3, @y = 1, @z = 2
+</ruby>
+
+In the example +object+ and +self+ are of the same type, but they don't need to.
+
+h4. Silencing Warnings, Streams, and Exceptions
+
+The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards:
+
+<ruby>
+silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
+</ruby>
+
+You can silence any stream while a block runs with +silence_stream+:
+
+<ruby>
+silence_stream(STDOUT) do
+ # STDOUT is silent here
+end
+</ruby>
+
+Silencing exceptions is also possible with +suppress+. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is +kind_of?+ any of the arguments, +suppress+ captures it and returns silently. Otherwise the exception is reraised:
+
+<ruby>
+# If the user is locked the increment is lost, no big deal.
+suppress(ActiveRecord::StaleObjectError) do
+ current_user.increment! :visits
+end
+</ruby>
+
+h3. Extensions to +Module+
+
+...
+
+h3. Extensions to +Class+
+
+h4. Class Attribute Accessors
+
+The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it:
+
+<ruby>
+class MysqlAdapter < AbstractAdapter
+ # Generates class methods to access @@emulate_booleans.
+ cattr_accessor :emulate_booleans
+ self.emulate_booleans = true
+end
+</ruby>
+
+Instance methods are created as well for convenience. For example given
+
+<ruby>
+module ActionController
+ class Base
+ cattr_accessor :logger
+ end
+end
+</ruby>
+
+we can access +logger+ in actions. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):
+
+<ruby>
+module ActiveRecord
+ class Base
+ # No pluralize_table_names= instance writer is generated.
+ cattr_accessor :pluralize_table_names, :instance_writer => false
+ end
+end
+</ruby>
+
+h4. Class Inheritable Attributes
+
+Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accesors for class-level data which is inherited but not shared with children:
+
+<ruby>
+module ActionController
+ class Base
+ # FIXME: REVISE/SIMPLIFY THIS COMMENT.
+ # The value of allow_forgery_protection is inherited,
+ # but its value in a particular class does not affect
+ # the value in the rest of the controllers hierarchy.
+ class_inheritable_accessor :allow_forgery_protection
+ end
+end
+</ruby>
+
+They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with +dup+ as long as the value is duplicable.
+
+There are some variants specialised in arrays and hashes:
+
+<ruby>
+class_inheritable_array
+class_inheritable_hash
+</ruby>
+
+Those writers take any inherited array or hash into account and extend them rather than overwrite them.
+
+As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):
+
+<ruby>
+module ActiveRecord
+ class Base
+ class_inheritable_accessor :default_scoping, :instance_writer => false
+ end
+end
+</ruby>
+
+Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point.
+
+There's a related macro called +superclass_delegating_accessor+, however, that does not copy the value when the base class is subclassed. Instead, it delegates reading to the superclass as long as the attribute is not set via its own writer. For example, +ActionMailer::Base+ defines +delivery_method+ this way:
+
+<ruby>
+module ActionMailer
+ class Base
+ superclass_delegating_accessor :delivery_method
+ self.delivery_method = :smtp
+ end
+end
+</ruby>
+
+If for whatever reason an application loads the definition of a mailer class and after that sets +ActionMailer::Base.delivery_method+, the mailer class will still see the new value. In addition, the mailer class is able to change the +delivery_method+ without affecting the value in the parent using its own inherited class attribute writer.
+
+h4. Subclasses
+
+The +subclasses+ method returns the names of all subclasses of a given class as an array of strings. That comprises not only direct subclasses, but all descendants down the hierarchy:
+
+<ruby>
+class C; end
+C.subclasses # => []
+
+Integer.subclasses # => ["Bignum", "Fixnum"]
+
+module M
+ class A; end
+ class B1 < A; end
+ class B2 < A; end
+end
+
+module N
+ class C < M::B1; end
+end
+
+M::A.subclasses # => ["N::C", "M::B2", "M::B1"]
+</ruby>
+
+The order in which these class names are returned is unspecified.
+
+See also +Object#subclasses_of+ in "Extensions to All Objects FIX THIS LINK":FIXME.
+
+h4. Class Removal
+
+Roughly speaking, the +remove_class+ method removes the class objects passed as arguments:
+
+<ruby>
+Class.remove_class(Hash, Dir) # => [Hash, Dir]
+Hash # => NameError: uninitialized constant Hash
+Dir # => NameError: uninitialized constant Dir
+</ruby>
+
+More specifically, +remove_class+ attempts to remove constants with the same name as the passed class objects from their parent modules. So technically this method does not guarantee the class objects themselves are not still valid and alive somewhere after the method call:
+
+<ruby>
+module M
+ class A; end
+ class B < A; end
+end
+
+A2 = M::A
+
+M::A.object_id # => 13053950