aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorAvnerCohen <israbirding@gmail.com>2012-10-12 00:28:47 +0200
committerAvnerCohen <israbirding@gmail.com>2012-10-12 00:28:47 +0200
commita2c843885470dddbad9430963190464a22167921 (patch)
tree497b707d686ab50b380728f2756435e9856390d4 /guides
parent61c64dc942a1a5fc142aab09f94f51bff0fee962 (diff)
downloadrails-a2c843885470dddbad9430963190464a22167921.tar.gz
rails-a2c843885470dddbad9430963190464a22167921.tar.bz2
rails-a2c843885470dddbad9430963190464a22167921.zip
1.9 hash syntax changes.
Diffstat (limited to 'guides')
-rw-r--r--guides/source/active_record_validations_callbacks.md186
-rw-r--r--guides/source/active_support_core_extensions.md226
-rw-r--r--guides/source/active_support_instrumentation.md108
-rw-r--r--guides/source/api_documentation_guidelines.md4
4 files changed, 262 insertions, 262 deletions
diff --git a/guides/source/active_record_validations_callbacks.md b/guides/source/active_record_validations_callbacks.md
index 333cbdd90b..b350b892bc 100644
--- a/guides/source/active_record_validations_callbacks.md
+++ b/guides/source/active_record_validations_callbacks.md
@@ -51,7 +51,7 @@ We can see how it works by looking at some `rails console` output:
```ruby
$ rails console
->> p = Person.new(:name => "John Doe")
+>> p = Person.new(name: "John Doe")
=> #<Person id: nil, name: "John Doe", created_at: nil, updated_at: nil>
>> p.new_record?
=> true
@@ -95,9 +95,9 @@ The following methods skip validations, and will save the object to the database
* `update_columns`
* `update_counters`
-Note that `save` also has the ability to skip validations if passed `:validate => false` as argument. This technique should be used with caution.
+Note that `save` also has the ability to skip validations if passed `validate: false` as argument. This technique should be used with caution.
-* `save(:validate => false)`
+* `save(validate: false)`
### `valid?` and `invalid?`
@@ -105,11 +105,11 @@ To verify whether or not an object is valid, Rails uses the `valid?` method. You
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true
+ validates :name, presence: true
end
-Person.create(:name => "John Doe").valid? # => true
-Person.create(:name => nil).valid? # => false
+Person.create(name: "John Doe").valid? # => true
+Person.create(name: nil).valid? # => false
```
After Active Record has performed validations, any errors found can be accessed through the `errors` instance method, which returns a collection of errors. By definition, an object is valid if this collection is empty after running validations.
@@ -118,7 +118,7 @@ Note that an object instantiated with `new` will not report errors even if it's
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true
+ validates :name, presence: true
end
>> p = Person.new
@@ -129,12 +129,12 @@ end
>> p.valid?
#=> false
>> p.errors
-#=> {:name=>["can't be blank"]}
+#=> {name:["can't be blank"]}
>> p = Person.create
#=> #<Person id: nil, name: nil>
>> p.errors
-#=> {:name=>["can't be blank"]}
+#=> {name:["can't be blank"]}
>> p.save
#=> false
@@ -156,7 +156,7 @@ This method is only useful _after_ validations have been run, because it only in
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true
+ validates :name, presence: true
end
>> Person.new.errors[:name].any? # => false
@@ -180,7 +180,7 @@ Validates that a checkbox on the user interface was checked when a form was subm
```ruby
class Person < ActiveRecord::Base
- validates :terms_of_service, :acceptance => true
+ validates :terms_of_service, acceptance: true
end
```
@@ -190,7 +190,7 @@ It can receive an `:accept` option, which determines the value that will be cons
```ruby
class Person < ActiveRecord::Base
- validates :terms_of_service, :acceptance => { :accept => 'yes' }
+ validates :terms_of_service, acceptance: { accept: 'yes' }
end
```
@@ -217,7 +217,7 @@ You should use this helper when you have two text fields that should receive exa
```ruby
class Person < ActiveRecord::Base
- validates :email, :confirmation => true
+ validates :email, confirmation: true
end
```
@@ -232,8 +232,8 @@ This check is performed only if `email_confirmation` is not `nil`. To require co
```ruby
class Person < ActiveRecord::Base
- validates :email, :confirmation => true
- validates :email_confirmation, :presence => true
+ validates :email, confirmation: true
+ validates :email_confirmation, presence: true
end
```
@@ -245,8 +245,8 @@ This helper validates that the attributes' values are not included in a given se
```ruby
class Account < ActiveRecord::Base
- validates :subdomain, :exclusion => { :in => %w(www us ca jp),
- :message => "Subdomain %{value} is reserved." }
+ validates :subdomain, exclusion: { in: %w(www us ca jp),
+ message: "Subdomain %{value} is reserved." }
end
```
@@ -260,8 +260,8 @@ This helper validates the attributes' values by testing whether they match a giv
```ruby
class Product < ActiveRecord::Base
- validates :legacy_code, :format => { :with => /\A[a-zA-Z]+\z/,
- :message => "Only letters allowed" }
+ validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/,
+ message: "Only letters allowed" }
end
```
@@ -273,8 +273,8 @@ This helper validates that the attributes' values are included in a given set. I
```ruby
class Coffee < ActiveRecord::Base
- validates :size, :inclusion => { :in => %w(small medium large),
- :message => "%{value} is not a valid size" }
+ validates :size, inclusion: { in: %w(small medium large),
+ message: "%{value} is not a valid size" }
end
```
@@ -288,10 +288,10 @@ This helper validates the length of the attributes' values. It provides a variet
```ruby
class Person < ActiveRecord::Base
- validates :name, :length => { :minimum => 2 }
- validates :bio, :length => { :maximum => 500 }
- validates :password, :length => { :in => 6..20 }
- validates :registration_number, :length => { :is => 6 }
+ validates :name, length: { minimum: 2 }
+ validates :bio, length: { maximum: 500 }
+ validates :password, length: { in: 6..20 }
+ validates :registration_number, length: { is: 6 }
end
```
@@ -306,8 +306,8 @@ The default error messages depend on the type of length validation being perform
```ruby
class Person < ActiveRecord::Base
- validates :bio, :length => { :maximum => 1000,
- :too_long => "%{count} characters is the maximum allowed" }
+ validates :bio, length: { maximum: 1000,
+ too_long: "%{count} characters is the maximum allowed" }
end
```
@@ -315,12 +315,12 @@ This helper counts characters by default, but you can split the value in a diffe
```ruby
class Essay < ActiveRecord::Base
- validates :content, :length => {
- :minimum => 300,
- :maximum => 400,
- :tokenizer => lambda { |str| str.scan(/\w+/) },
- :too_short => "must have at least %{count} words",
- :too_long => "must have at most %{count} words"
+ validates :content, length: {
+ minimum: 300,
+ maximum: 400,
+ tokenizer: lambda { |str| str.scan(/\w+/) },
+ too_short: "must have at least %{count} words",
+ too_long: "must have at most %{count} words"
}
end
```
@@ -345,8 +345,8 @@ WARNING. Note that the regular expression above allows a trailing newline charac
```ruby
class Player < ActiveRecord::Base
- validates :points, :numericality => true
- validates :games_played, :numericality => { :only_integer => true }
+ validates :points, numericality: true
+ validates :games_played, numericality: { only_integer: true }
end
```
@@ -368,7 +368,7 @@ This helper validates that the specified attributes are not empty. It uses the `
```ruby
class Person < ActiveRecord::Base
- validates :name, :login, :email, :presence => true
+ validates :name, :login, :email, presence: true
end
```
@@ -377,13 +377,13 @@ If you want to be sure that an association is present, you'll need to test wheth
```ruby
class LineItem < ActiveRecord::Base
belongs_to :order
- validates :order_id, :presence => true
+ validates :order_id, presence: true
end
```
If you validate the presence of an object associated via a `has_one` or `has_many` relationship, it will check that the object is neither `blank?` nor `marked_for_destruction?`.
-Since `false.blank?` is true, if you want to validate the presence of a boolean field you should use `validates :field_name, :inclusion => { :in => [true, false] }`.
+Since `false.blank?` is true, if you want to validate the presence of a boolean field you should use `validates :field_name, inclusion: { in: [true, false] }`.
The default error message is "_can't be empty_".
@@ -393,7 +393,7 @@ This helper validates that the attribute's value is unique right before the obje
```ruby
class Account < ActiveRecord::Base
- validates :email, :uniqueness => true
+ validates :email, uniqueness: true
end
```
@@ -403,8 +403,8 @@ There is a `:scope` option that you can use to specify other attributes that are
```ruby
class Holiday < ActiveRecord::Base
- validates :name, :uniqueness => { :scope => :year,
- :message => "should happen once per year" }
+ validates :name, uniqueness: { scope: :year,
+ message: "should happen once per year" }
end
```
@@ -412,7 +412,7 @@ There is also a `:case_sensitive` option that you can use to define whether the
```ruby
class Person < ActiveRecord::Base
- validates :name, :uniqueness => { :case_sensitive => false }
+ validates :name, uniqueness: { case_sensitive: false }
end
```
@@ -448,7 +448,7 @@ Like all other validations, `validates_with` takes the `:if`, `:unless` and `:on
```ruby
class Person < ActiveRecord::Base
- validates_with GoodnessValidator, :fields => [:first_name, :last_name]
+ validates_with GoodnessValidator, fields: [:first_name, :last_name]
end
class GoodnessValidator < ActiveModel::Validator
@@ -485,8 +485,8 @@ The `:allow_nil` option skips the validation when the value being validated is `
```ruby
class Coffee < ActiveRecord::Base
- validates :size, :inclusion => { :in => %w(small medium large),
- :message => "%{value} is not a valid size" }, :allow_nil => true
+ validates :size, inclusion: { in: %w(small medium large),
+ message: "%{value} is not a valid size" }, allow_nil: true
end
```
@@ -498,7 +498,7 @@ The `:allow_blank` option is similar to the `:allow_nil` option. This option wil
```ruby
class Topic < ActiveRecord::Base
- validates :title, :length => { :is => 5 }, :allow_blank => true
+ validates :title, length: { is: 5 }, allow_blank: true
end
Topic.create("title" => "").valid? # => true
@@ -513,18 +513,18 @@ As you've already seen, the `:message` option lets you specify the message that
### `:on`
-The `:on` option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use `:on => :create` to run the validation only when a new record is created or `:on => :update` to run the validation only when a record is updated.
+The `:on` option lets you specify when the validation should happen. The default behavior for all the built-in validation helpers is to be run on save (both when you're creating a new record and when you're updating it). If you want to change it, you can use `on: :create` to run the validation only when a new record is created or `on: :update` to run the validation only when a record is updated.
```ruby
class Person < ActiveRecord::Base
# it will be possible to update email with a duplicated value
- validates :email, :uniqueness => true, :on => :create
+ validates :email, uniqueness: true, on: :create
# it will be possible to create the record with a non-numerical age
- validates :age, :numericality => true, :on => :update
+ validates :age, numericality: true, on: :update
# the default (validates on both create and update)
- validates :name, :presence => true, :on => :save
+ validates :name, presence: true, on: :save
end
```
@@ -535,7 +535,7 @@ You can also specify validations to be strict and raise `ActiveModel::StrictVali
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => { :strict => true }
+ validates :name, presence: { strict: true }
end
Person.new.valid? #=> ActiveModel::StrictValidationFailed: Name can't be blank
@@ -545,7 +545,7 @@ There is also an ability to pass custom exception to `:strict` option
```ruby
class Person < ActiveRecord::Base
- validates :token, :presence => true, :uniqueness => true, :strict => TokenGenerationException
+ validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
Person.new.valid? #=> TokenGenerationException: Token can't be blank
@@ -562,7 +562,7 @@ You can associate the `:if` and `:unless` options with a symbol corresponding to
```ruby
class Order < ActiveRecord::Base
- validates :card_number, :presence => true, :if => :paid_with_card?
+ validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
@@ -576,7 +576,7 @@ You can also use a string that will be evaluated using `eval` and needs to conta
```ruby
class Person < ActiveRecord::Base
- validates :surname, :presence => true, :if => "name.nil?"
+ validates :surname, presence: true, if: "name.nil?"
end
```
@@ -586,8 +586,8 @@ Finally, it's possible to associate `:if` and `:unless` with a `Proc` object whi
```ruby
class Account < ActiveRecord::Base
- validates :password, :confirmation => true,
- :unless => Proc.new { |a| a.password.blank? }
+ validates :password, confirmation: true,
+ unless: Proc.new { |a| a.password.blank? }
end
```
@@ -597,14 +597,14 @@ Sometimes it is useful to have multiple validations use one condition, it can be
```ruby
class User < ActiveRecord::Base
- with_options :if => :is_admin? do |admin|
- admin.validates :password, :length => { :minimum => 10 }
- admin.validates :email, :presence => true
+ with_options if: :is_admin? do |admin|
+ admin.validates :password, length: { minimum: 10 }
+ admin.validates :email, presence: true
end
end
```
-All validations inside of `with_options` block will have automatically passed the condition `:if => :is_admin?`
+All validations inside of `with_options` block will have automatically passed the condition `if: :is_admin?`
### Combining validation conditions
@@ -612,9 +612,9 @@ On the other hand, when multiple conditions define whether or not a validation s
```ruby
class Computer < ActiveRecord::Base
- validates :mouse, :presence => true,
- :if => ["market.retail?", :desktop?]
- :unless => Proc.new { |c| c.trackpad.present? }
+ validates :mouse, presence: true,
+ if: ["market.retail?", :desktop?]
+ unless: Proc.new { |c| c.trackpad.present? }
end
```
@@ -656,7 +656,7 @@ class EmailValidator < ActiveModel::EachValidator
end
class Person < ActiveRecord::Base
- validates :email, :presence => true, :email => true
+ validates :email, presence: true, email: true
end
```
@@ -691,7 +691,7 @@ By default such validations will run every time you call `valid?`. It is also po
```ruby
class Invoice < ActiveRecord::Base
- validate :active_customer, :on => :create
+ validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
@@ -704,7 +704,7 @@ You can even create your own validation helpers and reuse them in several differ
```ruby
ActiveRecord::Base.class_eval do
def self.validates_as_choice(attr_name, n, options={})
- validates attr_name, :inclusion => { { :in => 1..n }.merge!(options) }
+ validates attr_name, inclusion: { { in: 1..n }.merge!(options) }
end
end
```
@@ -730,15 +730,15 @@ Returns an instance of the class `ActiveModel::Errors` containing all errors. Ea
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
+ validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
person.valid? # => false
person.errors
- # => {:name => ["can't be blank", "is too short (minimum is 3 characters)"]}
+ # => {name: ["can't be blank", "is too short (minimum is 3 characters)"]}
-person = Person.new(:name => "John Doe")
+person = Person.new(name: "John Doe")
person.valid? # => true
person.errors # => []
```
@@ -749,14 +749,14 @@ person.errors # => []
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
+ validates :name, presence: true, length: { minimum: 3 }
end
-person = Person.new(:name => "John Doe")
+person = Person.new(name: "John Doe")
person.valid? # => true
person.errors[:name] # => []
-person = Person.new(:name => "JD")
+person = Person.new(name: "JD")
person.valid? # => false
person.errors[:name] # => ["is too short (minimum is 3 characters)"]
@@ -777,7 +777,7 @@ class Person < ActiveRecord::Base
end
end
-person = Person.create(:name => "!@#")
+person = Person.create(name: "!@#")
person.errors[:name]
# => ["cannot contain the characters !@#%*()_-+="]
@@ -795,7 +795,7 @@ Another way to do this is using `[]=` setter
end
end
- person = Person.create(:name => "!@#")
+ person = Person.create(name: "!@#")
person.errors[:name]
# => ["cannot contain the characters !@#%*()_-+="]
@@ -822,7 +822,7 @@ The `clear` method is used when you intentionally want to clear all the messages
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
+ validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
@@ -845,14 +845,14 @@ The `size` method returns the total number of error messages for the object.
```ruby
class Person < ActiveRecord::Base
- validates :name, :presence => true, :length => { :minimum => 3 }
+ validates :name, presence: true, length: { minimum: 3 }
end
person = Person.new
person.valid? # => false
person.errors.size # => 2
-person = Person.new(:name => "Andrea", :email => "andrea@example.com")
+person = Person.new(name: "Andrea", email: "andrea@example.com")
person.valid? # => true
person.errors.size # => 0
```
@@ -876,8 +876,8 @@ When creating a form with the `form_for` helper, you can use the `error_messages
```ruby
class Product < ActiveRecord::Base
- validates :description, :value, :presence => true
- validates :value, :numericality => true, :allow_nil => true
+ validates :description, :value, presence: true
+ validates :value, numericality: true, allow_nil: true
end
```
@@ -915,9 +915,9 @@ The displayed text for each error message will always be formed by the capitaliz
Both the `form.error_messages` and the `error_messages_for` helpers accept options that let you customize the `div` element that holds the messages, change the header text, change the message below the header, and specify the tag used for the header element. For example,
```erb
-<%= f.error_messages :header_message => "Invalid product!",
- :message => "You'll need to fix the following fields:",
- :header_tag => :h3 %>
+<%= f.error_messages header_message: "Invalid product!",
+ message: "You'll need to fix the following fields:",
+ header_tag: :h3 %>
```
results in:
@@ -973,7 +973,7 @@ In order to use the available callbacks, you need to register them. You can impl
```ruby
class User < ActiveRecord::Base
- validates :login, :email, :presence => true
+ validates :login, :email, presence: true
before_validation :ensure_login_has_a_value
@@ -990,7 +990,7 @@ The macro-style class methods can also receive a block. Consider using this styl
```ruby
class User < ActiveRecord::Base
- validates :login, :email, :presence => true
+ validates :login, :email, presence: true
before_create do |user|
user.name = user.login.capitalize if user.name.blank?
@@ -1001,10 +1001,10 @@ end
Callbacks can also be registered to only fire on certain lifecycle events:
<ruby>
class User < ActiveRecord::Base
- before_validation :normalize_name, :on => :create
+ before_validation :normalize_name, on: :create
# :on takes an array as well
- after_validation :set_location, :on => [ :create, :update ]
+ after_validation :set_location, on: [ :create, :update ]
protected
def normalize_name
@@ -1096,7 +1096,7 @@ The following methods trigger callbacks:
* `increment!`
* `save`
* `save!`
-* `save(:validate => false)`
+* `save(validate: false)`
* `toggle!`
* `update`
* `update_attribute`
@@ -1151,7 +1151,7 @@ Callbacks work through model relationships, and can even be defined by them. Sup
```ruby
class User < ActiveRecord::Base
- has_many :posts, :dependent => :destroy
+ has_many :posts, dependent: :destroy
end
class Post < ActiveRecord::Base
@@ -1182,7 +1182,7 @@ You can associate the `:if` and `:unless` options with a symbol corresponding to
```ruby
class Order < ActiveRecord::Base
- before_save :normalize_card_number, :if => :paid_with_card?
+ before_save :normalize_card_number, if: :paid_with_card?
end
```
@@ -1192,7 +1192,7 @@ You can also use a string that will be evaluated using `eval` and hence needs to
```ruby
class Order < ActiveRecord::Base
- before_save :normalize_card_number, :if => "paid_with_card?"
+ before_save :normalize_card_number, if: "paid_with_card?"
end
```
@@ -1203,7 +1203,7 @@ Finally, it is possible to associate `:if` and `:unless` with a `Proc` object. T
```ruby
class Order < ActiveRecord::Base
before_save :normalize_card_number,
- :if => Proc.new { |order| order.paid_with_card? }
+ if: Proc.new { |order| order.paid_with_card? }
end
```
@@ -1213,8 +1213,8 @@ When writing conditional callbacks, it is possible to mix both `:if` and `:unles
```ruby
class Comment < ActiveRecord::Base
- after_create :send_email_to_author, :if => :author_wants_emails?,
- :unless => Proc.new { |comment| comment.post.ignore_comments? }
+ after_create :send_email_to_author, if: :author_wants_emails?,
+ unless: Proc.new { |comment| comment.post.ignore_comments? }
end
```
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 645498437d..193cc41d79 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -358,13 +358,13 @@ Arrays return the result of applying `to_query` to each element with `_key_[]` a
Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":
```ruby
-{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
+{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
```
The method `Hash#to_query` accepts an optional namespace for the keys:
```ruby
-{:id => 89, :name => "John Smith"}.to_query('user')
+{id: 89, name: "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
```
@@ -378,10 +378,10 @@ Given a default options hash, `with_options` yields a proxy object to a block. W
```ruby
class Account < ActiveRecord::Base
- has_many :customers, :dependent => :destroy
- has_many :products, :dependent => :destroy
- has_many :invoices, :dependent => :destroy
- has_many :expenses, :dependent => :destroy
+ has_many :customers, dependent: :destroy
+ has_many :products, dependent: :destroy
+ has_many :invoices, dependent: :destroy
+ has_many :expenses, dependent: :destroy
end
```
@@ -389,7 +389,7 @@ this way:
```ruby
class Account < ActiveRecord::Base
- with_options :dependent => :destroy do |assoc|
+ with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
@@ -401,9 +401,9 @@ end
That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
```ruby
-I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
+I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
subject i18n.t :subject
- body i18n.t :body, :user_name => user.name
+ body i18n.t :body, user_name: user.name
end
```
@@ -892,7 +892,7 @@ That is what `delegate` does for you:
class User < ActiveRecord::Base
has_one :profile
- delegate :name, :to => :profile
+ delegate :name, to: :profile
end
```
@@ -903,17 +903,17 @@ The method must be public in the target.
The `delegate` macro accepts several methods:
```ruby
-delegate :name, :age, :address, :twitter, :to => :profile
+delegate :name, :age, :address, :twitter, to: :profile
```
When interpolated into a string, the `:to` option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:
```ruby
# delegates to the Rails constant
-delegate :logger, :to => :Rails
+delegate :logger, to: :Rails
# delegates to the receiver's class
-delegate :table_name, :to => 'self.class'
+delegate :table_name, to: 'self.class'
```
WARNING: If the `:prefix` option is `true` this is less generic, see below.
@@ -921,7 +921,7 @@ WARNING: If the `:prefix` option is `true` this is less generic, see below.
By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:
```ruby
-delegate :name, :to => :profile, :allow_nil => true
+delegate :name, to: :profile, allow_nil: true
```
With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
@@ -929,7 +929,7 @@ With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:
```ruby
-delegate :street, :to => :address, :prefix => true
+delegate :street, to: :address, prefix: true
```
The previous example generates `address_street` rather than `street`.
@@ -939,7 +939,7 @@ WARNING: Since in this case the name of the generated method is composed of the
A custom prefix may also be configured:
```ruby
-delegate :size, :to => :attachment, :prefix => :avatar
+delegate :size, to: :attachment, prefix: :avatar
```
In the previous example the macro generates `avatar_size` rather than `size`.
@@ -1003,10 +1003,10 @@ For example `ActionMailer::Base` defines:
```ruby
class_attribute :default_params
self.default_params = {
- :mime_version => "1.0",
- :charset => "UTF-8",
- :content_type => "text/plain",
- :parts_order => [ "text/plain", "text/enriched", "text/html" ]
+ mime_version: "1.0",
+ charset: "UTF-8",
+ content_type: "text/plain",
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
}.freeze
```
@@ -1028,7 +1028,7 @@ The generation of the writer instance method can be prevented by setting the opt
```ruby
module ActiveRecord
class Base
- class_attribute :table_name_prefix, :instance_writer => false
+ class_attribute :table_name_prefix, instance_writer: false
self.table_name_prefix = ""
end
end
@@ -1040,7 +1040,7 @@ The generation of the reader instance method can be prevented by setting the opt
```ruby
class A
- class_attribute :x, :instance_reader => false
+ class_attribute :x, instance_reader: false
end
A.new.x = 1 # NoMethodError
@@ -1083,11 +1083,11 @@ The generation of the reader instance method can be prevented by setting `:insta
module A
class B
# No first_name instance reader is generated.
- cattr_accessor :first_name, :instance_reader => false
+ cattr_accessor :first_name, instance_reader: false
# No last_name= instance writer is generated.
- cattr_accessor :last_name, :instance_writer => false
+ cattr_accessor :last_name, instance_writer: false
# No surname instance reader or surname= writer is generated.
- cattr_accessor :surname, :instance_accessor => false
+ cattr_accessor :surname, instance_accessor: false
end
end
```
@@ -1260,7 +1260,7 @@ The method `truncate` returns a copy of its receiver truncated after a given `le
Ellipsis can be customized with the `:omission` option:
```ruby
-"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
+"Oh dear! Oh dear! I shall be late!".truncate(20, omission: '&hellip;')
# => "Oh dear! Oh &hellip;"
```
@@ -1271,14 +1271,14 @@ Pass a `:separator` to truncate the string at a natural break:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..."
-"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
# => "Oh dear! Oh..."
```
The option `:separator` can be a regexp:
```ruby
-"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => /\s/)
+"Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
# => "Oh dear! Oh..."
```
@@ -1757,7 +1757,7 @@ def full_messages
each do |attribute, messages|
...
attr_name = attribute.to_s.gsub('.', '_').humanize
- attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
+ attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
...
end
@@ -1861,13 +1861,13 @@ These methods use Time#advance for precise date calculations when using from_now
as well as adding or subtracting their results from a Time object. For example:
```ruby
-# equivalent to Time.current.advance(:months => 1)
+# equivalent to Time.current.advance(months: 1)
1.month.from_now
-# equivalent to Time.current.advance(:years => 2)
+# equivalent to Time.current.advance(years: 2)
2.years.from_now
-# equivalent to Time.current.advance(:months => 4, :years => 5)
+# equivalent to Time.current.advance(months: 4, years: 5)
(4.months + 5.years).from_now
```
@@ -1900,13 +1900,13 @@ Produce a string representation of a number as a telephone number:
# => 555-1234
1235551234.to_s(:phone)
# => 123-555-1234
-1235551234.to_s(:phone, :area_code => true)
+1235551234.to_s(:phone, area_code: true)
# => (123) 555-1234
-1235551234.to_s(:phone, :delimiter => " ")
+1235551234.to_s(:phone, delimiter: " ")
# => 123 555 1234
-1235551234.to_s(:phone, :area_code => true, :extension => 555)
+1235551234.to_s(:phone, area_code: true, extension: 555)
# => (123) 555-1234 x 555
-1235551234.to_s(:phone, :country_code => 1)
+1235551234.to_s(:phone, country_code: 1)
# => +1-123-555-1234
```
@@ -1915,7 +1915,7 @@ Produce a string representation of a number as currency:
```ruby
1234567890.50.to_s(:currency) # => $1,234,567,890.50
1234567890.506.to_s(:currency) # => $1,234,567,890.51
-1234567890.506.to_s(:currency, :precision => 3) # => $1,234,567,890.506
+1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
```
Produce a string representation of a number as a percentage:
@@ -1923,11 +1923,11 @@ Produce a string representation of a number as a percentage:
```ruby
100.to_s(:percentage)
# => 100.000%
-100.to_s(:percentage, :precision => 0)
+100.to_s(:percentage, precision: 0)
# => 100%
-1000.to_s(:percentage, :delimiter => '.', :separator => ',')
+1000.to_s(:percentage, delimiter: '.', separator: ',')
# => 1.000,000%
-302.24398923423.to_s(:percentage, :precision => 5)
+302.24398923423.to_s(:percentage, precision: 5)
# => 302.24399%
```
@@ -1936,19 +1936,19 @@ Produce a string representation of a number in delimited form:
```ruby
12345678.to_s(:delimited) # => 12,345,678
12345678.05.to_s(:delimited) # => 12,345,678.05
-12345678.to_s(:delimited, :delimiter => ".") # => 12.345.678
-12345678.to_s(:delimited, :delimiter => ",") # => 12,345,678
-12345678.05.to_s(:delimited, :separator => " ") # => 12,345,678 05
+12345678.to_s(:delimited, delimiter: ".") # => 12.345.678
+12345678.to_s(:delimited, delimiter: ",") # => 12,345,678
+12345678.05.to_s(:delimited, separator: " ") # => 12,345,678 05
```
Produce a string representation of a number rounded to a precision:
```ruby
111.2345.to_s(:rounded) # => 111.235
-111.2345.to_s(:rounded, :precision => 2) # => 111.23
-13.to_s(:rounded, :precision => 5) # => 13.00000
-389.32314.to_s(:rounded, :precision => 0) # => 389
-111.2345.to_s(:rounded, :significant => true) # => 111
+111.2345.to_s(:rounded, precision: 2) # => 111.23
+13.to_s(:rounded, precision: 5) # => 13.00000
+389.32314.to_s(:rounded, precision: 0) # => 389
+111.2345.to_s(:rounded, significant: true) # => 111
```
Produce a string representation of a number as a human-readable number of bytes:
@@ -2042,7 +2042,7 @@ Addition only assumes the elements respond to `+`:
```ruby
[[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
%w(foo bar baz).sum # => "foobarbaz"
-{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
+{a: 1, b: 2, c: 3}.sum # => [:b, 2, :c, 3, :a, 1]
```
The sum of an empty collection is zero by default, but this is customizable:
@@ -2176,7 +2176,7 @@ NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets:
```ruby
-User.exists?(:email => params[:email])
+User.exists?(email: params[:email])
```
That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.
@@ -2305,7 +2305,7 @@ If there's any element that does not belong to the type of the first one the roo
If the receiver is an array of hashes the root element is by default also "objects":
```ruby
-[{:a => 1, :b => 2}, {:c => 3}].to_xml
+[{a: 1, b: 2}, {c: 3}].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <objects type="array">
@@ -2326,7 +2326,7 @@ The name of children nodes is by default the name of the root node singularized.
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
```ruby
-Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
+Contributor.limit(2).order(:rank).to_xml(skip_types: true)
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors>
@@ -2372,8 +2372,8 @@ This method is similar in purpose to `Kernel#Array`, but there are some differen
The last point is particularly worth comparing for some enumerables:
```ruby
-Array.wrap(:foo => :bar) # => [{:foo => :bar}]
-Array(:foo => :bar) # => [[:foo, :bar]]
+Array.wrap(foo: :bar) # => [{foo: :bar}]
+Array(foo: :bar) # => [[:foo, :bar]]
```
There's also a related idiom that uses the splat operator:
@@ -2556,8 +2556,8 @@ NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
Ruby has a built-in method `Hash#merge` that merges two hashes:
```ruby
-{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
-# => {:a => 0, :b => 1, :c => 2}
+{a: 1, b: 1}.merge(a: 0, c: 2)
+# => {a: 0, b: 1, c: 2}
```
Active Support defines a few more ways of merging hashes that may be convenient.
@@ -2567,19 +2567,19 @@ Active Support defines a few more ways of merging hashes that may be convenient.
In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:
```ruby
-options = {:length => 30, :omission => "..."}.merge(options)
+options = {length: 30, omission: "..."}.merge(options)
```
Active Support defines `reverse_merge` in case you prefer this alternative notation:
```ruby
-options = options.reverse_merge(:length => 30, :omission => "...")
+options = options.reverse_merge(length: 30, omission: "...")
```
And a bang version `reverse_merge!` that performs the merge in place:
```ruby
-options.reverse_merge!(:length => 30, :omission => "...")
+options.reverse_merge!(length: 30, omission: "...")
```
WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
@@ -2601,8 +2601,8 @@ As you can see in the previous example if a key is found in both hashes the valu
Active Support defines `Hash#deep_merge`. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:
```ruby
-{:a => {:b => 1}}.deep_merge(:a => {:c => 2})
-# => {:a => {:b => 1, :c => 2}}
+{a: {b: 1}}.deep_merge(a: {c: 2})
+# => {a: {b: 1, c: 2}}
```
The method `deep_merge!` performs a deep merge in place.
@@ -2614,7 +2614,7 @@ NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
The method `Hash.deep_dup` duplicates itself and all keys and values inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.
```ruby
-hash = { :a => 1, :b => { :c => 2, :d => [3, 4] } }
+hash = { a: 1, b: { c: 2, d: [3, 4] } }
dup = hash.deep_dup
dup[:b][:e] = 5
@@ -2637,21 +2637,21 @@ The method `diff` returns a hash that represents a diff of the receiver and the
* The rest is just merged.
```ruby
-{:a => 1}.diff(:a => 1)
+{a: 1}.diff(a: 1)
# => {}, first rule
-{:a => 1}.diff(:a => 2)
-# => {:a => 1}, second rule
+{a: 1}.diff(a: 2)
+# => {a: 1}, second rule
-{:a => 1}.diff(:b => 2)
-# => {:a => 1, :b => 2}, third rule
+{a: 1}.diff(b: 2)
+# => {a: 1, b: 2}, third rule
-{:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4)
-# => {:a => 1, :b => 2, :d => 4}, all rules
+{a: 1, b: 2, c: 3}.diff(b: 1, c: 3, d: 4)
+# => {a: 1, b: 2, d: 4}, all rules
{}.diff({}) # => {}
-{:a => 1}.diff({}) # => {:a => 1}
-{}.diff(:a => 1) # => {:a => 1}
+{a: 1}.diff({}) # => {a: 1}
+{}.diff(a: 1) # => {a: 1}
```
An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice:
@@ -2671,14 +2671,14 @@ NOTE: Defined in `active_support/core_ext/hash/diff.rb`.
The method `except` returns a hash with the keys in the argument list removed, if present:
```ruby
-{:a => 1, :b => 2}.except(:a) # => {:b => 2}
+{a: 1, b: 2}.except(:a) # => {b: 2}
```
If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
```ruby
-{:a => 1}.with_indifferent_access.except(:a) # => {}
-{:a => 1}.with_indifferent_access.except("a") # => {}
+{a: 1}.with_indifferent_access.except(:a) # => {}
+{a: 1}.with_indifferent_access.except("a") # => {}
```
The method `except` may come in handy for example when you want to protect some parameter that can't be globally protected with `attr_protected`:
@@ -2697,14 +2697,14 @@ NOTE: Defined in `active_support/core_ext/hash/except.rb`.
The method `transform_keys` accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
```ruby
-{nil => nil, 1 => 1, :a => :a}.transform_keys{ |key| key.to_s.upcase }
+{nil => nil, 1 => 1, a: :a}.transform_keys{ |key| key.to_s.upcase }
# => {"" => nil, "A" => :a, "1" => 1}
```
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.transform_keys{ |key| key.to_s.upcase }
+{"a" => 1, a: 2}.transform_keys{ |key| key.to_s.upcase }
# => {"A" => 2}, in my test, can't rely on this result though
```
@@ -2725,7 +2725,7 @@ There's also the bang variant `transform_keys!` that applies the block operation
Besides that, one can use `deep_transform_keys` and `deep_transform_keys!` to perform the block operation on all the keys in the given hash and all the hashes nested into it. An example of the result is:
```ruby
-{nil => nil, 1 => 1, :nested => {:a => 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
# => {""=>nil, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
```
@@ -2736,14 +2736,14 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
The method `stringify_keys` returns a hash that has a stringified version of the keys in the receiver. It does so by sending `to_s` to them:
```ruby
-{nil => nil, 1 => 1, :a => :a}.stringify_keys
+{nil => nil, 1 => 1, a: :a}.stringify_keys
# => {"" => nil, "a" => :a, "1" => 1}
```
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.stringify_keys
+{"a" => 1, a: 2}.stringify_keys
# => {"a" => 2}, in my test, can't rely on this result though
```
@@ -2764,7 +2764,7 @@ There's also the bang variant `stringify_keys!` that stringifies keys in the ver
Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to stringify all the keys in the given hash and all the hashes nested into it. An example of the result is:
```ruby
-{nil => nil, 1 => 1, :nested => {:a => 3, 5 => 5}}.deep_stringify_keys
+{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys
# => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
```
@@ -2776,7 +2776,7 @@ The method `symbolize_keys` returns a hash that has a symbolized version of the
```ruby
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
-# => {1 => 1, nil => nil, :a => "a"}
+# => {1 => 1, nil => nil, a: "a"}
```
WARNING. Note in the previous example only one key was symbolized.
@@ -2784,8 +2784,8 @@ WARNING. Note in the previous example only one key was symbolized.
The result in case of collision is undefined:
```ruby
-{"a" => 1, :a => 2}.symbolize_keys
-# => {:a => 2}, in my test, can't rely on this result though
+{"a" => 1, a: 2}.symbolize_keys
+# => {a: 2}, in my test, can't rely on this result though
```
This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
@@ -2806,7 +2806,7 @@ Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to sy
```ruby
{nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys
-# => {nil=>nil, 1=>1, :nested=>{:a=>3, 5=>5}}
+# => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
```
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
@@ -2822,8 +2822,8 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does `ArgumentError` is raised.
```ruby
-{:a => 1}.assert_valid_keys(:a) # passes
-{:a => 1}.assert_valid_keys("a") # ArgumentError
+{a: 1}.assert_valid_keys(:a) # passes
+{a: 1}.assert_valid_keys("a") # ArgumentError
```
Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
@@ -2835,18 +2835,18 @@ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
```ruby
-{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
-# => {:c => 3, :a => 1}
+{a: 1, b: 2, c: 3}.slice(:a, :c)
+# => {c: 3, a: 1}
-{:a => 1, :b => 2, :c => 3}.slice(:b, :X)
-# => {:b => 2} # non-existing keys are ignored
+{a: 1, b: 2, c: 3}.slice(:b, :X)
+# => {b: 2} # non-existing keys are ignored
```
If the receiver responds to `convert_key` keys are normalized:
```ruby
-{:a => 1, :b => 2}.with_indifferent_access.slice("a")
-# => {:a => 1}
+{a: 1, b: 2}.with_indifferent_access.slice("a")
+# => {a: 1}
```
NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
@@ -2854,9 +2854,9 @@ NOTE. Slicing may come in handy for sanitizing option hashes with a white list o
There's also `slice!` which in addition to perform a slice in place returns what's removed:
```ruby
-hash = {:a => 1, :b => 2}
-rest = hash.slice!(:a) # => {:b => 2}
-hash # => {:a => 1}
+hash = {a: 1, b: 2}
+rest = hash.slice!(:a) # => {b: 2}
+hash # => {a: 1}
```
NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
@@ -2866,9 +2866,9 @@ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
The method `extract!` removes and returns the key/value pairs matching the given keys.
```ruby
-hash = {:a => 1, :b => 2}
-rest = hash.extract!(:a) # => {:a => 1}
-hash # => {:b => 2}
+hash = {a: 1, b: 2}
+rest = hash.extract!(:a) # => {a: 1}
+hash # => {b: 2}
```
NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
@@ -2878,7 +2878,7 @@ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
```ruby
-{:a => 1}.with_indifferent_access["a"] # => 1
+{a: 1}.with_indifferent_access["a"] # => 1
```
NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
@@ -2982,7 +2982,7 @@ An unbound method is not callable as is, you need to bind it first to an object
```ruby
clear = Hash.instance_method(:clear)
-clear.bind({:a => 1}).call # => {}
+clear.bind({a: 1}).call # => {}
```
Active Support defines `Proc#bind` with an analogous purpose:
@@ -3241,8 +3241,8 @@ The most generic way to jump to other days is `advance`. This method receives a
```ruby
date = Date.new(2010, 6, 6)
-date.advance(:years => 1, :weeks => 2) # => Mon, 20 Jun 2011
-date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010
+date.advance(years: 1, weeks: 2) # => Mon, 20 Jun 2011
+date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
```
Note in the previous example that increments may be negative.
@@ -3252,14 +3252,14 @@ To perform the computation the method first increments years, then months, then
The method `advance` advances first one month, and then one day, the result is:
```ruby
-Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
+Date.new(2010, 2, 28).advance(months: 1, days: 1)
# => Sun, 29 Mar 2010
```
While if it did it the other way around the result would be different:
```ruby
-Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
+Date.new(2010, 2, 28).advance(days: 1).advance(months: 1)
# => Thu, 01 Apr 2010
```
@@ -3268,14 +3268,14 @@ Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
The method `change` allows you to get a new date which is the same as the receiver except for the given year, month, or day:
```ruby
-Date.new(2010, 12, 23).change(:year => 2011, :month => 11)
+Date.new(2010, 12, 23).change(year: 2011, month: 11)
# => Wed, 23 Nov 2011
```
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
```ruby
-Date.new(2010, 1, 31).change(:month => 2)
+Date.new(2010, 1, 31).change(month: 2)
# => ArgumentError: invalid date
```
@@ -3461,7 +3461,7 @@ The most generic way to jump to another datetime is `advance`. This method recei
```ruby
d = DateTime.current
# => Thu, 05 Aug 2010 11:33:31 +0000
-d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
+d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
# => Tue, 06 Sep 2011 12:34:32 +0000
```
@@ -3472,14 +3472,14 @@ If we first move the date bits (that have also a relative order of processing, a
```ruby
d = DateTime.new(2010, 2, 28, 23, 59, 59)
# => Sun, 28 Feb 2010 23:59:59 +0000
-d.advance(:months => 1, :seconds => 1)
+d.advance(months: 1, seconds: 1)
# => Mon, 29 Mar 2010 00:00:00 +0000
```
but if we computed them the other way around, the result would be different:
```ruby
-d.advance(:seconds => 1).advance(:months => 1)
+d.advance(seconds: 1).advance(months: 1)
# => Thu, 01 Apr 2010 00:00:00 +0000
```
@@ -3492,28 +3492,28 @@ The method `change` allows you to get a new datetime which is the same as the re
```ruby
now = DateTime.current
# => Tue, 08 Jun 2010 01:56:22 +0000
-now.change(:year => 2011, :offset => Rational(-6, 24))
+now.change(year: 2011, offset: Rational(-6, 24))
# => Wed, 08 Jun 2011 01:56:22 -0600
```
If hours are zeroed, then minutes and seconds are too (unless they have given values):
```ruby
-now.change(:hour => 0)
+now.change(hour: 0)
# => Tue, 08 Jun 2010 00:00:00 +0000
```
Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):
```ruby
-now.change(:min => 0)
+now.change(min: 0)
# => Tue, 08 Jun 2010 01:00:00 +0000
```
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
```ruby
-DateTime.current.change(:month => 2, :day => 30)
+DateTime.current.change(month: 2, day: 30)
# => ArgumentError: invalid date
```
@@ -3596,7 +3596,7 @@ Time.zone_default
# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
t = Time.local_time(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
-t.advance(:seconds => 1)
+t.advance(seconds: 1)
# => Sun Mar 28 03:00:00 +0200 2010
```
diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md
index 6c06cfcc4b..b35691bbcc 100644
--- a/guides/source/active_support_instrumentation.md
+++ b/guides/source/active_support_instrumentation.md
@@ -37,7 +37,7 @@ ActionController
```ruby
{
- :key => 'posts/1-dasboard-view'
+ key: 'posts/1-dasboard-view'
}
```
@@ -49,7 +49,7 @@ ActionController
```ruby
{
- :key => 'posts/1-dasboard-view'
+ key: 'posts/1-dasboard-view'
}
```
@@ -61,7 +61,7 @@ ActionController
```ruby
{
- :key => 'posts/1-dasboard-view'
+ key: 'posts/1-dasboard-view'
}
```
@@ -73,7 +73,7 @@ ActionController
```ruby
{
- :key => 'posts/1-dasboard-view'
+ key: 'posts/1-dasboard-view'
}
```
@@ -85,7 +85,7 @@ ActionController
```ruby
{
- :path => '/users/1'
+ path: '/users/1'
}
```
@@ -97,7 +97,7 @@ ActionController
```ruby
{
- :path => '/users/1'
+ path: '/users/1'
}
```
@@ -114,12 +114,12 @@ ActionController
```ruby
{
- :controller => "PostsController",
- :action => "new",
- :params => { "action" => "new", "controller" => "posts" },
- :format => :html,
- :method => "GET",
- :path => "/posts/new"
+ controller: "PostsController",
+ action: "new",
+ params: { "action" => "new", "controller" => "posts" },
+ format: :html,
+ method: "GET",
+ path: "/posts/new"
}
```
@@ -137,15 +137,15 @@ ActionController
```ruby
{
- :controller => "PostsController",
- :action => "index",
- :params => {"action" => "index", "controller" => "posts"},
- :format => :html,
- :method => "GET",
- :path => "/posts",
- :status => 200,
- :view_runtime => 46.848,
- :db_runtime => 0.157
+ controller: "PostsController",
+ action: "index",
+ params: {"action" => "index", "controller" => "posts"},
+ format: :html,
+ method: "GET",
+ path: "/posts",
+ status: 200,
+ view_runtime: 46.848,
+ db_runtime: 0.157
}
```
@@ -170,8 +170,8 @@ INFO. Additional keys may be added by the caller.
```ruby
{
- :status => 302,
- :location => "http://localhost:3000/posts/new"
+ status: 302,
+ location: "http://localhost:3000/posts/new"
}
```
@@ -183,7 +183,7 @@ INFO. Additional keys may be added by the caller.
```ruby
{
- :filter => ":halting_filter"
+ filter: ":halting_filter"
}
```
@@ -199,8 +199,8 @@ ActionView
```ruby
{
- :identifier => "/Users/adam/projects/notifications/app/views/posts/index.html.erb",
- :layout => "layouts/application"
+ identifier: "/Users/adam/projects/notifications/app/views/posts/index.html.erb",
+ layout: "layouts/application"
}
```
@@ -212,7 +212,7 @@ ActionView
```ruby
{
- :identifier => "/Users/adam/projects/notifications/app/views/posts/_form.html.erb",
+ identifier: "/Users/adam/projects/notifications/app/views/posts/_form.html.erb",
}
```
@@ -231,10 +231,10 @@ INFO. The adapters will add their own data as well.
```ruby
{
- :sql => "SELECT \"posts\".* FROM \"posts\" ",
- :name => "Post Load",
- :connection_id => 70307250813140,
- :binds => []
+ sql: "SELECT \"posts\".* FROM \"posts\" ",
+ name: "Post Load",
+ connection_id: 70307250813140,
+ binds: []
}
```
@@ -265,13 +265,13 @@ ActionMailer
```ruby
{
- :mailer => "Notification",
- :message_id => "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
- :subject => "Rails Guides",
- :to => ["users@rails.com", "ddh@rails.com"],
- :from => ["me@rails.com"],
- :date => Sat, 10 Mar 2012 14:18:09 +0100,
- :mail=> "..." # ommitted for beverity
+ mailer: "Notification",
+ message_id: "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
+ subject: "Rails Guides",
+ to: ["users@rails.com", "ddh@rails.com"],
+ from: ["me@rails.com"],
+ date: Sat, 10 Mar 2012 14:18:09 +0100,
+ mail: "..." # ommitted for beverity
}
```
@@ -291,13 +291,13 @@ ActionMailer
```ruby
{
- :mailer => "Notification",
- :message_id => "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
- :subject => "Rails Guides",
- :to => ["users@rails.com", "ddh@rails.com"],
- :from => ["me@rails.com"],
- :date => Sat, 10 Mar 2012 14:18:09 +0100,
- :mail=> "..." # ommitted for beverity
+ mailer: "Notification",
+ message_id: "4f5b5491f1774_181b23fc3d4434d38138e5@mba.local.mail",
+ subject: "Rails Guides",
+ to: ["users@rails.com", "ddh@rails.com"],
+ from: ["me@rails.com"],
+ date: Sat, 10 Mar 2012 14:18:09 +0100,
+ mail: "..." # ommitted for beverity
}
```
@@ -335,7 +335,7 @@ INFO. Options passed to fetch will be merged with the payload when writing to th
```ruby
{
- :key => 'name-of-complicated-computation'
+ key: 'name-of-complicated-computation'
}
```
@@ -352,7 +352,7 @@ INFO. Options passed to fetch will be merged with the payload.
```ruby
{
- :key => 'name-of-complicated-computation'
+ key: 'name-of-complicated-computation'
}
```
@@ -366,7 +366,7 @@ INFO. Cache stores my add their own keys
```ruby
{
- :key => 'name-of-complicated-computation'
+ key: 'name-of-complicated-computation'
}
```
@@ -378,7 +378,7 @@ INFO. Cache stores my add their own keys
```ruby
{
- :key => 'name-of-complicated-computation'
+ key: 'name-of-complicated-computation'
}
```
@@ -390,7 +390,7 @@ INFO. Cache stores my add their own keys
```ruby
{
- :key => 'name-of-complicated-computation'
+ key: 'name-of-complicated-computation'
}
```
@@ -434,7 +434,7 @@ ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*a
event.name # => "process_action.action_controller"
event.duration # => 10 (in milliseconds)
- event.payload # => { :extra => :information }
+ event.payload # => { extra: :information }
Rails.logger.info "#{event} Received!"
end
@@ -445,7 +445,7 @@ Most times you only care about the data itself. Here is a shortuct to just get t
```ruby
ActiveSupport::Notifications.subscribe "process_action.action_controller" do |*args|
data = args.extract_options!
- data # { :extra => :information }
+ data # { extra: :information }
```
You may also subscribe to events matching a regular expresssion. This enables you to subscribe to
@@ -468,7 +468,7 @@ as well as the unique ID. All data passed into the `insturment` call will make i
Here's an example:
```ruby
-ActiveSupport::Notifications.instrument "my.custom.event", :this => :data do
+ActiveSupport::Notifications.instrument "my.custom.event", this: :data do
# do your custom stuff here
end
```
@@ -477,7 +477,7 @@ Now you can listen to this event with:
```ruby
ActiveSupport::Notifications.subscribe "my.custom.event" do |name, started, finished, unique_id, data|
- puts data.inspect # { :this => :data }
+ puts data.inspect # { this: :data }
end
```
diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md
index dcfa7eb6fb..48b4ddb102 100644
--- a/guides/source/api_documentation_guidelines.md
+++ b/guides/source/api_documentation_guidelines.md
@@ -64,7 +64,7 @@ On the other hand, big chunks of structured documentation may have a separate "E
#
# Person.exists?(5)
# Person.exists?('5')
-# Person.exists?(:name => "David")
+# Person.exists?(name: "David")
# Person.exists?(['name LIKE ?', "%#{query}%"])
```
@@ -88,7 +88,7 @@ If a line is too long, the comment may be placed on the next line:
# label(:post, :title, "A short title")
# # => <label for="post_title">A short title</label>
#
-# label(:post, :title, "A short title", :class => "title_label")
+# label(:post, :title, "A short title", class: "title_label")
# # => <label for="post_title" class="title_label">A short title</label>
```