Skip to content
Browse files

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

Conflicts:
	actionpack/lib/action_dispatch/routing/redirection.rb
  • Loading branch information...
2 parents 8eefdb6 + 1fd008c commit 7b70eeed43045dc29e73e23fbfdc323e9d397026 @vijaydev vijaydev committed
Showing with 959 additions and 957 deletions.
  1. +9 −9 actionmailer/lib/action_mailer/base.rb
  2. +3 −3 actionpack/lib/abstract_controller/layouts.rb
  3. +22 −17 actionpack/lib/action_dispatch/routing/mapper.rb
  4. +4 −0 activemodel/lib/active_model/secure_password.rb
  5. +18 −18 activerecord/lib/active_record/aggregations.rb
  6. +53 −53 activerecord/lib/active_record/associations.rb
  7. +11 −11 activerecord/lib/active_record/autosave_association.rb
  8. +19 −19 activerecord/lib/active_record/base.rb
  9. +1 −1 activerecord/lib/active_record/callbacks.rb
  10. +8 −8 activerecord/lib/active_record/connection_handling.rb
  11. +1 −1 activerecord/lib/active_record/core.rb
  12. +2 −2 activerecord/lib/active_record/counter_cache.rb
  13. +1 −1 activerecord/lib/active_record/errors.rb
  14. +2 −2 activerecord/lib/active_record/fixtures.rb
  15. +3 −3 activerecord/lib/active_record/locking/pessimistic.rb
  16. +1 −1 activerecord/lib/active_record/model_schema.rb
  17. +35 −35 activerecord/lib/active_record/nested_attributes.rb
  18. +1 −1 activerecord/lib/active_record/relation.rb
  19. +1 −1 activerecord/lib/active_record/relation/calculations.rb
  20. +1 −1 activerecord/lib/active_record/relation/finder_methods.rb
  21. +2 −2 activerecord/lib/active_record/relation/predicate_builder.rb
  22. +9 −9 activerecord/lib/active_record/relation/query_methods.rb
  23. +2 −2 activerecord/lib/active_record/relation/spawn_methods.rb
  24. +12 −12 activerecord/lib/active_record/sanitization.rb
  25. +7 −7 activerecord/lib/active_record/serializers/xml_serializer.rb
  26. +14 −14 activerecord/lib/active_record/transactions.rb
  27. +5 −5 activesupport/lib/active_support/concern.rb
  28. +9 −9 activesupport/lib/active_support/notifications.rb
  29. +19 −17 guides/source/action_controller_overview.md
  30. +1 −1 guides/source/action_mailer_basics.md
  31. +151 −190 guides/source/action_view_overview.md
  32. +4 −4 guides/source/active_model_basics.md
  33. +3 −3 guides/source/active_record_basics.md
  34. +30 −28 guides/source/active_record_querying.md
  35. +19 −17 guides/source/active_support_core_extensions.md
  36. +13 −10 guides/source/api_documentation_guidelines.md
  37. +16 −4 guides/source/asset_pipeline.md
  38. +94 −94 guides/source/association_basics.md
  39. +22 −22 guides/source/caching_with_rails.md
  40. +1 −1 guides/source/command_line.md
  41. +7 −7 guides/source/configuring.md
  42. +4 −4 guides/source/contributing_to_ruby_on_rails.md
  43. +1 −1 guides/source/debugging_rails_applications.md
  44. +3 −1 guides/source/development_dependencies_install.md
  45. +12 −12 guides/source/engines.md
  46. +34 −34 guides/source/form_helpers.md
  47. +34 −34 guides/source/generators.md
  48. +5 −5 guides/source/getting_started.md
  49. +8 −8 guides/source/i18n.md
  50. +1 −2 guides/source/index.html.erb
  51. +79 −82 guides/source/layouts_and_rendering.md
  52. +22 −22 guides/source/migrations.md
  53. +1 −1 guides/source/performance_testing.md
  54. +2 −2 guides/source/plugins.md
  55. +23 −11 guides/source/rails_application_templates.md
  56. +5 −5 guides/source/rails_on_rack.md
  57. +64 −64 guides/source/routing.md
  58. +2 −2 guides/source/security.md
  59. +17 −17 guides/source/testing.md
  60. +4 −4 guides/source/upgrading_ruby_on_rails.md
  61. +2 −1 railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt
View
18 actionmailer/lib/action_mailer/base.rb
@@ -70,7 +70,7 @@ module ActionMailer
# The block syntax is also useful in providing information specific to a part:
#
# mail(to: user.email) do |format|
- # format.text(:content_transfer_encoding => "base64")
+ # format.text(content_transfer_encoding: "base64")
# format.html
# end
#
@@ -129,12 +129,12 @@ module ActionMailer
# It is also possible to set a default host that will be used in all mailers by setting the <tt>:host</tt>
# option as a configuration option in <tt>config/application.rb</tt>:
#
- # config.action_mailer.default_url_options = { :host => "example.com" }
+ # config.action_mailer.default_url_options = { host: "example.com" }
#
# When you decide to set a default <tt>:host</tt> for your mailers, then you need to make sure to use the
- # <tt>:only_path => false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
+ # <tt>only_path: false</tt> option when using <tt>url_for</tt>. Since the <tt>url_for</tt> view helper
# will generate relative URLs by default when a <tt>:host</tt> option isn't explicitly provided, passing
- # <tt>:only_path => false</tt> will ensure that absolute URLs are generated.
+ # <tt>only_path: false</tt> will ensure that absolute URLs are generated.
#
# = Sending mail
#
@@ -246,10 +246,10 @@ module ActionMailer
# You can pass in any header value that a <tt>Mail::Message</tt> accepts. Out of the box,
# <tt>ActionMailer::Base</tt> sets the following:
#
- # * <tt>:mime_version => "1.0"</tt>
- # * <tt>:charset => "UTF-8",</tt>
- # * <tt>:content_type => "text/plain",</tt>
- # * <tt>:parts_order => [ "text/plain", "text/enriched", "text/html" ]</tt>
+ # * <tt>mime_version: "1.0"</tt>
+ # * <tt>charset: "UTF-8",</tt>
+ # * <tt>content_type: "text/plain",</tt>
+ # * <tt>parts_order: [ "text/plain", "text/enriched", "text/html" ]</tt>
#
# <tt>parts_order</tt> and <tt>charset</tt> are not actually valid <tt>Mail::Message</tt> header fields,
# but Action Mailer translates them appropriately and sets the correct values.
@@ -665,7 +665,7 @@ def attachments
#
# The block syntax also allows you to customize the part headers if desired:
#
- # mail(:to => 'mikel@test.lindsaar.net') do |format|
+ # mail(to: 'mikel@test.lindsaar.net') do |format|
# format.text(content_transfer_encoding: "base64")
# format.html
# end
View
6 actionpack/lib/abstract_controller/layouts.rb
@@ -170,7 +170,7 @@ module AbstractController
# <tt>:only</tt> and <tt>:except</tt> options can be passed to the layout call. For example:
#
# class WeblogController < ActionController::Base
- # layout "weblog_standard", :except => :rss
+ # layout "weblog_standard", except: :rss
#
# # ...
#
@@ -180,7 +180,7 @@ module AbstractController
# be rendered directly, without wrapping a layout around the rendered view.
#
# Both the <tt>:only</tt> and <tt>:except</tt> condition can accept an arbitrary number of method references, so
- # #<tt>:except => [ :rss, :text_only ]</tt> is valid, as is <tt>:except => :rss</tt>.
+ # #<tt>except: [ :rss, :text_only ]</tt> is valid, as is <tt>except: :rss</tt>.
#
# == Using a different layout in the action render call
#
@@ -192,7 +192,7 @@ module AbstractController
# layout "weblog_standard"
#
# def help
- # render :action => "help", :layout => "help"
+ # render action: "help", layout: "help"
# end
# end
#
View
39 actionpack/lib/action_dispatch/routing/mapper.rb
@@ -299,7 +299,7 @@ def root(options = {})
# and +:action+ to the controller's action. A pattern can also map
# wildcard segments (globs) to params:
#
- # match 'songs/*category/:title' => 'songs#show'
+ # match 'songs/*category/:title', to: 'songs#show'
#
# # 'songs/rock/classic/stairway-to-heaven' sets
# # params[:category] = 'rock/classic'
@@ -315,10 +315,14 @@ def root(options = {})
# A pattern can also point to a +Rack+ endpoint i.e. anything that
# responds to +call+:
#
- # match 'photos/:id' => lambda {|hash| [200, {}, "Coming soon"] }
- # match 'photos/:id' => PhotoRackApp
+ # match 'photos/:id', to: lambda {|hash| [200, {}, "Coming soon"] }
+ # match 'photos/:id', to: PhotoRackApp
# # Yes, controller actions are just rack endpoints
- # match 'photos/:id' => PhotosController.action(:show)
+ # match 'photos/:id', to: PhotosController.action(:show)
+ #
+ # Because request various HTTP verbs with a single action has security
+ # implications, is recommendable use HttpHelpers[rdoc-ref:HttpHelpers]
+ # instead +match+
#
# === Options
#
@@ -336,7 +340,7 @@ def root(options = {})
# [:module]
# The namespace for :controller.
#
- # match 'path' => 'c#a', module: 'sekret', controller: 'posts'
+ # match 'path', to: 'c#a', module: 'sekret', controller: 'posts'
# #=> Sekret::PostsController
#
# See <tt>Scoping#namespace</tt> for its scope equivalent.
@@ -347,8 +351,9 @@ def root(options = {})
# [:via]
# Allowed HTTP verb(s) for route.
#
- # match 'path' => 'c#a', via: :get
- # match 'path' => 'c#a', via: [:get, :post]
+ # match 'path', to: 'c#a', via: :get
+ # match 'path', to: 'c#a', via: [:get, :post]
+ # match 'path', to: 'c#a', via: :all
#
# [:to]
# Points to a +Rack+ endpoint. Can be an object that responds to
@@ -364,14 +369,14 @@ def root(options = {})
# <tt>resource(s)</tt> block. For example:
#
# resource :bar do
- # match 'foo' => 'c#a', on: :member, via: [:get, :post]
+ # match 'foo', to: 'c#a', on: :member, via: [:get, :post]
# end
#
# Is equivalent to:
#
# resource :bar do
# member do
- # match 'foo' => 'c#a', via: [:get, :post]
+ # match 'foo', to: 'c#a', via: [:get, :post]
# end
# end
#
@@ -384,7 +389,7 @@ def root(options = {})
# class Blacklist
# def matches?(request) request.remote_ip == '1.2.3.4' end
# end
- # match 'path' => 'c#a', constraints: Blacklist.new
+ # match 'path', to: 'c#a', constraints: Blacklist.new
#
# See <tt>Scoping#constraints</tt> for more examples with its scope
# equivalent.
@@ -393,7 +398,7 @@ def root(options = {})
# Sets defaults for parameters
#
# # Sets params[:format] to 'jpg' by default
- # match 'path' => 'c#a', defaults: { format: 'jpg' }
+ # match 'path', to: 'c#a', defaults: { format: 'jpg' }
#
# See <tt>Scoping#defaults</tt> for its scope equivalent.
#
@@ -402,7 +407,7 @@ def root(options = {})
# false, the pattern matches any request prefixed with the given path.
#
# # Matches any request starting with 'path'
- # match 'path' => 'c#a', anchor: false
+ # match 'path', to: 'c#a', anchor: false
#
# [:format]
# Allows you to specify the default value for optional +format+
@@ -499,7 +504,7 @@ def define_generate_prefix(app, name)
module HttpHelpers
# Define a route that only recognizes HTTP GET.
- # For supported arguments, see <tt>Base#match</tt>.
+ # For supported arguments, see match[rdoc-ref:Base#match]
#
# get 'bacon', to: 'food#bacon'
def get(*args, &block)
@@ -507,7 +512,7 @@ def get(*args, &block)
end
# Define a route that only recognizes HTTP POST.
- # For supported arguments, see <tt>Base#match</tt>.
+ # For supported arguments, see match[rdoc-ref:Base#match]
#
# post 'bacon', to: 'food#bacon'
def post(*args, &block)
@@ -515,7 +520,7 @@ def post(*args, &block)
end
# Define a route that only recognizes HTTP PATCH.
- # For supported arguments, see <tt>Base#match</tt>.
+ # For supported arguments, see match[rdoc-ref:Base#match]
#
# patch 'bacon', to: 'food#bacon'
def patch(*args, &block)
@@ -523,7 +528,7 @@ def patch(*args, &block)
end
# Define a route that only recognizes HTTP PUT.
- # For supported arguments, see <tt>Base#match</tt>.
+ # For supported arguments, see match[rdoc-ref:Base#match]
#
# put 'bacon', to: 'food#bacon'
def put(*args, &block)
@@ -531,7 +536,7 @@ def put(*args, &block)
end
# Define a route that only recognizes HTTP DELETE.
- # For supported arguments, see <tt>Base#match</tt>.
+ # For supported arguments, see match[rdoc-ref:Base#match]
#
# delete 'broccoli', to: 'food#broccoli'
def delete(*args, &block)
View
4 activemodel/lib/active_model/secure_password.rb
@@ -13,6 +13,10 @@ module ClassMethods
# you wish to turn off validations, pass <tt>validations: false</tt> as an
# argument. You can add more validations by hand if need be.
#
+ # If you don't need the confirmation validation, just don't set any
+ # value to the password_confirmation attribute and the the validation
+ # will not be triggered.
+ #
# You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use #has_secure_password:
#
# gem 'bcrypt-ruby', '~> 3.0.0'
View
36 activerecord/lib/active_record/aggregations.rb
@@ -16,8 +16,8 @@ def clear_aggregation_cache #:nodoc:
# the database).
#
# class Customer < ActiveRecord::Base
- # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount)
- # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount)
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
# end
#
# The customer class now has the following methods to manipulate the value objects:
@@ -138,15 +138,15 @@ def clear_aggregation_cache #:nodoc:
#
# class NetworkResource < ActiveRecord::Base
# composed_of :cidr,
- # :class_name => 'NetAddr::CIDR',
- # :mapping => [ %w(network_address network), %w(cidr_range bits) ],
- # :allow_nil => true,
- # :constructor => Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
- # :converter => Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
+ # class_name: 'NetAddr::CIDR',
+ # mapping: [ %w(network_address network), %w(cidr_range bits) ],
+ # allow_nil: true,
+ # constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") },
+ # converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) }
# end
#
# # This calls the :constructor
- # network_resource = NetworkResource.new(:network_address => '192.168.0.1', :cidr_range => 24)
+ # network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24)
#
# # These assignments will both use the :converter
# network_resource.cidr = [ '192.168.2.1', 8 ]
@@ -165,7 +165,7 @@ def clear_aggregation_cache #:nodoc:
# by specifying an instance of the value object in the conditions hash. The following example
# finds all customers with +balance_amount+ equal to 20 and +balance_currency+ equal to "USD":
#
- # Customer.where(:balance => Money.new(20, "USD")).all
+ # Customer.where(balance: Money.new(20, "USD")).all
#
module ClassMethods
# Adds reader and writer methods for manipulating a value object:
@@ -197,17 +197,17 @@ module ClassMethods
# can return nil to skip the assignment.
#
# Option examples:
- # composed_of :temperature, :mapping => %w(reading celsius)
- # composed_of :balance, :class_name => "Money", :mapping => %w(balance amount),
- # :converter => Proc.new { |balance| balance.to_money }
- # composed_of :address, :mapping => [ %w(address_street street), %w(address_city city) ]
+ # composed_of :temperature, mapping: %w(reading celsius)
+ # composed_of :balance, class_name: "Money", mapping: %w(balance amount),
+ # converter: Proc.new { |balance| balance.to_money }
+ # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ]
# composed_of :gps_location
- # composed_of :gps_location, :allow_nil => true
+ # composed_of :gps_location, allow_nil: true
# composed_of :ip_address,
- # :class_name => 'IPAddr',
- # :mapping => %w(ip to_i),
- # :constructor => Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
- # :converter => Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
+ # class_name: 'IPAddr',
+ # mapping: %w(ip to_i),
+ # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
+ # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
#
def composed_of(part_id, options = {})
options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter)
View
106 activerecord/lib/active_record/associations.rb
@@ -308,11 +308,11 @@ def association_instance_set(name, association)
# end
# class Programmer < ActiveRecord::Base
# has_many :assignments
- # has_many :projects, :through => :assignments
+ # has_many :projects, through: :assignments
# end
# class Project < ActiveRecord::Base
# has_many :assignments
- # has_many :programmers, :through => :assignments
+ # has_many :programmers, through: :assignments
# end
#
# For the second way, use +has_and_belongs_to_many+ in both models. This requires a join table
@@ -429,7 +429,7 @@ def association_instance_set(name, association)
# object from an association collection.
#
# class Project
- # has_and_belongs_to_many :developers, :after_add => :evaluate_velocity
+ # has_and_belongs_to_many :developers, after_add: :evaluate_velocity
#
# def evaluate_velocity(developer)
# ...
@@ -440,7 +440,7 @@ def association_instance_set(name, association)
#
# class Project
# has_and_belongs_to_many :developers,
- # :after_add => [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
+ # after_add: [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
# end
#
# Possible callbacks are: +before_add+, +after_add+, +before_remove+ and +after_remove+.
@@ -510,7 +510,7 @@ def association_instance_set(name, association)
#
# class Author < ActiveRecord::Base
# has_many :authorships
- # has_many :books, :through => :authorships
+ # has_many :books, through: :authorships
# end
#
# class Authorship < ActiveRecord::Base
@@ -526,7 +526,7 @@ def association_instance_set(name, association)
#
# class Firm < ActiveRecord::Base
# has_many :clients
- # has_many :invoices, :through => :clients
+ # has_many :invoices, through: :clients
# end
#
# class Client < ActiveRecord::Base
@@ -546,7 +546,7 @@ def association_instance_set(name, association)
#
# class Group < ActiveRecord::Base
# has_many :users
- # has_many :avatars, :through => :users
+ # has_many :avatars, through: :users
# end
#
# class User < ActiveRecord::Base
@@ -574,7 +574,7 @@ def association_instance_set(name, association)
# works correctly (where <tt>tags</tt> is a +has_many+ <tt>:through</tt> association):
#
# @post = Post.first
- # @tag = @post.tags.build :name => "ruby"
+ # @tag = @post.tags.build name: "ruby"
# @tag.save
#
# The last line ought to save the through record (a <tt>Taggable</tt>). This will only work if the
@@ -582,7 +582,7 @@ def association_instance_set(name, association)
#
# class Taggable < ActiveRecord::Base
# belongs_to :post
- # belongs_to :tag, :inverse_of => :taggings
+ # belongs_to :tag, inverse_of: :taggings
# end
#
# == Nested Associations
@@ -592,8 +592,8 @@ def association_instance_set(name, association)
#
# class Author < ActiveRecord::Base
# has_many :posts
- # has_many :comments, :through => :posts
- # has_many :commenters, :through => :comments
+ # has_many :comments, through: :posts
+ # has_many :commenters, through: :comments
# end
#
# class Post < ActiveRecord::Base
@@ -611,12 +611,12 @@ def association_instance_set(name, association)
#
# class Author < ActiveRecord::Base
# has_many :posts
- # has_many :commenters, :through => :posts
+ # has_many :commenters, through: :posts
# end
#
# class Post < ActiveRecord::Base
# has_many :comments
- # has_many :commenters, :through => :comments
+ # has_many :commenters, through: :comments
# end
#
# class Comment < ActiveRecord::Base
@@ -635,11 +635,11 @@ def association_instance_set(name, association)
# must adhere to.
#
# class Asset < ActiveRecord::Base
- # belongs_to :attachable, :polymorphic => true
+ # belongs_to :attachable, polymorphic: true
# end
#
# class Post < ActiveRecord::Base
- # has_many :assets, :as => :attachable # The :as option specifies the polymorphic interface to use.
+ # has_many :assets, as: :attachable # The :as option specifies the polymorphic interface to use.
# end
#
# @asset.attachable = @post
@@ -656,7 +656,7 @@ def association_instance_set(name, association)
# column in the posts table.
#
# class Asset < ActiveRecord::Base
- # belongs_to :attachable, :polymorphic => true
+ # belongs_to :attachable, polymorphic: true
#
# def attachable_type=(sType)
# super(sType.to_s.classify.constantize.base_class.to_s)
@@ -664,8 +664,8 @@ def association_instance_set(name, association)
# end
#
# class Post < ActiveRecord::Base
- # # because we store "Post" in attachable_type now :dependent => :destroy will work
- # has_many :assets, :as => :attachable, :dependent => :destroy
+ # # because we store "Post" in attachable_type now dependent: :destroy will work
+ # has_many :assets, as: :attachable, dependent: :destroy
# end
#
# class GuestPost < Post
@@ -727,7 +727,7 @@ def association_instance_set(name, association)
#
# To include a deep hierarchy of associations, use a hash:
#
- # Post.includes(:author, {:comments => {:author => :gravatar}}).each do |post|
+ # Post.includes(:author, {comments: {author: :gravatar}}).each do |post|
#
# That'll grab not only all the comments but all their authors and gravatar pictures.
# You can mix and match symbols, arrays and hashes in any combination to describe the
@@ -752,13 +752,13 @@ def association_instance_set(name, association)
# 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.
+ # <tt>order: "author.name DESC"</tt> will work but <tt>order: "name DESC"</tt> will not.
#
# If you do want eager load only some members of an association it is usually more natural
# to include an association which has conditions defined on it:
#
# class Post < ActiveRecord::Base
- # has_many :approved_comments, -> { where approved: true }, :class_name => 'Comment'
+ # has_many :approved_comments, -> { where approved: true }, class_name: 'Comment'
# end
#
# Post.includes(:approved_comments)
@@ -770,7 +770,7 @@ def association_instance_set(name, association)
# returning all the associated objects:
#
# class Picture < ActiveRecord::Base
- # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, :class_name => 'Comment'
+ # has_many :most_recent_comments, -> { order('id DESC').limit(10) }, class_name: 'Comment'
# end
#
# Picture.includes(:most_recent_comments).first.most_recent_comments # => returns all associated comments.
@@ -778,7 +778,7 @@ def association_instance_set(name, association)
# Eager loading is supported with polymorphic associations.
#
# class Address < ActiveRecord::Base
- # belongs_to :addressable, :polymorphic => true
+ # belongs_to :addressable, polymorphic: true
# end
#
# A call that tries to eager load the addressable model
@@ -812,10 +812,10 @@ def association_instance_set(name, association)
#
# TreeMixin.joins(:children)
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
- # TreeMixin.joins(:children => :parent)
+ # TreeMixin.joins(children: :parent)
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
# INNER JOIN parents_mixins ...
- # TreeMixin.joins(:children => {:parent => :children})
+ # TreeMixin.joins(children: {parent: :children})
# # => SELECT ... FROM mixins INNER JOIN mixins childrens_mixins ...
# INNER JOIN parents_mixins ...
# INNER JOIN mixins childrens_mixins_2
@@ -824,10 +824,10 @@ def association_instance_set(name, association)
#
# Post.joins(:categories)
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
- # Post.joins(:categories => :posts)
+ # Post.joins(categories: :posts)
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
- # Post.joins(:categories => {:posts => :categories})
+ # Post.joins(categories: {posts: :categories})
# # => SELECT ... FROM posts INNER JOIN categories_posts ... INNER JOIN categories ...
# INNER JOIN categories_posts posts_categories_join INNER JOIN posts posts_categories
# INNER JOIN categories_posts categories_posts_join INNER JOIN categories categories_posts_2
@@ -871,7 +871,7 @@ def association_instance_set(name, association)
#
# module Billing
# class Account < ActiveRecord::Base
- # belongs_to :firm, :class_name => "MyApplication::Business::Firm"
+ # belongs_to :firm, class_name: "MyApplication::Business::Firm"
# end
# end
# end
@@ -913,16 +913,16 @@ def association_instance_set(name, association)
# 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
+ # has_many :traps, inverse_of: :dungeon
+ # has_one :evil_wizard, inverse_of: :dungeon
# end
#
# class Trap < ActiveRecord::Base
- # belongs_to :dungeon, :inverse_of => :traps
+ # belongs_to :dungeon, inverse_of: :traps
# end
#
# class EvilWizard < ActiveRecord::Base
- # belongs_to :dungeon, :inverse_of => :evil_wizard
+ # belongs_to :dungeon, inverse_of: :evil_wizard
# end
#
# Then, from our code snippet above, +d+ and <tt>t.dungeon</tt> are actually the same
@@ -945,7 +945,7 @@ def association_instance_set(name, association)
# For example:
#
# class Author
- # has_many :posts, :dependent => :destroy
+ # has_many :posts, dependent: :destroy
# end
# Author.find(1).destroy # => Will destroy all of the author's posts, too
#
@@ -1029,12 +1029,12 @@ module ClassMethods
# parent object.
# [collection.delete(object, ...)]
# Removes one or more objects from the collection by setting their foreign keys to +NULL+.
- # Objects will be in addition destroyed if they're associated with <tt>:dependent => :destroy</tt>,
- # and deleted if they're associated with <tt>:dependent => :delete_all</tt>.
+ # Objects will be in addition destroyed if they're associated with <tt>dependent: :destroy</tt>,
+ # and deleted if they're associated with <tt>dependent: :delete_all</tt>.
#
# If the <tt>:through</tt> option is used, then the join records are deleted (rather than
- # nullified) by default, but you can specify <tt>:dependent => :destroy</tt> or
- # <tt>:dependent => :nullify</tt> to override this.
+ # nullified) by default, but you can specify <tt>dependent: :destroy</tt> or
+ # <tt>dependent: :nullify</tt> to override this.
# [collection.destroy(object, ...)]
# Removes one or more objects from the collection by running <tt>destroy</tt> on
# each record, regardless of any dependent option, ensuring callbacks are run.
@@ -1052,8 +1052,8 @@ module ClassMethods
# method loads the models and calls <tt>collection=</tt>. See above.
# [collection.clear]
# Removes every object from the collection. This destroys the associated objects if they
- # are associated with <tt>:dependent => :destroy</tt>, deletes them directly from the
- # database if <tt>:dependent => :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
+ # are associated with <tt>dependent: :destroy</tt>, deletes them directly from the
+ # database if <tt>dependent: :delete_all</tt>, otherwise sets their foreign keys to +NULL+.
# If the <tt>:through</tt> option is true no destroy callbacks are invoked on the join models.
# Join models are directly deleted.
# [collection.empty?]
@@ -1081,7 +1081,7 @@ module ClassMethods
# === Example
#
# Example: A Firm class declares <tt>has_many :clients</tt>, which will add:
- # * <tt>Firm#clients</tt> (similar to <tt>Clients.all :conditions => ["firm_id = ?", id]</tt>)
+ # * <tt>Firm#clients</tt> (similar to <tt>Clients.all conditions: ["firm_id = ?", id]</tt>)
# * <tt>Firm#clients<<</tt>
# * <tt>Firm#clients.delete</tt>
# * <tt>Firm#clients.destroy</tt>
@@ -1091,8 +1091,8 @@ module ClassMethods
# * <tt>Firm#clients.clear</tt>
# * <tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)
# * <tt>Firm#clients.size</tt> (similar to <tt>Client.count "firm_id = #{id}"</tt>)
- # * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions => "firm_id = #{id}")</tt>)
- # * <tt>Firm#clients.exists?(:name => 'ACME')</tt> (similar to <tt>Client.exists?(:name => 'ACME', :firm_id => firm.id)</tt>)
+ # * <tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, conditions: "firm_id = #{id}")</tt>)
+ # * <tt>Firm#clients.exists?(name: 'ACME')</tt> (similar to <tt>Client.exists?(name: 'ACME', firm_id: firm.id)</tt>)
# * <tt>Firm#clients.build</tt> (similar to <tt>Client.new("firm_id" => id)</tt>)
# * <tt>Firm#clients.create</tt> (similar to <tt>c = Client.new("firm_id" => id); c.save; c</tt>)
# The declaration can also include an options hash to specialize the behavior of the association.
@@ -1149,7 +1149,7 @@ module ClassMethods
# [:source]
# Specifies the source association name used by <tt>has_many :through</tt> queries.
# Only use it if the name cannot be inferred from the association.
- # <tt>has_many :subscribers, :through => :subscriptions</tt> will look for either <tt>:subscribers</tt> or
+ # <tt>has_many :subscribers, through: :subscriptions</tt> will look for either <tt>:subscribers</tt> or
# <tt>:subscriber</tt> on Subscription, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_many :through</tt> queries where the source
@@ -1213,7 +1213,7 @@ def has_many(name, scope = nil, options = {}, &extension)
# === Example
#
# An Account class declares <tt>has_one :beneficiary</tt>, which will add:
- # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.first(:conditions => "account_id = #{id}")</tt>)
+ # * <tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.first(conditions: "account_id = #{id}")</tt>)
# * <tt>Account#beneficiary=(beneficiary)</tt> (similar to <tt>beneficiary.account_id = account.id; beneficiary.save</tt>)
# * <tt>Account#build_beneficiary</tt> (similar to <tt>Beneficiary.new("account_id" => id)</tt>)
# * <tt>Account#create_beneficiary</tt> (similar to <tt>b = Beneficiary.new("account_id" => id); b.save; b</tt>)
@@ -1253,7 +1253,7 @@ def has_many(name, scope = nil, options = {}, &extension)
# [:source]
# Specifies the source association name used by <tt>has_one :through</tt> queries.
# Only use it if the name cannot be inferred from the association.
- # <tt>has_one :favorite, :through => :favorites</tt> will look for a
+ # <tt>has_one :favorite, through: :favorites</tt> will look for a
# <tt>:favorite</tt> on Favorite, unless a <tt>:source</tt> is given.
# [:source_type]
# Specifies type of the source association used by <tt>has_one :through</tt> queries where the source
@@ -1273,11 +1273,11 @@ def has_many(name, scope = nil, options = {}, &extension)
# See ActiveRecord::Associations::ClassMethods's overview on Bi-directional associations for more detail.
#
# Option examples:
- # has_one :credit_card, :dependent => :destroy # destroys the associated credit card
- # has_one :credit_card, :dependent => :nullify # updates the associated records foreign
+ # has_one :credit_card, dependent: :destroy # destroys the associated credit card
+ # has_one :credit_card, dependent: :nullify # updates the associated records foreign
# # key value to NULL rather than destroying it
- # has_one :last_comment, -> { order 'posted_on' }, :class_name => "Comment"
- # has_one :project_manager, -> { where role: 'project_manager' }, :class_name => "Person"
+ # has_one :last_comment, -> { order 'posted_on' }, class_name: "Comment"
+ # has_one :project_manager, -> { where role: 'project_manager' }, class_name: "Person"
# has_one :attachment, as: :attachable
# has_one :boss, readonly: :true
# has_one :club, through: :membership
@@ -1332,12 +1332,12 @@ def has_one(name, scope = nil, options = {})
# Specify the foreign key used for the association. By default this is guessed to be the name
# of the association with an "_id" suffix. So a class that defines a <tt>belongs_to :person</tt>
# association will use "person_id" as the default <tt>:foreign_key</tt>. Similarly,
- # <tt>belongs_to :favorite_person, :class_name => "Person"</tt> will use a foreign key
+ # <tt>belongs_to :favorite_person, class_name: "Person"</tt> will use a foreign key
# of "favorite_person_id".
# [:foreign_type]
# Specify the column used to store the associated object's type, if this is a polymorphic
# association. By default this is guessed to be the name of the association with a "_type"
- # suffix. So a class that defines a <tt>belongs_to :taggable, :polymorphic => true</tt>
+ # suffix. So a class that defines a <tt>belongs_to :taggable, polymorphic: true</tt>
# association will use "taggable_type" as the default <tt>:foreign_type</tt>.
# [:primary_key]
# Specify the method that returns the primary key of associated object used for the association.
@@ -1357,7 +1357,7 @@ def has_one(name, scope = nil, options = {})
# <tt>#{table_name}_count</tt> is created on the associate class (such that Post.comments_count will
# return the count cached, see note below). You can also specify a custom counter
# cache column by providing a column name instead of a +true+/+false+ value to this
- # option (e.g., <tt>:counter_cache => :my_custom_counter</tt>.)
+ # option (e.g., <tt>counter_cache: :my_custom_counter</tt>.)
# Note: Specifying a counter cache will add it to that model's list of readonly attributes
# using +attr_readonly+.
# [:polymorphic]
@@ -1415,7 +1415,7 @@ def belongs_to(name, scope = nil, options = {})
#
# class CreateDevelopersProjectsJoinTable < ActiveRecord::Migration
# def change
- # create_table :developers_projects, :id => false do |t|
+ # create_table :developers_projects, id: false do |t|
# t.integer :developer_id
# t.integer :project_id
# end
View
22 activerecord/lib/active_record/autosave_association.rb
@@ -16,7 +16,7 @@ module ActiveRecord
# Note that it also means that associations marked for destruction won't
# be destroyed directly. They will however still be marked for destruction.
#
- # Note that <tt>:autosave => false</tt> is not same as not declaring <tt>:autosave</tt>.
+ # Note that <tt>autosave: false</tt> is not same as not declaring <tt>:autosave</tt>.
# When the <tt>:autosave</tt> option is not present new associations are saved.
#
# == Validation
@@ -37,7 +37,7 @@ module ActiveRecord
# === One-to-one Example
#
# class Post
- # has_one :author, :autosave => true
+ # has_one :author, autosave: true
# end
#
# Saving changes to the parent and its associated model can now be performed
@@ -81,27 +81,27 @@ module ActiveRecord
# has_many :comments # :autosave option is not declared
# end
#
- # post = Post.new(:title => 'ruby rocks')
- # post.comments.build(:body => 'hello world')
+ # post = Post.new(title: 'ruby rocks')
+ # post.comments.build(body: 'hello world')
# post.save # => saves both post and comment
#
- # post = Post.create(:title => 'ruby rocks')
- # post.comments.build(:body => 'hello world')
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.build(body: 'hello world')
# post.save # => saves both post and comment
#
- # post = Post.create(:title => 'ruby rocks')
- # post.comments.create(:body => 'hello world')
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.create(body: 'hello world')
# post.save # => saves both post and comment
#
# When <tt>:autosave</tt> is true all children are saved, no matter whether they
# are new records or not:
#
# class Post
- # has_many :comments, :autosave => true
+ # has_many :comments, autosave: true
# end
#
- # post = Post.create(:title => 'ruby rocks')
- # post.comments.create(:body => 'hello world')
+ # post = Post.create(title: 'ruby rocks')
+ # post.comments.create(body: 'hello world')
# post.comments[0].body = 'hi everyone'
# post.save # => saves both post and comment, with 'hi everyone' as body
#
View
38 activerecord/lib/active_record/base.rb
@@ -35,7 +35,7 @@ module ActiveRecord #:nodoc:
# method is especially useful when you're receiving the data from somewhere else, like an
# HTTP request. It works like this:
#
- # user = User.new(:name => "David", :occupation => "Code Artist")
+ # user = User.new(name: "David", occupation: "Code Artist")
# user.name # => "David"
#
# You can also use block initialization:
@@ -68,7 +68,7 @@ module ActiveRecord #:nodoc:
# end
#
# def self.authenticate_safely_simply(user_name, password)
- # where(:user_name => user_name, :password => password).first
+ # where(user_name: user_name, password: password).first
# end
# end
#
@@ -86,27 +86,27 @@ module ActiveRecord #:nodoc:
#
# Company.where(
# "id = :id AND name = :name AND division = :division AND created_at > :accounting_date",
- # { :id => 3, :name => "37signals", :division => "First", :accounting_date => '2005-01-01' }
+ # { id: 3, name: "37signals", division: "First", accounting_date: '2005-01-01' }
# ).first
#
# Similarly, a simple hash without a statement will generate conditions based on equality with the SQL AND
# operator. For instance:
#
- # Student.where(:first_name => "Harvey", :status => 1)
+ # Student.where(first_name: "Harvey", status: 1)
# Student.where(params[:student])
#
# A range may be used in the hash to use the SQL BETWEEN operator:
#
- # Student.where(:grade => 9..12)
+ # Student.where(grade: 9..12)
#
# An array may be used in the hash to use the SQL IN operator:
#
- # Student.where(:grade => [9,11,12])
+ # Student.where(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.joins(:schools).where(:schools => { :category => 'public' })
+ # Student.joins(:schools).where(schools: { category: 'public' })
# Student.joins(:schools).where('schools.category' => 'public' )
#
# == Overwriting default accessors
@@ -140,10 +140,10 @@ module ActiveRecord #:nodoc:
# For example, an Active Record User with the <tt>name</tt> attribute has a <tt>name?</tt> method that you can call
# to determine whether the user has a name:
#
- # user = User.new(:name => "David")
+ # user = User.new(name: "David")
# user.name? # => true
#
- # anonymous = User.new(:name => "")
+ # anonymous = User.new(name: "")
# anonymous.name? # => false
#
# == Accessing attributes before they have been typecasted
@@ -164,8 +164,8 @@ module ActiveRecord #:nodoc:
# to <tt>find_by_</tt>, <tt>find_last_by_</tt>, or <tt>find_all_by_</tt> and thus produces finders
# like <tt>Person.find_by_user_name</tt>, <tt>Person.find_all_by_last_name</tt>, and
# <tt>Payment.find_by_transaction_id</tt>. Instead of writing
- # <tt>Person.where(:user_name => user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
- # And instead of writing <tt>Person.where(:last_name => last_name).all</tt>, you just do
+ # <tt>Person.where(user_name: user_name).first</tt>, you just do <tt>Person.find_by_user_name(user_name)</tt>.
+ # And instead of writing <tt>Person.where(last_name: last_name).all</tt>, you just do
# <tt>Person.find_all_by_last_name(last_name)</tt>.
#
# It's possible to add an exclamation point (!) on the end of the dynamic finders to get them to raise an
@@ -174,7 +174,7 @@ module ActiveRecord #:nodoc:
#
# It's also possible to use multiple attributes in the same find by separating them with "_and_".
#
- # Person.where(:user_name => user_name, :password => password).first
+ # Person.where(user_name: user_name, password: password).first
# Person.find_by_user_name_and_password(user_name, password) # with dynamic finder
#
# It's even possible to call these dynamic finder methods on relations and named scopes.
@@ -188,13 +188,13 @@ module ActiveRecord #:nodoc:
# unless they are given in a block.
#
# # No 'Summer' tag exists
- # Tag.find_or_create_by_name("Summer") # equal to Tag.create(:name => "Summer")
+ # Tag.find_or_create_by_name("Summer") # equal to Tag.create(name: "Summer")
#
# # Now the 'Summer' tag does exist
# Tag.find_or_create_by_name("Summer") # equal to Tag.find_by_name("Summer")
#
# # Now 'Bob' exist and is an 'admin'
- # User.find_or_create_by_name('Bob', :age => 40) { |u| u.admin = true }
+ # User.find_or_create_by_name('Bob', age: 40) { |u| u.admin = true }
#
# Adding an exclamation point (!) on to the end of <tt>find_or_create_by_</tt> will
# raise an <tt>ActiveRecord::RecordInvalid</tt> error if the new record is invalid.
@@ -209,7 +209,7 @@ module ActiveRecord #:nodoc:
# To find by a subset of the attributes to be used for instantiating a new object, pass a hash instead of
# a list of parameters.
#
- # Tag.find_or_create_by_name(:name => "rails", :creator => current_user)
+ # Tag.find_or_create_by_name(name: "rails", creator: current_user)
#
# That will either find an existing tag named "rails", or create a new one while setting the
# user that created it.
@@ -231,7 +231,7 @@ module ActiveRecord #:nodoc:
# serialize :preferences
# end
#
- # user = User.create(:preferences => { "background" => "black", "display" => large })
+ # user = User.create(preferences: { "background" => "black", "display" => large })
# User.find(user.id).preferences # => { "background" => "black", "display" => large }
#
# You can also specify a class option as the second parameter that'll raise an exception
@@ -241,7 +241,7 @@ module ActiveRecord #:nodoc:
# serialize :preferences, Hash
# end
#
- # user = User.create(:preferences => %w( one two three ))
+ # user = User.create(preferences: %w( one two three ))
# User.find(user.id).preferences # raises SerializationTypeMismatch
#
# When you specify a class option, the default value for that attribute will be a new
@@ -266,9 +266,9 @@ module ActiveRecord #:nodoc:
# class Client < Company; end
# class PriorityClient < Client; end
#
- # When you do <tt>Firm.create(:name => "37signals")</tt>, this record will be saved in
+ # When you do <tt>Firm.create(name: "37signals")</tt>, this record will be saved in
# the companies table with type = "Firm". You can then fetch this row again using
- # <tt>Company.where(:name => '37signals').first</tt> and it will return a Firm object.
+ # <tt>Company.where(name: '37signals').first</tt> and it will return a Firm object.
#
# If you don't have a type column defined in your table, single-table inheritance won't
# be triggered. In that case, it'll work just like normal subclasses with no special magic
View
2 activerecord/lib/active_record/callbacks.rb
@@ -35,7 +35,7 @@ module ActiveRecord
# class CreditCard < ActiveRecord::Base
# # Strip everything but digits, so the user can specify "555 234 34" or
# # "5552-3434" and both will mean "55523434"
- # before_validation(:on => :create) do
+ # before_validation(on: :create) do
# self.number = number.gsub(/[^0-9]/, "") if attribute_present?("number")
# end
# end
View
16 activerecord/lib/active_record/connection_handling.rb
@@ -5,18 +5,18 @@ module ConnectionHandling
# example for regular databases (MySQL, Postgresql, etc):
#
# ActiveRecord::Base.establish_connection(
- # :adapter => "mysql",
- # :host => "localhost",
- # :username => "myuser",
- # :password => "mypass",
- # :database => "somedatabase"
+ # adapter: "mysql",
+ # host: "localhost",
+ # username: "myuser",
+ # password: "mypass",
+ # database: "somedatabase"
# )
#
# Example for SQLite database:
#
# ActiveRecord::Base.establish_connection(
- # :adapter => "sqlite",
- # :database => "path/to/dbfile"
+ # adapter: "sqlite",
+ # database: "path/to/dbfile"
# )
#
# Also accepts keys as strings (for parsing from YAML for example):
@@ -64,7 +64,7 @@ def connection_id=(connection_id)
# Returns the configuration of the associated connection as a hash:
#
# ActiveRecord::Base.connection_config
- # # => {:pool=>5, :timeout=>5000, :database=>"db/development.sqlite3", :adapter=>"sqlite3"}
+ # # => {pool: 5, timeout: 5000, database: "db/development.sqlite3", adapter: "sqlite3"}
#
# Please use only for reading.
def connection_config
View
2 activerecord/lib/active_record/core.rb
@@ -154,7 +154,7 @@ def relation #:nodoc:
#
# ==== Example:
# # Instantiates a single new object
- # User.new(:first_name => 'Jamie')
+ # User.new(first_name: 'Jamie')
def initialize(attributes = nil)
defaults = self.class.column_defaults.dup
defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
View
4 activerecord/lib/active_record/counter_cache.rb
@@ -56,7 +56,7 @@ def reset_counters(id, *counters)
#
# # For the Post with id of 5, decrement the comment_count by 1, and
# # increment the action_count by 1
- # Post.update_counters 5, :comment_count => -1, :action_count => 1
+ # Post.update_counters 5, comment_count: -1, action_count: 1
# # Executes the following SQL:
# # UPDATE posts
# # SET comment_count = COALESCE(comment_count, 0) - 1,
@@ -64,7 +64,7 @@ def reset_counters(id, *counters)
# # WHERE id = 5
#
# # For the Posts with id of 10 and 15, increment the comment_count by 1
- # Post.update_counters [10, 15], :comment_count => 1
+ # Post.update_counters [10, 15], comment_count: 1
# # Executes the following SQL:
# # UPDATE posts
# # SET comment_count = COALESCE(comment_count, 0) + 1
View
2 activerecord/lib/active_record/errors.rb
@@ -22,7 +22,7 @@ class SubclassNotFound < ActiveRecordError #:nodoc:
# end
#
# # Comments are not patches, this assignment raises AssociationTypeMismatch.
- # @ticket.patches << Comment.new(:content => "Please attach tests to your patch.")
+ # @ticket.patches << Comment.new(content: "Please attach tests to your patch.")
class AssociationTypeMismatch < ActiveRecordError
end
View
4 activerecord/lib/active_record/fixtures.rb
@@ -250,7 +250,7 @@ class FixtureClassNotFound < ActiveRecord::ActiveRecordError #:nodoc:
#
# ### in fruit.rb
#
- # belongs_to :eater, :polymorphic => true
+ # belongs_to :eater, polymorphic: true
#
# ### in fruits.yml
#
@@ -730,7 +730,7 @@ module ClassMethods
#
# Examples:
#
- # set_fixture_class :some_fixture => SomeModel,
+ # set_fixture_class some_fixture: SomeModel,
# 'namespaced/fixture' => Another::Model
#
# The keys must be the fixture names, that coincide with the short paths to the fixture files.
View
6 activerecord/lib/active_record/locking/pessimistic.rb
@@ -3,12 +3,12 @@ module Locking
# Locking::Pessimistic provides support for row-level locking using
# SELECT ... FOR UPDATE and other lock types.
#
- # Pass <tt>:lock => true</tt> to <tt>ActiveRecord::Base.find</tt> to obtain an exclusive
+ # Pass <tt>lock: true</tt> to <tt>ActiveRecord::Base.find</tt> to obtain an exclusive
# lock on the selected rows:
# # select * from accounts where id=1 for update
- # Account.find(1, :lock => true)
+ # Account.find(1, lock: true)
#
- # Pass <tt>:lock => 'some locking clause'</tt> to give a database-specific locking clause
+ # Pass <tt>lock: 'some locking clause'</tt> to give a database-specific locking clause
# of your own such as 'LOCK IN SHARE MODE' or 'FOR UPDATE NOWAIT'. Example:
#
# Account.transaction do
View
2 activerecord/lib/active_record/model_schema.rb
@@ -285,7 +285,7 @@ def column_methods_hash #:nodoc:
#
# JobLevel.reset_column_information
# %w{assistant executive manager director}.each do |type|
- # JobLevel.create(:name => type)
+ # JobLevel.create(name: type)
# end
# end
#
View
70 activerecord/lib/active_record/nested_attributes.rb
@@ -50,14 +50,14 @@ class TooManyRecords < ActiveRecordError
# Enabling nested attributes on a one-to-one association allows you to
# create the member and avatar in one go:
#
- # params = { :member => { :name => 'Jack', :avatar_attributes => { :icon => 'smiling' } } }
+ # params = { member: { name: 'Jack', avatar_attributes: { icon: 'smiling' } } }
# member = Member.create(params[:member])
# member.avatar.id # => 2
# member.avatar.icon # => 'smiling'
#
# It also allows you to update the avatar through the member:
#
- # params = { :member => { :avatar_attributes => { :id => '2', :icon => 'sad' } } }
+ # params = { member: { avatar_attributes: { id: '2', icon: 'sad' } } }
# member.update_attributes params[:member]
# member.avatar.icon # => 'sad'
#
@@ -68,13 +68,13 @@ class TooManyRecords < ActiveRecordError
#
# class Member < ActiveRecord::Base
# has_one :avatar
- # accepts_nested_attributes_for :avatar, :allow_destroy => true
+ # accepts_nested_attributes_for :avatar, allow_destroy: true
# end
#
# Now, when you add the <tt>_destroy</tt> key to the attributes hash, with a
# value that evaluates to +true+, you will destroy the associated model:
#
- # member.avatar_attributes = { :id => '2', :_destroy => '1' }
+ # member.avatar_attributes = { id: '2', _destroy: '1' }
# member.avatar.marked_for_destruction? # => true
# member.save
# member.reload.avatar # => nil
@@ -97,11 +97,11 @@ class TooManyRecords < ActiveRecordError
# be instantiated, unless the hash also contains a <tt>_destroy</tt> key
# that evaluates to +true+.
#
- # params = { :member => {
- # :name => 'joe', :posts_attributes => [
- # { :title => 'Kari, the awesome Ruby documentation browser!' },
- # { :title => 'The egalitarian assumption of the modern citizen' },
- # { :title => '', :_destroy => '1' } # this will be ignored
+ # params = { member: {
+ # name: 'joe', posts_attributes: [
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
+ # { title: 'The egalitarian assumption of the modern citizen' },
+ # { title: '', _destroy: '1' } # this will be ignored
# ]
# }}
#
@@ -116,14 +116,14 @@ class TooManyRecords < ActiveRecordError
#
# class Member < ActiveRecord::Base
# has_many :posts
- # accepts_nested_attributes_for :posts, :reject_if => proc { |attributes| attributes['title'].blank? }
+ # accepts_nested_attributes_for :posts, reject_if: proc { |attributes| attributes['title'].blank? }
# end
#
- # params = { :member => {
- # :name => 'joe', :posts_attributes => [
- # { :title => 'Kari, the awesome Ruby documentation browser!' },
- # { :title => 'The egalitarian assumption of the modern citizen' },
- # { :title => '' } # this will be ignored because of the :reject_if proc
+ # params = { member: {
+ # name: 'joe', posts_attributes: [
+ # { title: 'Kari, the awesome Ruby documentation browser!' },
+ # { title: 'The egalitarian assumption of the modern citizen' },
+ # { title: '' } # this will be ignored because of the :reject_if proc
# ]
# }}
#
@@ -136,12 +136,12 @@ class TooManyRecords < ActiveRecordError
#
# class Member < ActiveRecord::Base
# has_many :posts
- # accepts_nested_attributes_for :posts, :reject_if => :new_record?
+ # accepts_nested_attributes_for :posts, reject_if: :new_record?
# end
#
# class Member < ActiveRecord::Base
# has_many :posts
- # accepts_nested_attributes_for :posts, :reject_if => :reject_posts
+ # accepts_nested_attributes_for :posts, reject_if: :reject_posts
#
# def reject_posts(attributed)
# attributed['title'].blank?
@@ -152,10 +152,10 @@ class TooManyRecords < ActiveRecordError
# associated record, the matching record will be modified:
#
# member.attributes = {
- # :name => 'Joe',
- # :posts_attributes => [
- # { :id => 1, :title => '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
- # { :id => 2, :title => '[UPDATED] other post' }
+ # name: 'Joe',
+ # posts_attributes: [
+ # { id: 1, title: '[UPDATED] An, as of yet, undisclosed awesome Ruby documentation browser!' },
+ # { id: 2, title: '[UPDATED] other post' }
# ]
# }
#
@@ -170,11 +170,11 @@ class TooManyRecords < ActiveRecordError
#
# class Member < ActiveRecord::Base
# has_many :posts
- # accepts_nested_attributes_for :posts, :allow_destroy => true
+ # accepts_nested_attributes_for :posts, allow_destroy: true
# end
#
- # params = { :member => {
- # :posts_attributes => [{ :id => '2', :_destroy => '1' }]
+ # params = { member: {
+ # posts_attributes: [{ id: '2', _destroy: '1' }]
# }}
#
# member.attributes = params[:member]
@@ -197,12 +197,12 @@ class TooManyRecords < ActiveRecordError
# <tt>inverse_of</tt> as this example illustrates:
#
# class Member < ActiveRecord::Base
- # has_many :posts, :inverse_of => :member
+ # has_many :posts, inverse_of: :member
# accepts_nested_attributes_for :posts
# end
#
# class Post < ActiveRecord::Base
- # belongs_to :member, :inverse_of => :posts
+ # belongs_to :member, inverse_of: :posts
# validates_presence_of :member
# end
module ClassMethods
@@ -248,11 +248,11 @@ module ClassMethods
#
# Examples:
# # creates avatar_attributes=
- # accepts_nested_attributes_for :avatar, :reject_if => proc { |attributes| attributes['name'].blank? }
+ # accepts_nested_attributes_for :avatar, reject_if: proc { |attributes| attributes['name'].blank? }
# # creates avatar_attributes=
- # accepts_nested_attributes_for :avatar, :reject_if => :all_blank
+ # accepts_nested_attributes_for :avatar, reject_if: :all_blank
# # creates avatar_attributes= and posts_attributes=
- # accepts_nested_attributes_for :avatar, :posts, :allow_destroy => true
+ # accepts_nested_attributes_for :avatar, :posts, allow_destroy: true
def accepts_nested_attributes_for(*attr_names)
options = { :allow_destroy => false, :update_only => false }
options.update(attr_names.extract_options!)
@@ -348,9 +348,9 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
# For example:
#
# assign_nested_attributes_for_collection_association(:people, {
- # '1' => { :id => '1', :name => 'Peter' },
- # '2' => { :name => 'John' },
- # '3' => { :id => '2', :_destroy => true }
+ # '1' => { id: '1', name: 'Peter' },
+ # '2' => { name: 'John' },
+ # '3' => { id: '2', _destroy: true }
# })
#
# Will update the name of the Person with ID 1, build a new associated
@@ -360,9 +360,9 @@ def assign_nested_attributes_for_one_to_one_association(association_name, attrib
# Also accepts an Array of attribute hashes:
#
# assign_nested_attributes_for_collection_association(:people, [
- # { :id => '1', :name => 'Peter' },
- # { :name => 'John' },
- # { :id => '2', :_destroy => true }
+ # { id: '1', name: 'Peter' },
+ # { name: 'John' },
+ # { id: '2', _destroy: true }
# ])
def assign_nested_attributes_for_collection_association(association_name, attributes_collection)
options = self.nested_attributes_options[association_name]
View
2 activerecord/lib/active_record/relation.rb
@@ -486,7 +486,7 @@ def to_sql
# Returns a hash of where conditions
#
# Users.where(name: 'Oscar').where_values_hash
- # # => {:name=>"oscar"}
+ # # => {name: "oscar"}
def where_values_hash
equalities = with_default_scope.where_values.grep(Arel::Nodes::Equality).find_all { |node|
node.left.relation.name == table_name
View
2 activerecord/lib/active_record/relation/calculations.rb
@@ -145,7 +145,7 @@ def calculate(operation, column_name, options = {})
# # SELECT DISTINCT role FROM people
# # => ['admin', 'member', 'guest']
#
- # Person.where(:age => 21).limit(5).pluck(:id)
+ # Person.where(age: 21).limit(5).pluck(:id)
# # SELECT people.id FROM people WHERE people.age = 21 LIMIT 5
# # => [2, 3]
#
View
2 activerecord/lib/active_record/relation/finder_methods.rb
@@ -76,7 +76,7 @@ def take!
#
# Person.first # returns the first object fetched by SELECT * FROM people
# Person.where(["user_name = ?", user_name]).first
- # Person.where(["user_name = :u", { :u => user_name }]).first
+ # Person.where(["user_name = :u", { u: user_name }]).first
# Person.order("created_on DESC").offset(5).first
# Person.first(3) # returns the first three objects fetched by SELECT * FROM people LIMIT 3
def first(limit = nil)
View
4 activerecord/lib/active_record/relation/predicate_builder.rb
@@ -36,10 +36,10 @@ def self.expand(klass, table, column, value)
queries = []
# Find the foreign key when using queries such as:
- # Post.where(:author => author)
+ # Post.where(author: author)
#
# For polymorphic relationships, find the foreign key and type:
- # PriceEstimate.where(:estimate_of => treasure)
+ # PriceEstimate.where(estimate_of: treasure)
if klass && value.class < Base && reflection = klass.reflect_on_association(column.to_sym)
if reflection.polymorphic?
queries << build(table[reflection.foreign_type], value.class.base_class)
View
18 activerecord/lib/active_record/relation/query_methods.rb
@@ -355,17 +355,17 @@ def bind!(value)
# author = Author.find(1)
#
# # The following queries will be equivalent:
- # Post.where(:author => author)
- # Post.where(:author_id => author)
+ # Post.where(author: author)
+ # Post.where(author_id: author)
#
# This also works with polymorphic belongs_to relationships:
#
- # treasure = Treasure.create(:name => 'gold coins')
- # treasure.price_estimates << PriceEstimate.create(:price => 125)
+ # treasure = Treasure.create(name: 'gold coins')
+ # treasure.price_estimates << PriceEstimate.create(price: 125)
#
# # The following queries will be equivalent:
- # PriceEstimate.where(:estimate_of => treasure)
- # PriceEstimate.where(:estimate_of_type => 'Treasure', :estimate_of_id => treasure)
+ # PriceEstimate.where(estimate_of: treasure)
+ # PriceEstimate.where(estimate_of_type: 'Treasure', estimate_of_id: treasure)
#
# === Joins
#
@@ -377,7 +377,7 @@ def bind!(value)
# For hash conditions, you can either use the table name in the key, or use a sub-hash.
#
# User.joins(:posts).where({ "posts.published" => true })
- # User.joins(:posts).where({ :posts => { :published => true } })
+ # User.joins(:posts).where({ posts: { published: true } })
#
# === empty condition
#
@@ -476,13 +476,13 @@ def lock!(locks = true)
#
# For example:
#
- # @posts = current_user.visible_posts.where(:name => params[:name])
+ # @posts = current_user.visible_posts.where(name: params[:name])
# # => the visible_posts method is expected to return a chainable Relation
#
# def visible_posts
# case role
# when 'Country Manager'
- # Post.where(:country => country)
+ # Post.where(country: country)
# when 'Reviewer'
# Post.published
# when 'Bad User'
View
4 activerecord/lib/active_record/relation/spawn_methods.rb
@@ -15,11 +15,11 @@ def spawn #:nodoc:
#
# ==== Examples
#
- # Post.where(:published => true).joins(:comments).merge( Comment.where(:spam => false) )
+ # Post.where(published: true).joins(:comments).merge( Comment.where(spam: false) )
# # Performs a single join query with both where conditions.
#
# recent_posts = Post.order('created_at DESC').first(5)
- # Post.where(:published => true).merge(recent_posts)
+ # Post.where(published: true).merge(recent_posts)
# # Returns the intersection of all published posts with the 5 most recently created posts.
# # (This is just an example. You'd probably want to do this with a single query!)
#
View
24 activerecord/lib/active_record/sanitization.rb
@@ -17,7 +17,7 @@ def sanitize(object) #:nodoc:
# Accepts an array, hash, or string of SQL conditions and sanitizes
# them into a valid SQL fragment for a WHERE clause.
# ["name='%s' and group_id='%s'", "foo'bar", 4] returns "name='foo''bar' and group_id='4'"
- # { :name => "foo'bar", :group_id => 4 } returns "name='foo''bar' and group_id='4'"
+ # { name: "foo'bar", group_id: 4 } returns "name='foo''bar' and group_id='4'"
# "name='foo''bar' and group_id='4'" returns "name='foo''bar' and group_id='4'"
def sanitize_sql_for_conditions(condition, table_name = self.table_name)
return nil if condition.blank?
@@ -32,7 +32,7 @@ def sanitize_sql_for_conditions(condition, table_name = self.table_name)
# Accepts an array, hash, or string of SQL conditions and sanitizes
# them into a valid SQL fragment for a SET clause.
- # { :name => nil, :group_id => 4 } returns "name = NULL , group_id='4'"
+ # { name: nil, group_id: 4 } returns "name = NULL , group_id='4'"
def sanitize_sql_for_assignment(assignments)
case assignments
when Array; sanitize_sql_array(assignments)
@@ -46,12 +46,12 @@ def sanitize_sql_for_assignment(assignments)
# aggregate attribute values.
# Given:
# class Person < ActiveRecord::Base
- # composed_of :address, :class_name => "Address",
- # :mapping => [%w(address_street street), %w(address_city city)]
+ # composed_of :address, class_name: "Address",
+ # mapping: [%w(address_street street), %w(address_city city)]
# end
# Then:
- # { :address => Address.new("813 abc st.", "chicago") }
- # # => { :address_street => "813 abc st.", :address_city => "chicago" }
+ # { address: Address.new("813 abc st.", "chicago") }
+ # # => { address_street: "813 abc st.", address_city: "chicago" }
def expand_hash_conditions_for_aggregates(attrs)
expanded_attrs = {}
attrs.each do |attr, value|
@@ -72,18 +72,18 @@ def expand_hash_conditions_for_aggregates(attrs)
end
# Sanitizes a hash of attribute/value pairs into SQL conditions for a WHERE clause.
- # { :name => "foo'bar", :group_id => 4 }
+ # { name: "foo'bar", group_id: 4 }
# # => "name='foo''bar' and group_id= 4"
- # { :status => nil, :group_id => [1,2,3] }
+ # { status: nil, group_id: [1,2,3] }
# # => "status IS NULL and group_id IN (1,2,3)"
- # { :age => 13..18 }
+ # { age: 13..18 }
# # => "age BETWEEN 13 AND 18"
# { 'other_records.id' => 7 }
# # => "`other_records`.`id` = 7"
- # { :other_records => { :id => 7 } }
+ # { other_records: { id: 7 } }
# # => "`other_records`.`id` = 7"
# And for value objects on a composed_of relationship:
- # { :address => Address.new("123 abc st.", "chicago") }
+ # { address: Address.new("123 abc st.", "chicago") }
# # => "address_street='123 abc st.' and address_city='chicago'"
def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name)
attrs = expand_hash_conditions_for_aggregates(attrs)
@@ -96,7 +96,7 @@ def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name
alias_method :sanitize_sql_hash, :sanitize_sql_hash_for_conditions
# Sanitizes a hash of attribute/value pairs into SQL conditions for a SET clause.
- # { :status => nil, :group_id => 1 }
+ # { status: nil, group_id: 1 }
# # => "status = NULL , group_id = 1"
def sanitize_sql_hash_for_assignment(attrs)
attrs.map do |attr, value|
View
14 activerecord/lib/active_record/serializers/xml_serializer.rb
@@ -36,7 +36,7 @@ module Serialization
#
# For instance:
#
- # topic.to_xml(:skip_instruct => true, :except => [ :id, :bonus_time, :written_on, :replies_count ])
+ # topic.to_xml(skip_instruct: true, except: [ :id, :bonus_time, :written_on, :replies_count ])
#
# <topic>
# <title>The First Topic</title>
@@ -50,7 +50,7 @@ module Serialization
#
# To include first level associations use <tt>:include</tt>:
#
- # firm.to_xml :include => [ :account, :clients ]
+ # firm.to_xml include: [ :account, :clients ]
#
# <?xml version="1.0" encoding="UTF-8"?>
# <firm>
@@ -81,7 +81,7 @@ module Serialization
# associated with models.
#
# proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
- # firm.to_xml :procs => [ proc ]
+ # firm.to_xml procs: [ proc ]
#
# <firm>
# # ... normal attributes as shown above ...
@@ -90,7 +90,7 @@ module Serialization
#
# To include deeper levels of associations pass a hash like this:
#
- # firm.to_xml :include => {:account => {}, :clients => {:include => :address}}
+ # firm.to_xml include: {account: {}, clients: {include: :address}}
# <?xml version="1.0" encoding="UTF-8"?>
# <firm>
# <id type="integer">1</id>
@@ -120,7 +120,7 @@ module Serialization
#
# To include any methods on the model being called use <tt>:methods</tt>:
#
- # firm.to_xml :methods => [ :calculated_earnings, :real_earnings ]
+ # firm.to_xml methods: [ :calculated_earnings, :real_earnings ]
#
# <firm>
# # ... normal attributes as shown above ...
@@ -132,7 +132,7 @@ module Serialization
# modified version of the options hash that was given to +to_xml+:
#
# proc = Proc.new { |options| options[:builder].tag!('abc', 'def') }
- # firm.to_xml :procs => [ proc ]
+ # firm.to_xml procs: [ proc ]
#
# <firm>
# # ... normal attributes as shown above ...
@@ -164,7 +164,7 @@ module Serialization
# def to_xml(options = {})
# require 'builder'
# options[:indent] ||= 2
- # xml = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
+ # xml = options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
# xml.instruct! unless options[:skip_instruct]
# xml.level_one do
# xml.tag!(:second_level, 'content')
View
28 activerecord/lib/active_record/transactions.rb
@@ -108,10 +108,10 @@ class TransactionError < ActiveRecordError # :nodoc:
#
# # Suppose that we have a Number model with a unique column called 'i'.
# Number.transaction do
- # Number.create(:i => 0)
+ # Number.create(i: 0)
# begin
# # This will raise a unique constraint error...
- # Number.create(:i => 0)
+ # Number.create(i: 0)
# rescue ActiveRecord::StatementInvalid
# # ...which we ignore.
# end
@@ -119,7 +119,7 @@ class TransactionError < ActiveRecordError # :nodoc:
# # On PostgreSQL, the transaction is now unusable. The following
# # statement will cause a PostgreSQL error, even though the unique
# # constraint is no longer violated:
- # Number.create(:i => 1)
+ # Number.create(i: 1)
# # => "PGError: ERROR: current transaction is aborted, commands
# # ignored until end of transaction block"
# end
@@ -134,9 +134,9 @@ class TransactionError < ActiveRecordError # :nodoc:
# transaction. For example, the following behavior may be surprising:
#
# User.transaction do
- # User.create(:username => 'Kotori')
+ # User.create(username: 'Kotori')
# User.transaction do
- # User.create(:username => 'Nemu')
+ # User.create(username: 'Nemu')
# raise ActiveRecord::Rollback
# end
# end
@@ -147,14 +147,14 @@ class TransactionError < ActiveRecordError # :nodoc:
# real transaction is committed.
#
# In order to get a ROLLBACK for the nested transaction you may ask for a real
- # sub-transaction by passing <tt>:requires_new => true</tt>. If anything goes wrong,
+ # sub-transaction by passing <tt>requires_new: true</tt>. If anything goes wrong,
# the database rolls back to the beginning of the sub-transaction without rolling
# back the parent transaction. If we add it to the previous example:
#
# User.transaction do
- # User.create(:username => 'Kotori')
- # User.transaction(:requires_new => true) do
- # User.create(:username => 'Nemu')
+ # User.create(username: 'Kotori')
+ # User.transaction(requires_new: true) do
+ # User.create(username: 'Nemu')
# raise ActiveRecord::Rollback
# end
# end
@@ -194,7 +194,7 @@ class TransactionError < ActiveRecordError # :nodoc:
# automatically released. The following example demonstrates the problem:
#
# Model.connection.transaction do # BEGIN
- # Model.connection.transaction(:requires_new => true) do # CREATE SAVEPOINT active_record_1
+ # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1
# Model.connection.create_table(...) # active_record_1 now automatically released
# end # RELEASE savepoint active_record_1
# # ^^^^ BOOM! database error!
@@ -213,13 +213,13 @@ def transaction(options = {}, &block)
# You can specify that the callback should only be fired by a certain action with
# the +:on+ option:
#
- # after_commit :do_foo, :on => :create
- # after_commit :do_bar, :on => :update
- # after_commit :do_baz, :on => :destroy
+ # after_commit :do_foo, on: :create
+ # after_commit :do_bar, on: :update
+ # after_commit :do_baz, on: :destroy
#
# Also, to have the callback fired on create and update, but not on destroy:
#
- # after_commit :do_zoo, :if => :persisted?
+ # after_commit :do_zoo, if: :persisted?
#
# Note that transactional fixtures do not play well with this feature. Please
# use the +test_after_commit+ gem to have these hooks fired in tests.
View
10 activesupport/lib/active_support/concern.rb
@@ -4,7 +4,9 @@ module ActiveSupport
# module M
# def self.included(base)
# base.extend ClassMethods
- # scope :disabled, -> { where(disabled: true) }
+ # base.class_eval do
+ # scope :disabled, -> { where(disabled: true) }
+ # end
# end
#
# module ClassMethods
@@ -77,10 +79,8 @@ module ActiveSupport
# module Foo
# extend ActiveSupport::Concern
# included do
- # class_eval do
- # def self.method_injected_by_foo
- # ...
- # end
+ # def self.method_injected_by_foo
+ # ...
# end
# end
# end
View
18 activesupport/lib/active_support/notifications.rb
@@ -84,15 +84,15 @@ module ActiveSupport
# resulting in the following output within the logs including a hash with the payload:
#
# notification: process_action.action_controller 2012-04-13 01:08:35 +0300 2012-04-13 01:08:35 +0300 af358ed7fab884532ec7 {
- # :controller=>"Devise::SessionsController",
- # :action=>"new",
- # :params=>{"action"=>"new", "controller"=>"devise/sessions"},
- # :format=>:html,
- # :method=>"GET",
- # :path=>"/login/sign_in",
- # :status=>200,
- # :view_runtime=>279.3080806732178,
- # :db_runtime=>40.053
+ # controller: "Devise::SessionsController",
+ # action: "new",
+ # params: {"action"=>"new", "controller"=>"devise/sessions"},
+ # format: :html,
+ # method: "GET",
+ # path: "/login/sign_in",
+ # status: 200,
+ # view_runtime: 279.3080806732178,
+ # db_runtime: 40.053
# }
#
# You can also subscribe to all events whose name matches a certain regexp:
View
36 guides/source/action_controller_overview.md
@@ -81,7 +81,7 @@ class ClientsController < ActionController::Base
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
- render action: "new"
+ render "new"
end
end
end
@@ -179,9 +179,9 @@ Your application has a session for each user in which you can store small amount
All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).
-For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
+For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
-The CookieStore can store around 4kB of data -- much less than the others -- but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
+The CookieStore can store around 4kB of data much less than the others but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.
If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.
@@ -371,13 +371,13 @@ end
Cookies
-------
-Your application can store small amounts of data on the client -- called cookies -- that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which -- much like the `session` -- works like a hash:
+Your application can store small amounts of data on the client called cookies that will be persisted across requests and even sessions. Rails provides easy access to cookies via the `cookies` method, which much like the `session` works like a hash:
```ruby
class CommentsController < ApplicationController
def new
# Auto-fill the commenter's name if it has been stored in a cookie
- @comment = Comment.new(name: cookies[:commenter_name])
+ @comment = Comment.new(author: cookies[:commenter_name])
end
def create
@@ -386,7 +386,7 @@ class CommentsController < ApplicationController
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
# Remember the commenter's name.
- cookies[:commenter_name] = @comment.name
+ cookies[:commenter_name] = @comment.author
else
# Delete cookie for the commenter's name cookie, if any.
cookies.delete(:commenter_name)
@@ -404,7 +404,7 @@ Note that while for session values you set the key to `nil`, to delete a cookie
Rendering xml and json data
---------------------------
-ActionController makes it extremely easy to render `xml` or `json` data. If you generate a controller using scaffold then your controller would look something like this.
+ActionController makes it extremely easy to render `xml` or `json` data. If you generate a controller using scaffolding then it would look something like this:
```ruby
class UsersController < ApplicationController
@@ -428,7 +428,7 @@ Filters are methods that are run before, after or "around" a controller action.
Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
-Before filters may halt the request cycle. A common before filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
+"Before" filters may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:
```ruby
class ApplicationController < ActionController::Base
@@ -454,7 +454,7 @@ class ApplicationController < ActionController::Base
end
```
-The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.
+The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.
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`:
@@ -468,11 +468,11 @@ Now, the `LoginsController`'s `new` and `create` actions will work as before wit
### After Filters and Around Filters
-In addition to before filters, you can also run filters after an action has been executed, or both before and after.
+In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
-After filters are similar to before filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, after filters cannot stop the action from running.
+"After" filters are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running.
-Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
+"Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:
@@ -494,7 +494,7 @@ class ChangesController < ActionController::Base
end
```
-Note that an around filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
+Note that an "around" filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
You can choose not to yield and build the response yourself, in which case the action will not be run.
@@ -616,6 +616,8 @@ If you want to set custom headers for a response then `response.headers` is the
response.headers["Content-Type"] = "application/pdf"
```
+Note: in the above case it would make more sense to use the `content_type` setter directly.
+
HTTP Authentications
--------------------
@@ -711,7 +713,7 @@ This will read and stream the file 4kB at the time, avoiding loading the entire
If `:type` is not specified, it will be guessed from the file extension specified in `:filename`. If the content type is not registered for the extension, `application/octet-stream` will be used.
-WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.
+WARNING: Be careful when using data coming from the client (params, cookies, etc.) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to.
TIP: It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack.
@@ -824,7 +826,7 @@ NOTE: Certain exceptions are only rescuable from the `ApplicationController` cla
Force HTTPS protocol
--------------------
-Sometime you might want to force a particular