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

1.9 Syntax related changes

This commit is contained in:
AvnerCohen 2012-11-10 17:16:21 +02:00
parent dcf401e3bc
commit 890da5149d
15 changed files with 93 additions and 93 deletions

View file

@ -56,7 +56,7 @@ module ActiveRecord
#
# # 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 @@ module ActiveRecord
# # 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 file

@ -22,7 +22,7 @@ module ActiveRecord
# 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 file

@ -250,7 +250,7 @@ module ActiveRecord
#
# ### in fruit.rb
#
# belongs_to :eater, :polymorphic => true
# belongs_to :eater, polymorphic: true
#
# ### in fruits.yml
#
@ -730,7 +730,7 @@ module ActiveRecord
#
# 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 file

@ -3,12 +3,12 @@ module ActiveRecord
# 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 file

@ -285,7 +285,7 @@ module ActiveRecord
#
# JobLevel.reset_column_information
# %w{assistant executive manager director}.each do |type|
# JobLevel.create(:name => type)
# JobLevel.create(name: type)
# end
# end
#

View file

@ -50,14 +50,14 @@ module ActiveRecord
# 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 @@ module ActiveRecord
#
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
#
# 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 @@ module ActiveRecord
#
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
#
# 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 @@ module ActiveRecord
# <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 ActiveRecord
#
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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 file

@ -486,7 +486,7 @@ module ActiveRecord
# 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 file

@ -145,7 +145,7 @@ module ActiveRecord
# # 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 file

@ -78,7 +78,7 @@ module ActiveRecord
#
# 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 file

@ -36,10 +36,10 @@ module ActiveRecord
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 file

@ -357,17 +357,17 @@ module ActiveRecord
# 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
#
@ -379,7 +379,7 @@ module ActiveRecord
# 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
#
@ -478,13 +478,13 @@ module ActiveRecord
#
# 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 file

@ -15,11 +15,11 @@ module ActiveRecord
#
# ==== 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 file

@ -17,7 +17,7 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
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 @@ module ActiveRecord
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 file

@ -36,7 +36,7 @@ module ActiveRecord #:nodoc:
#
# 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 ActiveRecord #:nodoc:
#
# 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 ActiveRecord #:nodoc:
# 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 ActiveRecord #:nodoc:
#
# 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 ActiveRecord #:nodoc:
#
# 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 ActiveRecord #:nodoc:
# 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 ActiveRecord #:nodoc:
# 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 file

@ -108,10 +108,10 @@ module ActiveRecord
#
# # 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 @@ module ActiveRecord
# # 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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 @@ module ActiveRecord
# 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.