aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_support_core_extensions.md
diff options
context:
space:
mode:
authorPrem Sichanugrist <s@sikachu.com>2012-09-01 21:37:59 -0400
committerPrem Sichanugrist <s@sikac.hu>2012-09-17 15:54:23 -0400
commit31ef4cf656785a190723d2d8fb4c0fd06f4009bc (patch)
tree582a93b9441b41c1150ae421a2a878194af6475e /guides/source/active_support_core_extensions.md
parented62b1bf0b6fff53524c168f9615af84dea99537 (diff)
downloadrails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.tar.gz
rails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.tar.bz2
rails-31ef4cf656785a190723d2d8fb4c0fd06f4009bc.zip
Convert all inline codes to Markdown syntax
Diffstat (limited to 'guides/source/active_support_core_extensions.md')
-rw-r--r--guides/source/active_support_core_extensions.md1168
1 files changed, 584 insertions, 584 deletions
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index 06edaa29f2..226ff67ff7 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -22,15 +22,15 @@ Thus, after a simple require like:
require 'active_support'
```
-objects do not even respond to +blank?+. Let's see how to load its definition.
+objects do not even respond to `blank?`. Let's see how to load its definition.
#### Cherry-picking a Definition
-The most lightweight way to get +blank?+ is to cherry-pick the file that defines it.
+The most lightweight way to get `blank?` is to cherry-pick the file that defines it.
-For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of +blank?+ the note reads:
+For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `blank?` the note reads:
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
That means that this single call is enough:
@@ -42,9 +42,9 @@ Active Support has been carefully revised so that cherry-picking a file loads on
#### Loading Grouped Core Extensions
-The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+.
+The next level is to simply load all extensions to `Object`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
-Thus, to load all extensions to +Object+ (including +blank?+):
+Thus, to load all extensions to `Object` (including `blank?`):
```ruby
require 'active_support/core_ext/object'
@@ -66,32 +66,32 @@ And finally, if you want to have all Active Support available just issue:
require 'active_support/all'
```
-That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via +autoload+, so it is only loaded if used.
+That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via `autoload`, so it is only loaded if used.
### Active Support Within a Ruby on Rails Application
-A Ruby on Rails application loads all Active Support unless +config.active_support.bare+ is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.
+A Ruby on Rails application loads all Active Support unless `config.active_support.bare` is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.
Extensions to All Objects
-------------------------
-### +blank?+ and +present?+
+### `blank?` and `present?`
The following values are considered to be blank in a Rails application:
-* +nil+ and +false+,
+* `nil` and `false`,
* strings composed only of whitespace (see note below),
* empty arrays and hashes, and
-* any other object that responds to +empty?+ and it is empty.
+* any other object that responds to `empty?` and it is empty.
INFO: The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.
WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
-For example, this method from +ActionDispatch::Session::AbstractStore+ uses +blank?+ for checking whether a session key is present:
+For example, this method from `ActionDispatch::Session::AbstractStore` uses `blank?` for checking whether a session key is present:
```ruby
def ensure_session_key!
@@ -101,7 +101,7 @@ def ensure_session_key!
end
```
-The method +present?+ is equivalent to +!blank?+. This example is taken from +ActionDispatch::Http::Cache::Response+:
+The method `present?` is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`:
```ruby
def set_conditional_cache_control!
@@ -110,19 +110,19 @@ def set_conditional_cache_control!
end
```
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
-### +presence+
+### `presence`
-The +presence+ method returns its receiver if +present?+, and +nil+ otherwise. It is useful for idioms like this:
+The `presence` method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this:
```ruby
host = config[:host].presence || 'localhost'
```
-NOTE: Defined in +active_support/core_ext/object/blank.rb+.
+NOTE: Defined in `active_support/core_ext/object/blank.rb`.
-### +duplicable?+
+### `duplicable?`
A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:
@@ -131,7 +131,7 @@ A few fundamental objects in Ruby are singletons. For example, in the whole life
Math.cos(0).to_i.object_id # => 3
```
-Hence, there's no way these objects can be duplicated through +dup+ or +clone+:
+Hence, there's no way these objects can be duplicated through `dup` or `clone`:
```ruby
true.dup # => TypeError: can't dup TrueClass
@@ -144,22 +144,22 @@ Some numbers which are not singletons are not duplicable either:
(2**1024).clone # => allocator undefined for Bignum
```
-Active Support provides +duplicable?+ to programmatically query an object about this property:
+Active Support provides `duplicable?` to programmatically query an object about this property:
```ruby
"".duplicable? # => true
false.duplicable? # => false
```
-By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class and module objects.
+By definition all objects are `duplicable?` except `nil`, `false`, `true`, symbols, numbers, and class and module objects.
-WARNING. Any class can disallow duplication removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell whether a given arbitrary object is duplicable. +duplicable?+ depends on the hard-coded list above, but it is much faster than +rescue+. Use it only if you know the hard-coded list is enough in your use case.
+WARNING. Any class can disallow duplication removing `dup` and `clone` or raising exceptions from them, only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case.
-NOTE: Defined in +active_support/core_ext/object/duplicable.rb+.
+NOTE: Defined in `active_support/core_ext/object/duplicable.rb`.
-### +deep_dup+
+### `deep_dup`
-The +deep_dup+ method returns deep copy of a given object. Normally, when you +dup+ an object that contains other objects, ruby does not +dup+ them. If you have an array with a string, for example, it will look like this:
+The `deep_dup` method returns deep copy of a given object. Normally, when you `dup` an object that contains other objects, ruby does not `dup` them. If you have an array with a string, for example, it will look like this:
```ruby
array = ['string']
@@ -178,9 +178,9 @@ array #=> ['foo']
duplicate #=> ['foo', 'another-string']
```
-As you can see, after duplicating +Array+ instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since +dup+ does not make deep copy, the string inside array is still the same object.
+As you can see, after duplicating `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make deep copy, the string inside array is still the same object.
-If you need a deep copy of an object, you should use +deep_dup+. Here is an example:
+If you need a deep copy of an object, you should use `deep_dup`. Here is an example:
```ruby
array = ['string']
@@ -192,7 +192,7 @@ array #=> ['string']
duplicate #=> ['foo']
```
-If object is not duplicable, +deep_dup+ will just return this object:
+If object is not duplicable, `deep_dup` will just return this object:
```ruby
number = 1
@@ -200,11 +200,11 @@ dup = number.deep_dup
number.object_id == dup.object_id # => true
```
-NOTE: Defined in +active_support/core_ext/object/deep_dup.rb+.
+NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
-### +try+
+### `try`
-When you want to call a method on an object only if it is not +nil+, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use +try+. +try+ is like +Object#send+ except that it returns +nil+ if sent to +nil+.
+When you want to call a method on an object only if it is not `nil`, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use `try`. `try` is like `Object#send` except that it returns `nil` if sent to `nil`.
Here is an example:
@@ -218,7 +218,7 @@ end
@number.try(:next)
```
-Another example is this code from +ActiveRecord::ConnectionAdapters::AbstractAdapter+ where +@logger+ could be +nil+. You can see that the code uses +try+ and avoids an unnecessary check.
+Another example is this code from `ActiveRecord::ConnectionAdapters::AbstractAdapter` where `@logger` could be `nil`. You can see that the code uses `try` and avoids an unnecessary check.
```ruby
def log_info(sql, name, ms)
@@ -229,17 +229,17 @@ def log_info(sql, name, ms)
end
```
-+try+ can also be called without arguments but a block, which will only be executed if the object is not nil:
+`try` can also be called without arguments but a block, which will only be executed if the object is not nil:
```ruby
@person.try { |p| "#{p.first_name} #{p.last_name}" }
```
-NOTE: Defined in +active_support/core_ext/object/try.rb+.
+NOTE: Defined in `active_support/core_ext/object/try.rb`.
-### +class_eval(*args, &block)+
+### `class_eval(*args, &block)`
-You can evaluate code in the context of any object's singleton class using +class_eval+:
+You can evaluate code in the context of any object's singleton class using `class_eval`:
```ruby
class Proc
@@ -256,11 +256,11 @@ class Proc
end
```
-NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
+NOTE: Defined in `active_support/core_ext/kernel/singleton_class.rb`.
-### +acts_like?(duck)+
+### `acts_like?(duck)`
-The method +acts_like?+ provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as +String+ defines
+The method `acts_like?` provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as `String` defines
```ruby
def acts_like_string?
@@ -273,21 +273,21 @@ which is only a marker, its body or return value are irrelevant. Then, client co
some_klass.acts_like?(:string)
```
-Rails has classes that act like +Date+ or +Time+ and follow this contract.
+Rails has classes that act like `Date` or `Time` and follow this contract.
-NOTE: Defined in +active_support/core_ext/object/acts_like.rb+.
+NOTE: Defined in `active_support/core_ext/object/acts_like.rb`.
-### +to_param+
+### `to_param`
-All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as URL fragments.
+All objects in Rails respond to the method `to_param`, which is meant to return something that represents them as values in a query string, or as URL fragments.
-By default +to_param+ just calls +to_s+:
+By default `to_param` just calls `to_s`:
```ruby
7.to_param # => "7"
```
-The return value of +to_param+ should *not* be escaped:
+The return value of `to_param` should *not* be escaped:
```ruby
"Tom & Jerry".to_param # => "Tom & Jerry"
@@ -295,13 +295,13 @@ The return value of +to_param+ should *not* be escaped:
Several classes in Rails overwrite this method.
-For example +nil+, +true+, and +false+ return themselves. +Array#to_param+ calls +to_param+ on the elements and joins the result with "/":
+For example `nil`, `true`, and `false` return themselves. `Array#to_param` calls `to_param` on the elements and joins the result with "/":
```ruby
[0, true, String].to_param # => "0/true/String"
```
-Notably, the Rails routing system calls +to_param+ on models to get a value for the +:id+ placeholder. +ActiveRecord::Base#to_param+ returns the +id+ of a model, but you can redefine that method in your models. For example, given
+Notably, the Rails routing system calls `to_param` on models to get a value for the `:id` placeholder. `ActiveRecord::Base#to_param` returns the `id` of a model, but you can redefine that method in your models. For example, given
```ruby
class User
@@ -317,13 +317,13 @@ we get:
user_path(@user) # => "/users/357-john-smith"
```
-WARNING. Controllers need to be aware of any redefinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+.
+WARNING. Controllers need to be aware of any redefinition of `to_param` because when a request like that comes in "357-john-smith" is the value of `params[:id]`.
-NOTE: Defined in +active_support/core_ext/object/to_param.rb+.
+NOTE: Defined in `active_support/core_ext/object/to_param.rb`.
-### +to_query+
+### `to_query`
-Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given
+Except for hashes, given an unescaped `key` this method constructs the part of a query string that would map such key to what `to_param` returns. For example, given
```ruby
class User
@@ -348,33 +348,33 @@ account.to_query('company[name]')
so its output is ready to be used in a query string.
-Arrays return the result of applying +to_query+ to each element with `_key_[]` as key, and join the result with "&":
+Arrays return the result of applying `to_query` to each element with `_key_[]` as key, and join the result with "&":
```ruby
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
```
-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 "&":
+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"
```
-The method +Hash#to_query+ accepts an optional namespace for the keys:
+The method `Hash#to_query` accepts an optional namespace for the keys:
```ruby
{:id => 89, :name => "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
```
-NOTE: Defined in +active_support/core_ext/object/to_query.rb+.
+NOTE: Defined in `active_support/core_ext/object/to_query.rb`.
-### +with_options+
+### `with_options`
-The method +with_options+ provides a way to factor out common options in a series of method calls.
+The method `with_options` provides a way to factor out common options in a series of method calls.
-Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
+Given a default options hash, `with_options` yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
```ruby
class Account < ActiveRecord::Base
@@ -407,17 +407,17 @@ I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
end
```
-TIP: Since +with_options+ forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
+TIP: Since `with_options` forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
-NOTE: Defined in +active_support/core_ext/object/with_options.rb+.
+NOTE: Defined in `active_support/core_ext/object/with_options.rb`.
### Instance Variables
Active Support provides several methods to ease access to instance variables.
-#### +instance_variable_names+
+#### `instance_variable_names`
-Ruby 1.8 and 1.9 have a method called +instance_variables+ that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines +instance_variable_names+ as a portable way to obtain them as strings:
+Ruby 1.8 and 1.9 have a method called `instance_variables` that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines `instance_variable_names` as a portable way to obtain them as strings:
```ruby
class C
@@ -431,11 +431,11 @@ C.new(0, 1).instance_variable_names # => ["@y", "@x"]
WARNING: The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter.
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
+NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
-#### +instance_values+
+#### `instance_values`
-The method +instance_values+ returns a hash that maps instance variable names without "@" to their
+The method `instance_values` returns a hash that maps instance variable names without "@" to their
corresponding values. Keys are strings:
```ruby
@@ -448,17 +448,17 @@ end
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
```
-NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.
+NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
### Silencing Warnings, Streams, and Exceptions
-The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards:
+The methods `silence_warnings` and `enable_warnings` change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:
```ruby
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
```
-You can silence any stream while a block runs with +silence_stream+:
+You can silence any stream while a block runs with `silence_stream`:
```ruby
silence_stream(STDOUT) do
@@ -466,7 +466,7 @@ silence_stream(STDOUT) do
end
```
-The +quietly+ method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
+The `quietly` method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
```ruby
quietly { system 'bundle install' }
@@ -474,7 +474,7 @@ quietly { system 'bundle install' }
For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.
-Silencing exceptions is also possible with +suppress+. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is +kind_of?+ any of the arguments, +suppress+ captures it and returns silently. Otherwise the exception is reraised:
+Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is reraised:
```ruby
# If the user is locked the increment is lost, no big deal.
@@ -483,13 +483,13 @@ suppress(ActiveRecord::StaleObjectError) do
end
```
-NOTE: Defined in +active_support/core_ext/kernel/reporting.rb+.
+NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`.
-### +in?+
+### `in?`
-The predicate +in?+ tests if an object is included in another object or a list of objects. An +ArgumentError+ exception will be raised if a single argument is passed and it does not respond to +include?+.
+The predicate `in?` tests if an object is included in another object or a list of objects. An `ArgumentError` exception will be raised if a single argument is passed and it does not respond to `include?`.
-Examples of +in?+:
+Examples of `in?`:
```ruby
1.in?(1,2) # => true
@@ -499,16 +499,16 @@ Examples of +in?+:
1.in?(1) # => ArgumentError
```
-NOTE: Defined in +active_support/core_ext/object/inclusion.rb+.
+NOTE: Defined in `active_support/core_ext/object/inclusion.rb`.
-Extensions to +Module+
+Extensions to `Module`
----------------------
-### +alias_method_chain+
+### `alias_method_chain`
Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
-For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap +ActionController::TestCase#process+ this way in +test/test_helper.rb+:
+For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionController::TestCase#process` this way in `test/test_helper.rb`:
```ruby
ActionController::TestCase.class_eval do
@@ -523,9 +523,9 @@ ActionController::TestCase.class_eval do
end
```
-That's the method +get+, +post+, etc., delegate the work to.
+That's the method `get`, `post`, etc., delegate the work to.
-That technique has a risk, it could be the case that +:original_process+ was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
+That technique has a risk, it could be the case that `:original_process` was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
```ruby
ActionController::TestCase.class_eval do
@@ -538,7 +538,7 @@ ActionController::TestCase.class_eval do
end
```
-The method +alias_method_chain+ provides a shortcut for that pattern:
+The method `alias_method_chain` provides a shortcut for that pattern:
```ruby
ActionController::TestCase.class_eval do
@@ -550,13 +550,13 @@ ActionController::TestCase.class_eval do
end
```
-Rails uses +alias_method_chain+ all over the code base. For example validations are added to +ActiveRecord::Base#save+ by wrapping the method that way in a separate module specialized in validations.
+Rails uses `alias_method_chain` all over the code base. For example validations are added to `ActiveRecord::Base#save` by wrapping the method that way in a separate module specialized in validations.
-NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.
+NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
### Attributes
-#### +alias_attribute+
+#### `alias_attribute`
Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
@@ -568,15 +568,15 @@ class User < ActiveRecord::Base
end
```
-NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.
+NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
#### Internal Attributes
When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.
-Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby built-in +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
+Active Support defines the macros `attr_internal_reader`, `attr_internal_writer`, and `attr_internal_accessor`. They behave like their Ruby built-in `attr_*` counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
-The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
+The macro `attr_internal` is a synonym for `attr_internal_accessor`:
```ruby
# library
@@ -590,9 +590,9 @@ class MyCrawler < ThirdPartyLibrary::Crawler
end
```
-In the previous example it could be the case that +:log_level+ does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own +:log_level+. Thanks to +attr_internal+ there's no collision.
+In the previous example it could be the case that `:log_level` does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own `:log_level`. Thanks to `attr_internal` there's no collision.
-By default the internal instance variable is named with a leading underscore, +@_log_level+ in the example above. That's configurable via +Module.attr_internal_naming_format+ though, you can pass any +sprintf+-like format string with a leading +@+ and a +%s+ somewhere, which is where the name will be placed. The default is +"@_%s"+.
+By default the internal instance variable is named with a leading underscore, `@_log_level` in the example above. That's configurable via `Module.attr_internal_naming_format` though, you can pass any `sprintf`-like format string with a leading `@` and a `%s` somewhere, which is where the name will be placed. The default is `"@_%s"`.
Rails uses internal attributes in a few spots, for examples for views:
@@ -606,11 +606,11 @@ module ActionView
end
```
-NOTE: Defined in +active_support/core_ext/module/attr_internal.rb+.
+NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`.
#### Module Attributes
-The macros +mattr_reader+, +mattr_writer+, and +mattr_accessor+ are analogous to the +cattr_*+ macros defined for class. Check "Class Attributes":#class-attributes.
+The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are analogous to the `cattr_*` macros defined for class. Check "Class Attributes":#class-attributes.
For example, the dependencies mechanism uses them:
@@ -633,13 +633,13 @@ module ActiveSupport
end
```
-NOTE: Defined in +active_support/core_ext/module/attribute_accessors.rb+.
+NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`.
### Parents
-#### +parent+
+#### `parent`
-The +parent+ method on a nested named module returns the module that contains its corresponding constant:
+The `parent` method on a nested named module returns the module that contains its corresponding constant:
```ruby
module X
@@ -654,15 +654,15 @@ X::Y::Z.parent # => X::Y
M.parent # => X::Y
```
-If the module is anonymous or belongs to the top-level, +parent+ returns +Object+.
+If the module is anonymous or belongs to the top-level, `parent` returns `Object`.
-WARNING: Note that in that case +parent_name+ returns +nil+.
+WARNING: Note that in that case `parent_name` returns `nil`.
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
-#### +parent_name+
+#### `parent_name`
-The +parent_name+ method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
+The `parent_name` method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
```ruby
module X
@@ -677,15 +677,15 @@ X::Y::Z.parent_name # => "X::Y"
M.parent_name # => "X::Y"
```
-For top-level or anonymous modules +parent_name+ returns +nil+.
+For top-level or anonymous modules `parent_name` returns `nil`.
-WARNING: Note that in that case +parent+ returns +Object+.
+WARNING: Note that in that case `parent` returns `Object`.
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
-#### +parents+
+#### `parents`
-The method +parents+ calls +parent+ on the receiver and upwards until +Object+ is reached. The chain is returned in an array, from bottom to top:
+The method `parents` calls `parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top:
```ruby
module X
@@ -700,11 +700,11 @@ X::Y::Z.parents # => [X::Y, X, Object]
M.parents # => [X::Y, X, Object]
```
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
### Constants
-The method +local_constants+ returns the names of the constants that have been
+The method `local_constants` returns the names of the constants that have been
defined in the receiver module:
```ruby
@@ -721,18 +721,18 @@ X.local_constants # => [:X1, :X2, :Y]
X::Y.local_constants # => [:Y1, :X1]
```
-The names are returned as symbols. (The deprecated method +local_constant_names+ returns strings.)
+The names are returned as symbols. (The deprecated method `local_constant_names` returns strings.)
-NOTE: Defined in +active_support/core_ext/module/introspection.rb+.
+NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
#### Qualified Constant Names
-The standard methods +const_defined?+, +const_get+ , and +const_set+ accept
+The standard methods `const_defined?`, `const_get` , and `const_set` accept
bare constant names. Active Support extends this API to be able to pass
relative qualified constant names.
-The new methods are +qualified_const_defined?+, +qualified_const_get+, and
-+qualified_const_set+. Their arguments are assumed to be qualified constant
+The new methods are `qualified_const_defined?`, `qualified_const_get`, and
+`qualified_const_set`. Their arguments are assumed to be qualified constant
names relative to their receiver:
```ruby
@@ -748,7 +748,7 @@ Math.qualified_const_get("E") # => 2.718281828459045
```
These methods are analogous to their builtin counterparts. In particular,
-+qualified_constant_defined?+ accepts an optional second argument to be
+`qualified_constant_defined?` accepts an optional second argument to be
able to say whether you want the predicate to look in the ancestors.
This flag is taken into account for each constant in the expression while
walking down the path.
@@ -767,7 +767,7 @@ module N
end
```
-+qualified_const_defined?+ behaves this way:
+`qualified_const_defined?` behaves this way:
```ruby
N.qualified_const_defined?("C::X", false) # => false
@@ -776,18 +776,18 @@ N.qualified_const_defined?("C::X") # => true
```
As the last example implies, the second argument defaults to true,
-as in +const_defined?+.
+as in `const_defined?`.
For coherence with the builtin methods only relative paths are accepted.
-Absolute qualified constant names like +::Math::PI+ raise +NameError+.
+Absolute qualified constant names like `::Math::PI` raise `NameError`.
-NOTE: Defined in +active_support/core_ext/module/qualified_const.rb+.
+NOTE: Defined in `active_support/core_ext/module/qualified_const.rb`.
### Reachable
A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
-That is what ordinarily happens, if a module is called "M", the +M+ constant exists and holds it:
+That is what ordinarily happens, if a module is called "M", the `M` constant exists and holds it:
```ruby
module M
@@ -819,7 +819,7 @@ end
orphan.reachable? # => false
```
-NOTE: Defined in +active_support/core_ext/module/reachable.rb+.
+NOTE: Defined in `active_support/core_ext/module/reachable.rb`.
### Anonymous
@@ -836,7 +836,7 @@ N.name # => "N"
Module.new.name # => nil
```
-You can check whether a module has a name with the predicate +anonymous?+:
+You can check whether a module has a name with the predicate `anonymous?`:
```ruby
module M
@@ -860,13 +860,13 @@ m.anonymous? # => false
though an anonymous module is unreachable by definition.
-NOTE: Defined in +active_support/core_ext/module/anonymous.rb+.
+NOTE: Defined in `active_support/core_ext/module/anonymous.rb`.
### Method Delegation
-The macro +delegate+ offers an easy way to forward methods.
+The macro `delegate` offers an easy way to forward methods.
-Let's imagine that users in some application have login information in the +User+ model but name and other data in a separate +Profile+ model:
+Let's imagine that users in some application have login information in the `User` model but name and other data in a separate `Profile` model:
```ruby
class User < ActiveRecord::Base
@@ -874,7 +874,7 @@ class User < ActiveRecord::Base
end
```
-With that configuration you get a user's name via his profile, +user.profile.name+, but it could be handy to still be able to access such attribute directly:
+With that configuration you get a user's name via his profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:
```ruby
class User < ActiveRecord::Base
@@ -886,7 +886,7 @@ class User < ActiveRecord::Base
end
```
-That is what +delegate+ does for you:
+That is what `delegate` does for you:
```ruby
class User < ActiveRecord::Base
@@ -900,13 +900,13 @@ It is shorter, and the intention more obvious.
The method must be public in the target.
-The +delegate+ macro accepts several methods:
+The `delegate` macro accepts several methods:
```ruby
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:
+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
@@ -916,25 +916,25 @@ delegate :logger, :to => :Rails
delegate :table_name, :to => 'self.class'
```
-WARNING: If the +:prefix+ option is +true+ this is less generic, see below.
+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:
+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
```
-With +:allow_nil+ the call +user.name+ returns +nil+ if the user has no profile.
+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:
+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
```
-The previous example generates +address_street+ rather than +street+.
+The previous example generates `address_street` rather than `street`.
-WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the +:to+ option must be a method name.
+WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the `:to` option must be a method name.
A custom prefix may also be configured:
@@ -942,15 +942,15 @@ A custom prefix may also be configured:
delegate :size, :to => :attachment, :prefix => :avatar
```
-In the previous example the macro generates +avatar_size+ rather than +size+.
+In the previous example the macro generates `avatar_size` rather than `size`.
-NOTE: Defined in +active_support/core_ext/module/delegation.rb+
+NOTE: Defined in `active_support/core_ext/module/delegation.rb`
### Redefining Methods
-There are cases where you need to define a method with +define_method+, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.
+There are cases where you need to define a method with `define_method`, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.
-The method +redefine_method+ prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API:
+The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API:
```ruby
redefine_method("#{reflection.name}=") do |new_value|
@@ -965,16 +965,16 @@ redefine_method("#{reflection.name}=") do |new_value|
end
```
-NOTE: Defined in +active_support/core_ext/module/remove_method.rb+
+NOTE: Defined in `active_support/core_ext/module/remove_method.rb`
-Extensions to +Class+
+Extensions to `Class`
---------------------
### Class Attributes
-#### +class_attribute+
+#### `class_attribute`
-The method +class_attribute+ declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
+The method `class_attribute` declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
```ruby
class A
@@ -998,7 +998,7 @@ A.x # => :a
B.x # => :b
```
-For example +ActionMailer::Base+ defines:
+For example `ActionMailer::Base` defines:
```ruby
class_attribute :default_params
@@ -1023,7 +1023,7 @@ a1.x # => 1, comes from A
a2.x # => 2, overridden in a2
```
-The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to +false+.
+The generation of the writer instance method can be prevented by setting the option `:instance_writer` to `false`.
```ruby
module ActiveRecord
@@ -1036,7 +1036,7 @@ end
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
-The generation of the reader instance method can be prevented by setting the option +:instance_reader+ to +false+.
+The generation of the reader instance method can be prevented by setting the option `:instance_reader` to `false`.
```ruby
class A
@@ -1046,15 +1046,15 @@ end
A.new.x = 1 # NoMethodError
```
-For convenience +class_attribute+ also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called +x?+.
+For convenience `class_attribute` also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called `x?`.
-When +:instance_reader+ is +false+, the instance predicate returns a +NoMethodError+ just like the reader method.
+When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.
-NOTE: Defined in +active_support/core_ext/class/attribute.rb+
+NOTE: Defined in `active_support/core_ext/class/attribute.rb`
-#### +cattr_reader+, +cattr_writer+, and +cattr_accessor+
+#### `cattr_reader`, `cattr_writer`, and `cattr_accessor`
-The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it:
+The macros `cattr_reader`, `cattr_writer`, and `cattr_accessor` are analogous to their `attr_*` counterparts but for classes. They initialize a class variable to `nil` unless it already exists, and generate the corresponding class methods to access it:
```ruby
class MysqlAdapter < AbstractAdapter
@@ -1064,7 +1064,7 @@ class MysqlAdapter < AbstractAdapter
end
```
-Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with +class_attribute+ (see above). For example given
+Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with `class_attribute` (see above). For example given
```ruby
module ActionView
@@ -1075,9 +1075,9 @@ module ActionView
end
```
-we can access +field_error_proc+ in views.
+we can access `field_error_proc` in views.
-The generation of the reader instance method can be prevented by setting +:instance_reader+ to +false+ and the generation of the writer instance method can be prevented by setting +:instance_writer+ to +false+. Generation of both methods can be prevented by setting +:instance_accessor+ to +false+. In all cases, the value must be exactly +false+ and not any false value.
+The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.
```ruby
module A
@@ -1092,15 +1092,15 @@ module A
end
```
-A model may find it useful to set +:instance_accessor+ to +false+ as a way to prevent mass-assignment from setting the attribute.
+A model may find it useful to set `:instance_accessor` to `false` as a way to prevent mass-assignment from setting the attribute.
-NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+.
+NOTE: Defined in `active_support/core_ext/class/attribute_accessors.rb`.
### Subclasses & Descendants
-#### +subclasses+
+#### `subclasses`
-The +subclasses+ method returns the subclasses of the receiver:
+The `subclasses` method returns the subclasses of the receiver:
```ruby
class C; end
@@ -1120,11 +1120,11 @@ The order in which these classes are returned is unspecified.
WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.
-NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
+NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
-#### +descendants+
+#### `descendants`
-The +descendants+ method returns all classes that are `&lt;` than its receiver:
+The `descendants` method returns all classes that are `&lt;` than its receiver:
```ruby
class C; end
@@ -1142,16 +1142,16 @@ C.descendants # => [B, A, D]
The order in which these classes are returned is unspecified.
-NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.
+NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
-Extensions to +String+
+Extensions to `String`
----------------------
### Output Safety
#### Motivation
-Inserting data into HTML templates needs extra care. For example, you can't just interpolate +@review.title+ verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks.
+Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks.
#### Safe Strings
@@ -1163,14 +1163,14 @@ Strings are considered to be <i>unsafe</i> by default:
"".html_safe? # => false
```
-You can obtain a safe string from a given one with the +html_safe+ method:
+You can obtain a safe string from a given one with the `html_safe` method:
```ruby
s = "".html_safe
s.html_safe? # => true
```
-It is important to understand that +html_safe+ performs no escaping whatsoever, it is just an assertion:
+It is important to understand that `html_safe` performs no escaping whatsoever, it is just an assertion:
```ruby
s = "<script>...</script>".html_safe
@@ -1178,9 +1178,9 @@ s.html_safe? # => true
s # => "<script>...</script>"
```
-It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
+It is your responsibility to ensure calling `html_safe` on a particular string is fine.
-If you append onto a safe string, either in-place with +concat+/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
+If you append onto a safe string, either in-place with `concat`/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
```ruby
"".html_safe + "<" # => "&lt;"
@@ -1198,7 +1198,7 @@ These methods should not be used in ordinary views. In Rails 3 unsafe values are
<%= @review.title %> <%# fine in Rails 3, escaped if needed %>
```
-To insert something verbatim use the +raw+ helper rather than calling +html_safe+:
+To insert something verbatim use the `raw` helper rather than calling `html_safe`:
```erb
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
@@ -1210,7 +1210,7 @@ or, equivalently, use `<%==`:
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
```
-The +raw+ helper calls +html_safe+ for you:
+The `raw` helper calls `html_safe` for you:
```ruby
def raw(stringish)
@@ -1218,46 +1218,46 @@ def raw(stringish)
end
```
-NOTE: Defined in +active_support/core_ext/string/output_safety.rb+.
+NOTE: Defined in `active_support/core_ext/string/output_safety.rb`.
#### Transformation
-As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are +downcase+, +gsub+, +strip+, +chomp+, +underscore+, etc.
+As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are `downcase`, `gsub`, `strip`, `chomp`, `underscore`, etc.
-In the case of in-place transformations like +gsub!+ the receiver itself becomes unsafe.
+In the case of in-place transformations like `gsub!` the receiver itself becomes unsafe.
INFO: The safety bit is lost always, no matter whether the transformation actually changed something.
#### Conversion and Coercion
-Calling +to_s+ on a safe string returns a safe string, but coercion with +to_str+ returns an unsafe string.
+Calling `to_s` on a safe string returns a safe string, but coercion with `to_str` returns an unsafe string.
#### Copying
-Calling +dup+ or +clone+ on safe strings yields safe strings.
+Calling `dup` or `clone` on safe strings yields safe strings.
-### +squish+
+### `squish`
-The method +squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
+The method `squish` strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
```ruby
" \n foo\n\r \t bar \n".squish # => "foo bar"
```
-There's also the destructive version +String#squish!+.
+There's also the destructive version `String#squish!`.
-NOTE: Defined in +active_support/core_ext/string/filters.rb+.
+NOTE: Defined in `active_support/core_ext/string/filters.rb`.
-### +truncate+
+### `truncate`
-The method +truncate+ returns a copy of its receiver truncated after a given +length+:
+The method `truncate` returns a copy of its receiver truncated after a given `length`:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
```
-Ellipsis can be customized with the +:omission+ option:
+Ellipsis can be customized with the `:omission` option:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
@@ -1266,7 +1266,7 @@ Ellipsis can be customized with the +:omission+ option:
Note in particular that truncation takes into account the length of the omission string.
-Pass a +:separator+ to truncate the string at a natural break:
+Pass a `:separator` to truncate the string at a natural break:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(18)
@@ -1275,40 +1275,40 @@ Pass a +:separator+ to truncate the string at a natural break:
# => "Oh dear! Oh..."
```
-The option +:separator+ can be a regexp:
+The option `:separator` can be a regexp:
```ruby
"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => /\s/)
# => "Oh dear! Oh..."
```
-In above examples "dear" gets cut first, but then +:separator+ prevents it.
+In above examples "dear" gets cut first, but then `:separator` prevents it.
-NOTE: Defined in +active_support/core_ext/string/filters.rb+.
+NOTE: Defined in `active_support/core_ext/string/filters.rb`.
-### +inquiry+
+### `inquiry`
-The `inquiry` method converts a string into a +StringInquirer+ object making equality checks prettier.
+The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier.
```ruby
"production".inquiry.production? # => true
"active".inquiry.inactive? # => false
```
-### +starts_with?+ and +ends_with?+
+### `starts_with?` and `ends_with?`
-Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
+Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`:
```ruby
"foo".starts_with?("f") # => true
"foo".ends_with?("o") # => true
```
-NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+.
+NOTE: Defined in `active_support/core_ext/string/starts_ends_with.rb`.
-### +strip_heredoc+
+### `strip_heredoc`
-The method +strip_heredoc+ strips indentation in heredocs.
+The method `strip_heredoc` strips indentation in heredocs.
For example in
@@ -1329,9 +1329,9 @@ the user would see the usage message aligned against the left margin.
Technically, it looks for the least indented line in the whole string, and removes
that amount of leading whitespace.
-NOTE: Defined in +active_support/core_ext/string/strip.rb+.
+NOTE: Defined in `active_support/core_ext/string/strip.rb`.
-### +indent+
+### `indent`
Indents the lines in the receiver:
@@ -1347,7 +1347,7 @@ EOS
end
```
-The second argument, +indent_string+, specifies which indent string to use. The default is +nil+, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
+The second argument, `indent_string`, specifies which indent string to use. The default is `nil`, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
```ruby
" foo".indent(2) # => " foo"
@@ -1355,22 +1355,22 @@ The second argument, +indent_string+, specifies which indent string to use. The
"foo".indent(2, "\t") # => "\t\tfoo"
```
-While +indent_string+ is tipically one space or tab, it may be any string.
+While `indent_string` is tipically one space or tab, it may be any string.
-The third argument, +indent_empty_lines+, is a flag that says whether empty lines should be indented. Default is false.
+The third argument, `indent_empty_lines`, is a flag that says whether empty lines should be indented. Default is false.
```ruby
"foo\n\nbar".indent(2) # => " foo\n\n bar"
"foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
```
-The +indent!+ method performs indentation in-place.
+The `indent!` method performs indentation in-place.
### Access
-#### +at(position)+
+#### `at(position)`
-Returns the character of the string at position +position+:
+Returns the character of the string at position `position`:
```ruby
"hello".at(0) # => "h"
@@ -1379,11 +1379,11 @@ Returns the character of the string at position +position+:
"hello".at(10) # => nil
```
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
-#### +from(position)+
+#### `from(position)`
-Returns the substring of the string starting at position +position+:
+Returns the substring of the string starting at position `position`:
```ruby
"hello".from(0) # => "hello"
@@ -1392,11 +1392,11 @@ Returns the substring of the string starting at position +position+:
"hello".from(10) # => "" if < 1.9, nil in 1.9
```
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
-#### +to(position)+
+#### `to(position)`
-Returns the substring of the string up to position +position+:
+Returns the substring of the string up to position `position`:
```ruby
"hello".to(0) # => "h"
@@ -1405,25 +1405,25 @@ Returns the substring of the string up to position +position+:
"hello".to(10) # => "hello"
```
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
-#### +first(limit = 1)+
+#### `first(limit = 1)`
-The call +str.first(n)+ is equivalent to +str.to(n-1)+ if +n+ > 0, and returns an empty string for +n+ == 0.
+The call `str.first(n)` is equivalent to `str.to(n-1)` if `n` > 0, and returns an empty string for `n` == 0.
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
-#### +last(limit = 1)+
+#### `last(limit = 1)`
-The call +str.last(n)+ is equivalent to +str.from(-n)+ if +n+ > 0, and returns an empty string for +n+ == 0.
+The call `str.last(n)` is equivalent to `str.from(-n)` if `n` > 0, and returns an empty string for `n` == 0.
-NOTE: Defined in +active_support/core_ext/string/access.rb+.
+NOTE: Defined in `active_support/core_ext/string/access.rb`.
### Inflections
-#### +pluralize+
+#### `pluralize`
-The method +pluralize+ returns the plural of its receiver:
+The method `pluralize` returns the plural of its receiver:
```ruby
"table".pluralize # => "tables"
@@ -1431,9 +1431,9 @@ The method +pluralize+ returns the plural of its receiver:
"equipment".pluralize # => "equipment"
```
-As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments.
+As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in `config/initializers/inflections.rb`. That file is generated by the `rails` command and has instructions in comments.
-+pluralize+ can also take an optional +count+ parameter. If `count == 1` the singular form will be returned. For any other value of +count+ the plural form will be returned:
+`pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:
```ruby
"dude".pluralize(0) # => "dudes"
@@ -1452,11 +1452,11 @@ def undecorated_table_name(class_name = base_class.name)
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +singularize+
+#### `singularize`
-The inverse of +pluralize+:
+The inverse of `pluralize`:
```ruby
"tables".singularize # => "table"
@@ -1475,11 +1475,11 @@ def derive_class_name
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +camelize+
+#### `camelize`
-The method +camelize+ returns its receiver in camel case:
+The method `camelize` returns its receiver in camel case:
```ruby
"product".camelize # => "Product"
@@ -1503,7 +1503,7 @@ def session_store=(store)
end
```
-+camelize+ accepts an optional argument, it can be +:upper+ (default), or +:lower+. With the latter the first letter becomes lowercase:
+`camelize` accepts an optional argument, it can be `:upper` (default), or `:lower`. With the latter the first letter becomes lowercase:
```ruby
"visual_effect".camelize(:lower) # => "visualEffect"
@@ -1511,7 +1511,7 @@ end
That may be handy to compute method names in a language that follows that convention, for example JavaScript.
-INFO: As a rule of thumb you can think of +camelize+ as the inverse of +underscore+, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in +config/initializers/inflections.rb+:
+INFO: As a rule of thumb you can think of `camelize` as the inverse of `underscore`, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in `config/initializers/inflections.rb`:
```ruby
ActiveSupport::Inflector.inflections do |inflect|
@@ -1521,13 +1521,13 @@ end
"SSLError".underscore.camelize #=> "SSLError"
```
-+camelize+ is aliased to +camelcase+.
+`camelize` is aliased to `camelcase`.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +underscore+
+#### `underscore`
-The method +underscore+ goes the other way around, from camel case to paths:
+The method `underscore` goes the other way around, from camel case to paths:
```ruby
"Product".underscore # => "product"
@@ -1546,9 +1546,9 @@ and understands strings that start with lowercase:
"visualEffect".underscore # => "visual_effect"
```
-+underscore+ accepts no argument though.
+`underscore` accepts no argument though.
-Rails class and module autoloading uses +underscore+ to infer the relative path without extension of a file that would define a given missing constant:
+Rails class and module autoloading uses `underscore` to infer the relative path without extension of a file that would define a given missing constant:
```ruby
# active_support/dependencies.rb
@@ -1560,26 +1560,26 @@ def load_missing_constant(from_mod, const_name)
end
```
-INFO: As a rule of thumb you can think of +underscore+ as the inverse of +camelize+, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
+INFO: As a rule of thumb you can think of `underscore` as the inverse of `camelize`, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +titleize+
+#### `titleize`
-The method +titleize+ capitalizes the words in the receiver:
+The method `titleize` capitalizes the words in the receiver:
```ruby
"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize # => "Fermat's Enigma"
```
-+titleize+ is aliased to +titlecase+.
+`titleize` is aliased to `titlecase`.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +dasherize+
+#### `dasherize`
-The method +dasherize+ replaces the underscores in the receiver with dashes:
+The method `dasherize` replaces the underscores in the receiver with dashes:
```ruby
"name".dasherize # => "name"
@@ -1596,11 +1596,11 @@ def reformat_name(name)
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +demodulize+
+#### `demodulize`
-Given a string with a qualified constant name, +demodulize+ returns the very constant name, that is, the rightmost part of it:
+Given a string with a qualified constant name, `demodulize` returns the very constant name, that is, the rightmost part of it:
```ruby
"Product".demodulize # => "Product"
@@ -1621,11 +1621,11 @@ def counter_cache_column
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +deconstantize+
+#### `deconstantize`
-Given a string with a qualified constant reference expression, +deconstantize+ removes the rightmost segment, generally leaving the name of the constant's container:
+Given a string with a qualified constant reference expression, `deconstantize` removes the rightmost segment, generally leaving the name of the constant's container:
```ruby
"Product".deconstantize # => ""
@@ -1633,7 +1633,7 @@ Given a string with a qualified constant reference expression, +deconstantize+ r
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
```
-Active Support for example uses this method in +Module#qualified_const_set+:
+Active Support for example uses this method in `Module#qualified_const_set`:
```ruby
def qualified_const_set(path, value)
@@ -1646,24 +1646,24 @@ def qualified_const_set(path, value)
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +parameterize+
+#### `parameterize`
-The method +parameterize+ normalizes its receiver in a way that can be used in pretty URLs.
+The method `parameterize` normalizes its receiver in a way that can be used in pretty URLs.
```ruby
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
```
-In fact, the result string is wrapped in an instance of +ActiveSupport::Multibyte::Chars+.
+In fact, the result string is wrapped in an instance of `ActiveSupport::Multibyte::Chars`.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +tableize+
+#### `tableize`
-The method +tableize+ is +underscore+ followed by +pluralize+.
+The method `tableize` is `underscore` followed by `pluralize`.
```ruby
"Person".tableize # => "people"
@@ -1671,13 +1671,13 @@ The method +tableize+ is +underscore+ followed by +pluralize+.
"InvoiceLine".tableize # => "invoice_lines"
```
-As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
+As a rule of thumb, `tableize` returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight `tableize` indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +classify+
+#### `classify`
-The method +classify+ is the inverse of +tableize+. It gives you the class name corresponding to a table name:
+The method `classify` is the inverse of `tableize`. It gives you the class name corresponding to a table name:
```ruby
"people".classify # => "Person"
@@ -1691,13 +1691,13 @@ The method understands qualified table names:
"highrise_production.companies".classify # => "Company"
```
-Note that +classify+ returns a class name as a string. You can get the actual class object invoking +constantize+ on it, explained next.
+Note that `classify` returns a class name as a string. You can get the actual class object invoking `constantize` on it, explained next.
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +constantize+
+#### `constantize`
-The method +constantize+ resolves the constant reference expression in its receiver:
+The method `constantize` resolves the constant reference expression in its receiver:
```ruby
"Fixnum".constantize # => Fixnum
@@ -1708,9 +1708,9 @@ end
"M::X".constantize # => 1
```
-If the string evaluates to no known constant, or its content is not even a valid constant name, +constantize+ raises +NameError+.
+If the string evaluates to no known constant, or its content is not even a valid constant name, `constantize` raises `NameError`.
-Constant name resolution by +constantize+ starts always at the top-level +Object+ even if there is no leading "::".
+Constant name resolution by `constantize` starts always at the top-level `Object` even if there is no leading "::".
```ruby
X = :in_Object
@@ -1725,7 +1725,7 @@ end
So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.
-Mailer test cases obtain the mailer being tested from the name of the test class using +constantize+:
+Mailer test cases obtain the mailer being tested from the name of the test class using `constantize`:
```ruby
# action_mailer/test_case.rb
@@ -1736,11 +1736,11 @@ rescue NameError => e
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +humanize+
+#### `humanize`
-The method +humanize+ gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word:
+The method `humanize` gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word:
```ruby
"name".humanize # => "Name"
@@ -1748,7 +1748,7 @@ The method +humanize+ gives you a sensible name for display out of an attribute
"comments_count".humanize # => "Comments count"
```
-The helper method +full_messages+ uses +humanize+ as a fallback to include attribute names:
+The helper method `full_messages` uses `humanize` as a fallback to include attribute names:
```ruby
def full_messages
@@ -1765,11 +1765,11 @@ def full_messages
end
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
-#### +foreign_key+
+#### `foreign_key`
-The method +foreign_key+ gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
+The method `foreign_key` gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
```ruby
"User".foreign_key # => "user_id"
@@ -1783,20 +1783,20 @@ Pass a false argument if you do not want the underscore in "_id":
"User".foreign_key(false) # => "userid"
```
-Associations use this method to infer foreign keys, for example +has_one+ and +has_many+ do this:
+Associations use this method to infer foreign keys, for example `has_one` and `has_many` do this:
```ruby
# active_record/associations.rb
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
```
-NOTE: Defined in +active_support/core_ext/string/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
### Conversions
-#### +to_date+, +to_time+, +to_datetime+
+#### `to_date`, `to_time`, `to_datetime`
-The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wrappers around +Date._parse+:
+The methods `to_date`, `to_time`, and `to_datetime` are basically convenience wrappers around `Date._parse`:
```ruby
"2010-07-27".to_date # => Tue, 27 Jul 2010
@@ -1804,22 +1804,22 @@ The methods +to_date+, +to_time+, and +to_datetime+ are basically convenience wr
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
```
-+to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in:
+`to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:
```ruby
"2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
```
-Default is +:utc+.
+Default is `:utc`.
-Please refer to the documentation of +Date._parse+ for further details.
+Please refer to the documentation of `Date._parse` for further details.
-INFO: The three of them return +nil+ for blank receivers.
+INFO: The three of them return `nil` for blank receivers.
-NOTE: Defined in +active_support/core_ext/string/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/string/conversions.rb`.
-Extensions to +Numeric+
+Extensions to `Numeric`
-----------------------
### Bytes
@@ -1851,7 +1851,7 @@ Singular forms are aliased so you are able to say:
1.megabyte # => 1048576
```
-NOTE: Defined in +active_support/core_ext/numeric/bytes.rb+.
+NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`.
### Time
@@ -1888,7 +1888,7 @@ Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and
Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision
date and time arithmetic.
-NOTE: Defined in +active_support/core_ext/numeric/time.rb+.
+NOTE: Defined in `active_support/core_ext/numeric/time.rb`.
### Formatting
@@ -1975,25 +1975,25 @@ Produce a string representation of a number in human-readable words:
1234567890123456.to_s(:human) # => "1.23 Quadrillion"
```
-NOTE: Defined in +active_support/core_ext/numeric/formatting.rb+.
+NOTE: Defined in `active_support/core_ext/numeric/formatting.rb`.
-Extensions to +Integer+
+Extensions to `Integer`
-----------------------
-### +multiple_of?+
+### `multiple_of?`
-The method +multiple_of?+ tests whether an integer is multiple of the argument:
+The method `multiple_of?` tests whether an integer is multiple of the argument:
```ruby
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false
```
-NOTE: Defined in +active_support/core_ext/integer/multiple.rb+.
+NOTE: Defined in `active_support/core_ext/integer/multiple.rb`.
-### +ordinal+
+### `ordinal`
-The method +ordinal+ returns the ordinal suffix string corresponding to the receiver integer:
+The method `ordinal` returns the ordinal suffix string corresponding to the receiver integer:
```ruby
1.ordinal # => "st"
@@ -2004,11 +2004,11 @@ The method +ordinal+ returns the ordinal suffix string corresponding to the rece
-134.ordinal # => "th"
```
-NOTE: Defined in +active_support/core_ext/integer/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
-### +ordinalize+
+### `ordinalize`
-The method +ordinalize+ returns the ordinal string corresponding to the receiver integer. In comparison, note that the +ordinal+ method returns *only* the suffix string.
+The method `ordinalize` returns the ordinal string corresponding to the receiver integer. In comparison, note that the `ordinal` method returns *only* the suffix string.
```ruby
1.ordinalize # => "1st"
@@ -2019,19 +2019,19 @@ The method +ordinalize+ returns the ordinal string corresponding to the receiver
-134.ordinalize # => "-134th"
```
-NOTE: Defined in +active_support/core_ext/integer/inflections.rb+.
+NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
-Extensions to +BigDecimal+
+Extensions to `BigDecimal`
--------------------------
...
-Extensions to +Enumerable+
+Extensions to `Enumerable`
--------------------------
-### +sum+
+### `sum`
-The method +sum+ adds the elements of an enumerable:
+The method `sum` adds the elements of an enumerable:
```ruby
[1, 2, 3].sum # => 6
@@ -2053,7 +2053,7 @@ The sum of an empty collection is zero by default, but this is customizable:
[].sum(1) # => 1
```
-If a block is given, +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
+If a block is given, `sum` becomes an iterator that yields the elements of the collection and sums the returned values:
```ruby
(1..5).sum {|n| n * 2 } # => 30
@@ -2066,7 +2066,7 @@ The sum of an empty receiver can be customized in this form as well:
[].sum(1) {|n| n**3} # => 1
```
-The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:
+The method `ActiveRecord::Observer#observed_subclasses` for example is implemented this way:
```ruby
def observed_subclasses
@@ -2074,11 +2074,11 @@ def observed_subclasses
end
```
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
-### +index_by+
+### `index_by`
-The method +index_by+ generates a hash with the elements of an enumerable indexed by some key.
+The method `index_by` generates a hash with the elements of an enumerable indexed by some key.
It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:
@@ -2089,11 +2089,11 @@ invoices.index_by(&:number)
WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
-### +many?+
+### `many?`
-The method +many?+ is shorthand for +collection.size > 1+:
+The method `many?` is shorthand for `collection.size > 1`:
```erb
<% if pages.many? %>
@@ -2101,37 +2101,37 @@ The method +many?+ is shorthand for +collection.size > 1+:
<% end %>
```
-If an optional block is given, +many?+ only takes into account those elements that return true:
+If an optional block is given, `many?` only takes into account those elements that return true:
```ruby
@see_more = videos.many? {|video| video.category == params[:category]}
```
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
-### +exclude?+
+### `exclude?`
-The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the built-in +include?+:
+The predicate `exclude?` tests whether a given object does *not* belong to the collection. It is the negation of the built-in `include?`:
```ruby
to_visit << node if visited.exclude?(node)
```
-NOTE: Defined in +active_support/core_ext/enumerable.rb+.
+NOTE: Defined in `active_support/core_ext/enumerable.rb`.
-Extensions to +Array+
+Extensions to `Array`
---------------------
### Accessing
-Active Support augments the API of arrays to ease certain ways of accessing them. For example, +to+ returns the subarray of elements up to the one at the passed index:
+Active Support augments the API of arrays to ease certain ways of accessing them. For example, `to` returns the subarray of elements up to the one at the passed index:
```ruby
%w(a b c d).to(2) # => %w(a b c)
[].to(7) # => []
```
-Similarly, +from+ returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.
+Similarly, `from` returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.
```ruby
%w(a b c d).from(2) # => %w(c d)
@@ -2139,18 +2139,18 @@ Similarly, +from+ returns the tail from the element at the passed index to the e
[].from(0) # => []
```
-The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is built-in). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available.
+The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element (`first` is built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
```ruby
%w(a b c d).third # => c
%w(a b c d).fifth # => nil
```
-NOTE: Defined in +active_support/core_ext/array/access.rb+.
+NOTE: Defined in `active_support/core_ext/array/access.rb`.
### Adding Elements
-#### +prepend+
+#### `prepend`
This method is an alias of `Array#unshift`.
@@ -2159,9 +2159,9 @@ This method is an alias of `Array#unshift`.
[].prepend(10) # => [10]
```
-NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
+NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
-#### +append+
+#### `append`
This method is an alias of `Array#<<`.
@@ -2170,11 +2170,11 @@ This method is an alias of `Array#<<`.
[].append([1,2]) # => [[1,2]]
```
-NOTE: Defined in +active_support/core_ext/array/prepend_and_append.rb+.
+NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
### Options Extraction
-When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets:
+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])
@@ -2184,9 +2184,9 @@ That syntactic sugar is used a lot in Rails to avoid positional arguments where
If a method expects a variable number of arguments and uses `*` in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
-In those cases, you may give an options hash a distinguished treatment with +extract_options!+. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.
+In those cases, you may give an options hash a distinguished treatment with `extract_options!`. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.
-Let's see for example the definition of the +caches_action+ controller macro:
+Let's see for example the definition of the `caches_action` controller macro:
```ruby
def caches_action(*actions)
@@ -2196,15 +2196,15 @@ def caches_action(*actions)
end
```
-This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to +extract_options!+ you obtain the options hash and remove it from +actions+ in a simple and explicit way.
+This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to `extract_options!` you obtain the options hash and remove it from `actions` in a simple and explicit way.
-NOTE: Defined in +active_support/core_ext/array/extract_options.rb+.
+NOTE: Defined in `active_support/core_ext/array/extract_options.rb`.
### Conversions
-#### +to_sentence+
+#### `to_sentence`
-The method +to_sentence+ turns an array into a string containing a sentence that enumerates its items:
+The method `to_sentence` turns an array into a string containing a sentence that enumerates its items:
```ruby
%w().to_sentence # => ""
@@ -2228,13 +2228,13 @@ The defaults for these options can be localised, their keys are:
Options `:connector` and `:skip_last_comma` are deprecated.
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
-#### +to_formatted_s+
+#### `to_formatted_s`
-The method +to_formatted_s+ acts like +to_s+ by default.
+The method `to_formatted_s` acts like `to_s` by default.
-If the array contains items that respond to +id+, however, it may be passed the symbol `:db` as argument. That's typically used with collections of ARs. Returned strings are:
+If the array contains items that respond to `id`, however, it may be passed the symbol `:db` as argument. That's typically used with collections of ARs. Returned strings are:
```ruby
[].to_formatted_s(:db) # => "null"
@@ -2242,13 +2242,13 @@ If the array contains items that respond to +id+, however, it may be passed the
invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
```
-Integers in the example above are supposed to come from the respective calls to +id+.
+Integers in the example above are supposed to come from the respective calls to `id`.
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
-#### +to_xml+
+#### `to_xml`
-The method +to_xml+ returns a string containing an XML representation of its receiver:
+The method `to_xml` returns a string containing an XML representation of its receiver:
```ruby
Contributor.limit(2).order(:rank).to_xml
@@ -2270,7 +2270,7 @@ Contributor.limit(2).order(:rank).to_xml
# </contributors>
```
-To do so it sends +to_xml+ to every item in turn, and collects the results under a root node. All items must respond to +to_xml+, an exception is raised otherwise.
+To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise.
By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors".
@@ -2345,16 +2345,16 @@ Contributor.limit(2).order(:rank).to_xml(:skip_types => true)
# </contributors>
```
-NOTE: Defined in +active_support/core_ext/array/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
### Wrapping
-The method +Array.wrap+ wraps its argument in an array unless it is already an array (or array-like).
+The method `Array.wrap` wraps its argument in an array unless it is already an array (or array-like).
Specifically:
-* If the argument is +nil+ an empty list is returned.
-* Otherwise, if the argument responds to +to_ary+ it is invoked, and if the value of +to_ary+ is not +nil+, it is returned.
+* If the argument is `nil` an empty list is returned.
+* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
* Otherwise, an array with the argument as its single element is returned.
```ruby
@@ -2365,9 +2365,9 @@ Array.wrap(0) # => [0]
This method is similar in purpose to `Kernel#Array`, but there are some differences:
-* If the argument responds to +to_ary+ the method is invoked. `Kernel#Array` moves on to try +to_a+ if the returned value is +nil+, but `Array.wrap` returns +nil+ right away.
-* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
-* It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array.
+* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
+* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
+* It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
The last point is particularly worth comparing for some enumerables:
@@ -2382,15 +2382,15 @@ There's also a related idiom that uses the splat operator:
[*object]
```
-which in Ruby 1.8 returns +[nil]+ for +nil+, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
+which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
-Thus, in this case the behavior is different for +nil+, and the differences with `Kernel#Array` explained above apply to the rest of +object+s.
+Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s.
-NOTE: Defined in +active_support/core_ext/array/wrap.rb+.
+NOTE: Defined in `active_support/core_ext/array/wrap.rb`.
### Duplicating
-The method +Array.deep_dup+ duplicates itself and all objects inside recursively with ActiveSupport method +Object#deep_dup+. It works like +Array#map+ with sending +deep_dup+ method to each object inside.
+The method `Array.deep_dup` duplicates itself and all objects inside recursively with ActiveSupport method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside.
```ruby
array = [1, [2, 3]]
@@ -2399,13 +2399,13 @@ dup[1][2] = 4
array[1][2] == nil # => true
```
-NOTE: Defined in +active_support/core_ext/array/deep_dup.rb+.
+NOTE: Defined in `active_support/core_ext/array/deep_dup.rb`.
### Grouping
-#### +in_groups_of(number, fill_with = nil)+
+#### `in_groups_of(number, fill_with = nil)`
-The method +in_groups_of+ splits an array into consecutive groups of a certain size. It returns an array with the groups:
+The method `in_groups_of` splits an array into consecutive groups of a certain size. It returns an array with the groups:
```ruby
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
@@ -2423,25 +2423,25 @@ or yields them in turn if a block is passed:
<% end %>
```
-The first example shows +in_groups_of+ fills the last group with as many +nil+ elements as needed to have the requested size. You can change this padding value using the second optional argument:
+The first example shows `in_groups_of` fills the last group with as many `nil` elements as needed to have the requested size. You can change this padding value using the second optional argument:
```ruby
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
```
-And you can tell the method not to fill the last group passing +false+:
+And you can tell the method not to fill the last group passing `false`:
```ruby
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
```
-As a consequence +false+ can't be a used as a padding value.
+As a consequence `false` can't be a used as a padding value.
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
-#### +in_groups(number, fill_with = nil)+
+#### `in_groups(number, fill_with = nil)`
-The method +in_groups+ splits an array into a certain number of groups. The method returns an array with the groups:
+The method `in_groups` splits an array into a certain number of groups. The method returns an array with the groups:
```ruby
%w(1 2 3 4 5 6 7).in_groups(3)
@@ -2457,7 +2457,7 @@ or yields them in turn if a block is passed:
["6", "7", nil]
```
-The examples above show that +in_groups+ fills some groups with a trailing +nil+ element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
+The examples above show that `in_groups` fills some groups with a trailing `nil` element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
You can change this padding value using the second optional argument:
@@ -2466,20 +2466,20 @@ You can change this padding value using the second optional argument:
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
```
-And you can tell the method not to fill the smaller groups passing +false+:
+And you can tell the method not to fill the smaller groups passing `false`:
```ruby
%w(1 2 3 4 5 6 7).in_groups(3, false)
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
```
-As a consequence +false+ can't be a used as a padding value.
+As a consequence `false` can't be a used as a padding value.
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
-#### +split(value = nil)+
+#### `split(value = nil)`
-The method +split+ divides an array by a separator and returns the resulting chunks.
+The method `split` divides an array by a separator and returns the resulting chunks.
If a block is passed the separators are those elements of the array for which the block returns true:
@@ -2488,7 +2488,7 @@ If a block is passed the separators are those elements of the array for which th
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
```
-Otherwise, the value received as argument, which defaults to +nil+, is the separator:
+Otherwise, the value received as argument, which defaults to `nil`, is the separator:
```ruby
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
@@ -2497,16 +2497,16 @@ Otherwise, the value received as argument, which defaults to +nil+, is the separ
TIP: Observe in the previous example that consecutive separators result in empty arrays.
-NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
+NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
-Extensions to +Hash+
+Extensions to `Hash`
--------------------
### Conversions
-#### +to_xml+
+#### `to_xml`
-The method +to_xml+ returns a string containing an XML representation of its receiver:
+The method `to_xml` returns a string containing an XML representation of its receiver:
```ruby
{"foo" => 1, "bar" => 2}.to_xml
@@ -2518,17 +2518,17 @@ The method +to_xml+ returns a string containing an XML representation of its rec
# </hash>
```
-To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair +key+, +value+:
+To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair `key`, `value`:
-* If +value+ is a hash there's a recursive call with +key+ as `:root`.
+* If `value` is a hash there's a recursive call with `key` as `:root`.
-* If +value+ is an array there's a recursive call with +key+ as `:root`, and +key+ singularized as `:children`.
+* If `value` is an array there's a recursive call with `key` as `:root`, and `key` singularized as `:children`.
-* If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as `:root`, and +key+ singularized as second argument. Its return value becomes a new node.
+* If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. Its return value becomes a new node.
-* If +value+ responds to +to_xml+ the method is invoked with +key+ as `:root`.
+* If `value` responds to `to_xml` the method is invoked with `key` as `:root`.
-* Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
+* Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
```ruby
XML_TYPE_NAMES = {
@@ -2549,11 +2549,11 @@ By default the root node is "hash", but that's configurable via the `:root` opti
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.
-NOTE: Defined in +active_support/core_ext/hash/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
### Merging
-Ruby has a built-in method +Hash#merge+ that merges two hashes:
+Ruby has a built-in method `Hash#merge` that merges two hashes:
```ruby
{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
@@ -2562,56 +2562,56 @@ Ruby has a built-in method +Hash#merge+ that merges two hashes:
Active Support defines a few more ways of merging hashes that may be convenient.
-#### +reverse_merge+ and +reverse_merge!+
+#### `reverse_merge` and `reverse_merge!`
-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:
+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)
```
-Active Support defines +reverse_merge+ in case you prefer this alternative notation:
+Active Support defines `reverse_merge` in case you prefer this alternative notation:
```ruby
options = options.reverse_merge(:length => 30, :omission => "...")
```
-And a bang version +reverse_merge!+ that performs the merge in place:
+And a bang version `reverse_merge!` that performs the merge in place:
```ruby
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.
+WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
-NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.
+NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
-#### +reverse_update+
+#### `reverse_update`
-The method +reverse_update+ is an alias for +reverse_merge!+, explained above.
+The method `reverse_update` is an alias for `reverse_merge!`, explained above.
-WARNING. Note that +reverse_update+ has no bang.
+WARNING. Note that `reverse_update` has no bang.
-NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.
+NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
-#### +deep_merge+ and +deep_merge!+
+#### `deep_merge` and `deep_merge!`
As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.
-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:
+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}}
```
-The method +deep_merge!+ performs a deep merge in place.
+The method `deep_merge!` performs a deep merge in place.
-NOTE: Defined in +active_support/core_ext/hash/deep_merge.rb+.
+NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
### Deep duplicating
-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.
+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] } }
@@ -2624,15 +2624,15 @@ hash[:b][:e] == nil # => true
hash[:b][:d] == [3, 4] # => true
```
-NOTE: Defined in +active_support/core_ext/hash/deep_dup.rb+.
+NOTE: Defined in `active_support/core_ext/hash/deep_dup.rb`.
### Diffing
-The method +diff+ returns a hash that represents a diff of the receiver and the argument with the following logic:
+The method `diff` returns a hash that represents a diff of the receiver and the argument with the following logic:
-* Pairs +key+, +value+ that exist in both hashes do not belong to the diff hash.
+* Pairs `key`, `value` that exist in both hashes do not belong to the diff hash.
-* If both hashes have +key+, but with different values, the pair in the receiver wins.
+* If both hashes have `key`, but with different values, the pair in the receiver wins.
* The rest is just merged.
@@ -2654,7 +2654,7 @@ The method +diff+ returns a hash that represents a diff of the receiver and the
{}.diff(:a => 1) # => {:a => 1}
```
-An important property of this diff hash is that you can retrieve the original hash by applying +diff+ twice:
+An important property of this diff hash is that you can retrieve the original hash by applying `diff` twice:
```ruby
hash.diff(hash2).diff(hash2) == hash
@@ -2662,39 +2662,39 @@ hash.diff(hash2).diff(hash2) == hash
Diffing hashes may be useful for error messages related to expected option hashes for example.
-NOTE: Defined in +active_support/core_ext/hash/diff.rb+.
+NOTE: Defined in `active_support/core_ext/hash/diff.rb`.
### Working with Keys
-#### +except+ and +except!+
+#### `except` and `except!`
-The method +except+ returns a hash with the keys in the argument list removed, if present:
+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}
```
-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:
+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") # => {}
```
-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+:
+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`:
```ruby
params[:account] = params[:account].except(:plan_id) unless admin?
@account.update_attributes(params[:account])
```
-There's also the bang variant +except!+ that removes keys in the very receiver.
+There's also the bang variant `except!` that removes keys in the very receiver.
-NOTE: Defined in +active_support/core_ext/hash/except.rb+.
+NOTE: Defined in `active_support/core_ext/hash/except.rb`.
-#### +transform_keys+ and +transform_keys!+
+#### `transform_keys` and `transform_keys!`
-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:
+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 }
@@ -2708,7 +2708,7 @@ The result in case of collision is undefined:
# => {"A" => 2}, in my test, can't rely on this result though
```
-This method may be useful for example to build specialized conversions. For instance +stringify_keys+ and +symbolize_keys+ use +transform_keys+ to perform their key conversions:
+This method may be useful for example to build specialized conversions. For instance `stringify_keys` and `symbolize_keys` use `transform_keys` to perform their key conversions:
```ruby
def stringify_keys
@@ -2720,20 +2720,20 @@ def symbolize_keys
end
```
-There's also the bang variant +transform_keys!+ that applies the block operations to keys in the very receiver.
+There's also the bang variant `transform_keys!` that applies the block operations to keys in the very receiver.
-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:
+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, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
```
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
-#### +stringify_keys+ and +stringify_keys!+
+#### `stringify_keys` and `stringify_keys!`
-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:
+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
@@ -2747,7 +2747,7 @@ The result in case of collision is undefined:
# => {"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 +ActionView::Helpers::FormHelper+ defines:
+This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines:
```ruby
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
@@ -2757,22 +2757,22 @@ def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
end
```
-The second line can safely access the "type" key, and let the user to pass either +:type+ or "type".
+The second line can safely access the "type" key, and let the user to pass either `:type` or "type".
-There's also the bang variant +stringify_keys!+ that stringifies keys in the very receiver.
+There's also the bang variant `stringify_keys!` that stringifies keys in the very receiver.
-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:
+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, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
```
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
-#### +symbolize_keys+ and +symbolize_keys!+
+#### `symbolize_keys` and `symbolize_keys!`
-The method +symbolize_keys+ returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending +to_sym+ to them:
+The method `symbolize_keys` returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending `to_sym` to them:
```ruby
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
@@ -2788,7 +2788,7 @@ The result in case of collision is undefined:
# => {: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
+This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
```ruby
def rewrite_path(options)
@@ -2798,37 +2798,37 @@ def rewrite_path(options)
end
```
-The second line can safely access the +:params+ key, and let the user to pass either +:params+ or "params".
+The second line can safely access the `:params` key, and let the user to pass either `:params` or "params".
-There's also the bang variant +symbolize_keys!+ that symbolizes keys in the very receiver.
+There's also the bang variant `symbolize_keys!` that symbolizes keys in the very receiver.
-Besides that, one can use +deep_symbolize_keys+ and +deep_symbolize_keys!+ to symbolize all the keys in the given hash and all the hashes nested into it. An example of the result is:
+Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to symbolize 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_symbolize_keys
# => {nil=>nil, 1=>1, :nested=>{:a=>3, 5=>5}}
```
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
-#### +to_options+ and +to_options!+
+#### `to_options` and `to_options!`
-The methods +to_options+ and +to_options!+ are respectively aliases of +symbolize_keys+ and +symbolize_keys!+.
+The methods `to_options` and `to_options!` are respectively aliases of `symbolize_keys` and `symbolize_keys!`.
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
-#### +assert_valid_keys+
+#### `assert_valid_keys`
-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.
+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
```
-Active Record does not accept unknown options when building associations, for example. It implements that control via +assert_valid_keys+.
+Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
-NOTE: Defined in +active_support/core_ext/hash/keys.rb+.
+NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
### Slicing
@@ -2842,7 +2842,7 @@ Ruby has built-in support for taking slices out of strings and arrays. Active Su
# => {:b => 2} # non-existing keys are ignored
```
-If the receiver responds to +convert_key+ keys are normalized:
+If the receiver responds to `convert_key` keys are normalized:
```ruby
{:a => 1, :b => 2}.with_indifferent_access.slice("a")
@@ -2851,7 +2851,7 @@ If the receiver responds to +convert_key+ keys are normalized:
NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
-There's also +slice!+ which in addition to perform a slice in place returns what's removed:
+There's also `slice!` which in addition to perform a slice in place returns what's removed:
```ruby
hash = {:a => 1, :b => 2}
@@ -2859,11 +2859,11 @@ rest = hash.slice!(:a) # => {:b => 2}
hash # => {:a => 1}
```
-NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
+NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
### Extracting
-The method +extract!+ removes and returns the key/value pairs matching the given keys.
+The method `extract!` removes and returns the key/value pairs matching the given keys.
```ruby
hash = {:a => 1, :b => 2}
@@ -2871,24 +2871,24 @@ rest = hash.extract!(:a) # => {:a => 1}
hash # => {:b => 2}
```
-NOTE: Defined in +active_support/core_ext/hash/slice.rb+.
+NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
### Indifferent Access
-The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:
+The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
```ruby
{:a => 1}.with_indifferent_access["a"] # => 1
```
-NOTE: Defined in +active_support/core_ext/hash/indifferent_access.rb+.
+NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
-Extensions to +Regexp+
+Extensions to `Regexp`
----------------------
-### +multiline?+
+### `multiline?`
-The method +multiline?+ says whether a regexp has the +/m+ flag set, that is, whether the dot matches newlines.
+The method `multiline?` says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines.
```ruby
%r{.}.multiline? # => false
@@ -2910,14 +2910,14 @@ def assign_route_options(segments, defaults, requirements)
end
```
-NOTE: Defined in +active_support/core_ext/regexp.rb+.
+NOTE: Defined in `active_support/core_ext/regexp.rb`.
-Extensions to +Range+
+Extensions to `Range`
---------------------
-### +to_s+
+### `to_s`
-Active Support extends the method +Range#to_s+ so that it understands an optional format argument. As of this writing the only supported non-default format is +:db+:
+Active Support extends the method `Range#to_s` so that it understands an optional format argument. As of this writing the only supported non-default format is `:db`:
```ruby
(Date.today..Date.tomorrow).to_s
@@ -2927,13 +2927,13 @@ Active Support extends the method +Range#to_s+ so that it understands an optiona
# => "BETWEEN '2009-10-25' AND '2009-10-26'"
```
-As the example depicts, the +:db+ format generates a +BETWEEN+ SQL clause. That is used by Active Record in its support for range values in conditions.
+As the example depicts, the `:db` format generates a `BETWEEN` SQL clause. That is used by Active Record in its support for range values in conditions.
-NOTE: Defined in +active_support/core_ext/range/conversions.rb+.
+NOTE: Defined in `active_support/core_ext/range/conversions.rb`.
-### +include?+
+### `include?`
-The methods +Range#include?+ and +Range#===+ say whether some value falls between the ends of a given instance:
+The methods `Range#include?` and `Range#===` say whether some value falls between the ends of a given instance:
```ruby
(2..3).include?(Math::E) # => true
@@ -2953,11 +2953,11 @@ Active Support extends these methods so that the argument may be another range i
(1...9) === (3..9) # => false
```
-NOTE: Defined in +active_support/core_ext/range/include_range.rb+.
+NOTE: Defined in `active_support/core_ext/range/include_range.rb`.
-### +overlaps?+
+### `overlaps?`
-The method +Range#overlaps?+ says whether any two given ranges have non-void intersection:
+The method `Range#overlaps?` says whether any two given ranges have non-void intersection:
```ruby
(1..10).overlaps?(7..11) # => true
@@ -2965,37 +2965,37 @@ The method +Range#overlaps?+ says whether any two given ranges have non-void int
(1..10).overlaps?(11..27) # => false
```
-NOTE: Defined in +active_support/core_ext/range/overlaps.rb+.
+NOTE: Defined in `active_support/core_ext/range/overlaps.rb`.
-Extensions to +Proc+
+Extensions to `Proc`
--------------------
-### +bind+
+### `bind`
-As you surely know Ruby has an +UnboundMethod+ class whose instances are methods that belong to the limbo of methods without a self. The method +Module#instance_method+ returns an unbound method for example:
+As you surely know Ruby has an `UnboundMethod` class whose instances are methods that belong to the limbo of methods without a self. The method `Module#instance_method` returns an unbound method for example:
```ruby
Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
```
-An unbound method is not callable as is, you need to bind it first to an object with +bind+:
+An unbound method is not callable as is, you need to bind it first to an object with `bind`:
```ruby
clear = Hash.instance_method(:clear)
clear.bind({:a => 1}).call # => {}
```
-Active Support defines +Proc#bind+ with an analogous purpose:
+Active Support defines `Proc#bind` with an analogous purpose:
```ruby
Proc.new { size }.bind([]).call # => 0
```
-As you see that's callable and bound to the argument, the return value is indeed a +Method+.
+As you see that's callable and bound to the argument, the return value is indeed a `Method`.
-NOTE: To do so +Proc#bind+ actually creates a method under the hood. If you ever see a method with a weird name like +__bind_1256598120_237302+ in a stack trace you know now where it comes from.
+NOTE: To do so `Proc#bind` actually creates a method under the hood. If you ever see a method with a weird name like `__bind_1256598120_237302` in a stack trace you know now where it comes from.
-Action Pack uses this trick in +rescue_from+ for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by +handler_for_rescue+, thus simplifying the code in the caller:
+Action Pack uses this trick in `rescue_from` for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by `handler_for_rescue`, thus simplifying the code in the caller:
```ruby
def handler_for_rescue(exception)
@@ -3012,28 +3012,28 @@ def handler_for_rescue(exception)
end
```
-NOTE: Defined in +active_support/core_ext/proc.rb+.
+NOTE: Defined in `active_support/core_ext/proc.rb`.
-Extensions to +Date+
+Extensions to `Date`
--------------------
### Calculations
-NOTE: All the following methods are defined in +active_support/core_ext/date/calculations.rb+.
+NOTE: All the following methods are defined in `active_support/core_ext/date/calculations.rb`.
-INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, +Date.new(1582, 10, 4).tomorrow+ returns +Date.new(1582, 10, 15)+ and so on. Please check +test/core_ext/date_ext_test.rb+ in the Active Support test suite for expected behavior.
+INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, `Date.new(1582, 10, 4).tomorrow` returns `Date.new(1582, 10, 15)` and so on. Please check `test/core_ext/date_ext_test.rb` in the Active Support test suite for expected behavior.
-#### +Date.current+
+#### `Date.current`
-Active Support defines +Date.current+ to be today in the current time zone. That's like +Date.today+, except that it honors the user time zone, if defined. It also defines +Date.yesterday+ and +Date.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Date.current+.
+Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Date.current`.
-When making Date comparisons using methods which honor the user time zone, make sure to use +Date.current+ and not +Date.today+. There are cases where the user time zone might be in the future compared to the system time zone, which +Date.today+ uses by default. This means +Date.today+ may equal +Date.yesterday+.
+When making Date comparisons using methods which honor the user time zone, make sure to use `Date.current` and not `Date.today`. There are cases where the user time zone might be in the future compared to the system time zone, which `Date.today` uses by default. This means `Date.today` may equal `Date.yesterday`.
#### Named dates
-##### +prev_year+, +next_year+
+##### `prev_year`, `next_year`
-In Ruby 1.9 +prev_year+ and +next_year+ return a date with the same day/month in the last or next year:
+In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year:
```ruby
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
@@ -3049,11 +3049,11 @@ d.prev_year # => Sun, 28 Feb 1999
d.next_year # => Wed, 28 Feb 2001
```
-+prev_year+ is aliased to +last_year+.
+`prev_year` is aliased to `last_year`.
-##### +prev_month+, +next_month+
+##### `prev_month`, `next_month`
-In Ruby 1.9 +prev_month+ and +next_month+ return the date with the same day in the last or next month:
+In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month:
```ruby
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
@@ -3070,11 +3070,11 @@ Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
```
-+prev_month+ is aliased to +last_month+.
+`prev_month` is aliased to `last_month`.
-##### +prev_quarter+, +next_quarter+
+##### `prev_quarter`, `next_quarter`
-Same as +prev_month+ and +next_month+. It returns the date with the same day in the previous or next quarter:
+Same as `prev_month` and `next_month`. It returns the date with the same day in the previous or next quarter:
```ruby
t = Time.local(2010, 5, 8) # => Sat, 08 May 2010
@@ -3091,11 +3091,11 @@ Time.local(2000, 10, 31).prev_quarter # => Mon, 30 Oct 2000
Time.local(2000, 11, 31).next_quarter # => Wed, 28 Feb 2001
```
-+prev_quarter+ is aliased to +last_quarter+.
+`prev_quarter` is aliased to `last_quarter`.
-##### +beginning_of_week+, +end_of_week+
+##### `beginning_of_week`, `end_of_week`
-The methods +beginning_of_week+ and +end_of_week+ return the dates for the
+The methods `beginning_of_week` and `end_of_week` return the dates for the
beginning and end of the week, respectively. Weeks are assumed to start on
Monday, but that can be changed passing an argument.
@@ -3107,11 +3107,11 @@ d.end_of_week # => Sun, 09 May 2010
d.end_of_week(:sunday) # => Sat, 08 May 2010
```
-+beginning_of_week+ is aliased to +at_beginning_of_week+ and +end_of_week+ is aliased to +at_end_of_week+.
+`beginning_of_week` is aliased to `at_beginning_of_week` and `end_of_week` is aliased to `at_end_of_week`.
-##### +monday+, +sunday+
+##### `monday`, `sunday`
-The methods +monday+ and +sunday+ return the dates for the beginning and
+The methods `monday` and `sunday` return the dates for the beginning and
end of the week, respectively. Weeks are assumed to start on Monday.
```ruby
@@ -3120,9 +3120,9 @@ d.monday # => Mon, 03 May 2010
d.sunday # => Sun, 09 May 2010
```
-##### +prev_week+, +next_week+
+##### `prev_week`, `next_week`
-The method +next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day:
+The method `next_week` receives a symbol with a day name in English (in lowercase, default is `:monday`) and it returns the date corresponding to that day:
```ruby
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
@@ -3130,7 +3130,7 @@ d.next_week # => Mon, 10 May 2010
d.next_week(:saturday) # => Sat, 15 May 2010
```
-The method +prev_week+ is analogous:
+The method `prev_week` is analogous:
```ruby
d.prev_week # => Mon, 26 Apr 2010
@@ -3138,11 +3138,11 @@ d.prev_week(:saturday) # => Sat, 01 May 2010
d.prev_week(:friday) # => Fri, 30 Apr 2010
```
-+prev_week+ is aliased to +last_week+.
+`prev_week` is aliased to `last_week`.
-##### +beginning_of_month+, +end_of_month+
+##### `beginning_of_month`, `end_of_month`
-The methods +beginning_of_month+ and +end_of_month+ return the dates for the beginning and end of the month:
+The methods `beginning_of_month` and `end_of_month` return the dates for the beginning and end of the month:
```ruby
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
@@ -3150,11 +3150,11 @@ d.beginning_of_month # => Sat, 01 May 2010
d.end_of_month # => Mon, 31 May 2010
```
-+beginning_of_month+ is aliased to +at_beginning_of_month+, and +end_of_month+ is aliased to +at_end_of_month+.
+`beginning_of_month` is aliased to `at_beginning_of_month`, and `end_of_month` is aliased to `at_end_of_month`.
-##### +beginning_of_quarter+, +end_of_quarter+
+##### `beginning_of_quarter`, `end_of_quarter`
-The methods +beginning_of_quarter+ and +end_of_quarter+ return the dates for the beginning and end of the quarter of the receiver's calendar year:
+The methods `beginning_of_quarter` and `end_of_quarter` return the dates for the beginning and end of the quarter of the receiver's calendar year:
```ruby
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
@@ -3162,11 +3162,11 @@ d.beginning_of_quarter # => Thu, 01 Apr 2010
d.end_of_quarter # => Wed, 30 Jun 2010
```
-+beginning_of_quarter+ is aliased to +at_beginning_of_quarter+, and +end_of_quarter+ is aliased to +at_end_of_quarter+.
+`beginning_of_quarter` is aliased to `at_beginning_of_quarter`, and `end_of_quarter` is aliased to `at_end_of_quarter`.
-##### +beginning_of_year+, +end_of_year+
+##### `beginning_of_year`, `end_of_year`
-The methods +beginning_of_year+ and +end_of_year+ return the dates for the beginning and end of the year:
+The methods `beginning_of_year` and `end_of_year` return the dates for the beginning and end of the year:
```ruby
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
@@ -3174,20 +3174,20 @@ d.beginning_of_year # => Fri, 01 Jan 2010
d.end_of_year # => Fri, 31 Dec 2010
```
-+beginning_of_year+ is aliased to +at_beginning_of_year+, and +end_of_year+ is aliased to +at_end_of_year+.
+`beginning_of_year` is aliased to `at_beginning_of_year`, and `end_of_year` is aliased to `at_end_of_year`.
#### Other Date Computations
-##### +years_ago+, +years_since+
+##### `years_ago`, `years_since`
-The method +years_ago+ receives a number of years and returns the same date those many years ago:
+The method `years_ago` receives a number of years and returns the same date those many years ago:
```ruby
date = Date.new(2010, 6, 7)
date.years_ago(10) # => Wed, 07 Jun 2000
```
-+years_since+ moves forward in time:
+`years_since` moves forward in time:
```ruby
date = Date.new(2010, 6, 7)
@@ -3201,9 +3201,9 @@ Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009
Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015
```
-##### +months_ago+, +months_since+
+##### `months_ago`, `months_since`
-The methods +months_ago+ and +months_since+ work analogously for months:
+The methods `months_ago` and `months_since` work analogously for months:
```ruby
Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
@@ -3217,18 +3217,18 @@ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
```
-##### +weeks_ago+
+##### `weeks_ago`
-The method +weeks_ago+ works analogously for weeks:
+The method `weeks_ago` works analogously for weeks:
```ruby
Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010
Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010
```
-##### +advance+
+##### `advance`
-The most generic way to jump to other days is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, and returns a date advanced as much as the present keys indicate:
+The most generic way to jump to other days is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, and returns a date advanced as much as the present keys indicate:
```ruby
date = Date.new(2010, 6, 6)
@@ -3240,7 +3240,7 @@ Note in the previous example that increments may be negative.
To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.
-The method +advance+ advances first one month, and then one day, the result is:
+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)
@@ -3256,14 +3256,14 @@ Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
#### Changing Components
-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:
+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)
# => Wed, 23 Nov 2011
```
-This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised:
+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)
@@ -3283,7 +3283,7 @@ d - 3.hours
# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
```
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
```ruby
Date.new(1582, 10, 4) + 1.day
@@ -3292,56 +3292,56 @@ Date.new(1582, 10, 4) + 1.day
#### Timestamps
-INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+. If set, they honor the user time zone.
+INFO: The following methods return a `Time` object if possible, otherwise a `DateTime`. If set, they honor the user time zone.
-##### +beginning_of_day+, +end_of_day+
+##### `beginning_of_day`, `end_of_day`
-The method +beginning_of_day+ returns a timestamp at the beginning of the day (00:00:00):
+The method `beginning_of_day` returns a timestamp at the beginning of the day (00:00:00):
```ruby
date = Date.new(2010, 6, 7)
date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010
```
-The method +end_of_day+ returns a timestamp at the end of the day (23:59:59):
+The method `end_of_day` returns a timestamp at the end of the day (23:59:59):
```ruby
date = Date.new(2010, 6, 7)
date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010
```
-+beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight+.
+`beginning_of_day` is aliased to `at_beginning_of_day`, `midnight`, `at_midnight`.
-##### +beginning_of_hour+, +end_of_hour+
+##### `beginning_of_hour`, `end_of_hour`
-The method +beginning_of_hour+ returns a timestamp at the beginning of the hour (hh:00:00):
+The method `beginning_of_hour` returns a timestamp at the beginning of the hour (hh:00:00):
```ruby
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010
```
-The method +end_of_hour+ returns a timestamp at the end of the hour (hh:59:59):
+The method `end_of_hour` returns a timestamp at the end of the hour (hh:59:59):
```ruby
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010
```
-+beginning_of_hour+ is aliased to +at_beginning_of_hour+.
+`beginning_of_hour` is aliased to `at_beginning_of_hour`.
-INFO: +beginning_of_hour+ and +end_of_hour+ are implemented for +Time+ and +DateTime+ but *not* +Date+ as it does not make sense to request the beginning or end of an hour on a +Date+ instance.
+INFO: `beginning_of_hour` and `end_of_hour` are implemented for `Time` and `DateTime` but *not* `Date` as it does not make sense to request the beginning or end of an hour on a `Date` instance.
-##### +ago+, +since+
+##### `ago`, `since`
-The method +ago+ receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
+The method `ago` receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
```ruby
date = Date.current # => Fri, 11 Jun 2010
date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
```
-Similarly, +since+ moves forward:
+Similarly, `since` moves forward:
```ruby
date = Date.current # => Fri, 11 Jun 2010
@@ -3352,16 +3352,16 @@ date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
### Conversions
-Extensions to +DateTime+
+Extensions to `DateTime`
------------------------
-WARNING: +DateTime+ is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example +seconds_since_midnight+ might not return the real amount in such a day.
+WARNING: `DateTime` is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example `seconds_since_midnight` might not return the real amount in such a day.
### Calculations
-NOTE: All the following methods are defined in +active_support/core_ext/date_time/calculations.rb+.
+NOTE: All the following methods are defined in `active_support/core_ext/date_time/calculations.rb`.
-The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_ext/date/calculations.rb+ you inherit these methods and their aliases, except that they will always return datetimes:
+The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ext/date/calculations.rb` you inherit these methods and their aliases, except that they will always return datetimes:
```ruby
yesterday
@@ -3389,7 +3389,7 @@ prev_year (last_year)
next_year
```
-The following methods are reimplemented so you do *not* need to load +active_support/core_ext/date/calculations.rb+ for these ones:
+The following methods are reimplemented so you do *not* need to load `active_support/core_ext/date/calculations.rb` for these ones:
```ruby
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
@@ -3398,9 +3398,9 @@ ago
since (in)
```
-On the other hand, +advance+ and +change+ are also defined and support more options, they are documented below.
+On the other hand, `advance` and `change` are also defined and support more options, they are documented below.
-The following methods are only implemented in +active_support/core_ext/date_time/calculations.rb+ as they only make sense when used with a +DateTime+ instance:
+The following methods are only implemented in `active_support/core_ext/date_time/calculations.rb` as they only make sense when used with a `DateTime` instance:
```ruby
beginning_of_hour (at_beginning_of_hour)
@@ -3409,35 +3409,35 @@ end_of_hour
#### Named Datetimes
-##### +DateTime.current+
+##### `DateTime.current`
-Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines +DateTime.yesterday+ and +DateTime.tomorrow+, and the instance predicates +past?+, and +future?+ relative to +DateTime.current+.
+Active Support defines `DateTime.current` to be like `Time.now.to_datetime`, except that it honors the user time zone, if defined. It also defines `DateTime.yesterday` and `DateTime.tomorrow`, and the instance predicates `past?`, and `future?` relative to `DateTime.current`.
#### Other Extensions
-##### +seconds_since_midnight+
+##### `seconds_since_midnight`
-The method +seconds_since_midnight+ returns the number of seconds since midnight:
+The method `seconds_since_midnight` returns the number of seconds since midnight:
```ruby
now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000
now.seconds_since_midnight # => 73596
```
-##### +utc+
+##### `utc`
-The method +utc+ gives you the same datetime in the receiver expressed in UTC.
+The method `utc` gives you the same datetime in the receiver expressed in UTC.
```ruby
now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
now.utc # => Mon, 07 Jun 2010 23:27:52 +0000
```
-This method is also aliased as +getutc+.
+This method is also aliased as `getutc`.
-##### +utc?+
+##### `utc?`
-The predicate +utc?+ says whether the receiver has UTC as its time zone:
+The predicate `utc?` says whether the receiver has UTC as its time zone:
```ruby
now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
@@ -3445,9 +3445,9 @@ now.utc? # => false
now.utc.utc? # => true
```
-##### +advance+
+##### `advance`
-The most generic way to jump to another datetime is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, +:hours+, +:minutes+, and +:seconds+, and returns a datetime advanced as much as the present keys indicate.
+The most generic way to jump to another datetime is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, `:hours`, `:minutes`, and `:seconds`, and returns a datetime advanced as much as the present keys indicate.
```ruby
d = DateTime.current
@@ -3456,7 +3456,7 @@ d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :se
# => Tue, 06 Sep 2011 12:34:32 +0000
```
-This method first computes the destination date passing +:years+, +:months+, +:weeks+, and +:days+ to +Date#advance+ documented above. After that, it adjusts the time calling +since+ with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in +Date#advance+ applies, and we can extend it to show order relevance related to the time bits.
+This method first computes the destination date passing `:years`, `:months`, `:weeks`, and `:days` to `Date#advance` documented above. After that, it adjusts the time calling `since` with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in `Date#advance` applies, and we can extend it to show order relevance related to the time bits.
If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:
@@ -3474,11 +3474,11 @@ d.advance(:seconds => 1).advance(:months => 1)
# => Thu, 01 Apr 2010 00:00:00 +0000
```
-WARNING: Since +DateTime+ is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
+WARNING: Since `DateTime` is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
#### Changing Components
-The method +change+ allows you to get a new datetime which is the same as the receiver except for the given options, which may include +:year+, +:month+, +:day+, +:hour+, +:min+, +:sec+, +:offset+, +:start+:
+The method `change` allows you to get a new datetime which is the same as the receiver except for the given options, which may include `:year`, `:month`, `:day`, `:hour`, `:min`, `:sec`, `:offset`, `:start`:
```ruby
now = DateTime.current
@@ -3501,7 +3501,7 @@ 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:
+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)
@@ -3521,21 +3521,21 @@ now - 1.week
# => Mon, 02 Aug 2010 23:15:17 +0000
```
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
```ruby
DateTime.new(1582, 10, 4, 23) + 1.hour
# => Fri, 15 Oct 1582 00:00:00 +0000
```
-Extensions to +Time+
+Extensions to `Time`
--------------------
### Calculations
-NOTE: All the following methods are defined in +active_support/core_ext/time/calculations.rb+.
+NOTE: All the following methods are defined in `active_support/core_ext/time/calculations.rb`.
-Active Support adds to +Time+ many of the methods available for +DateTime+:
+Active Support adds to `Time` many of the methods available for `DateTime`:
```ruby
past?
@@ -3577,8 +3577,8 @@ next_year
They are analogous. Please refer to their documentation above and take into account the following differences:
-* +change+ accepts an additional +:usec+ option.
-* +Time+ understands DST, so you get correct DST calculations as in
+* `change` accepts an additional `:usec` option.
+* `Time` understands DST, so you get correct DST calculations as in
```ruby
Time.zone_default
@@ -3591,17 +3591,17 @@ t.advance(:seconds => 1)
# => Sun Mar 28 03:00:00 +0200 2010
```
-* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.
+* If `since` or `ago` jump to a time that can't be expressed with `Time` a `DateTime` object is returned instead.
-#### +Time.current+
+#### `Time.current`
-Active Support defines +Time.current+ to be today in the current time zone. That's like +Time.now+, except that it honors the user time zone, if defined. It also defines +Time.yesterday+ and +Time.tomorrow+, and the instance predicates +past?+, +today?+, and +future?+, all of them relative to +Time.current+.
+Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines `Time.yesterday` and `Time.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Time.current`.
-When making Time comparisons using methods which honor the user time zone, make sure to use +Time.current+ and not +Time.now+. There are cases where the user time zone might be in the future compared to the system time zone, which +Time.today+ uses by default. This means +Time.now+ may equal +Time.yesterday+.
+When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` and not `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.today` uses by default. This means `Time.now` may equal `Time.yesterday`.
-#### +all_day+, +all_week+, +all_month+, +all_quarter+ and +all_year+
+#### `all_day`, `all_week`, `all_month`, `all_quarter` and `all_year`
-The method +all_day+ returns a range representing the whole day of the current time.
+The method `all_day` returns a range representing the whole day of the current time.
```ruby
now = Time.current
@@ -3610,7 +3610,7 @@ now.all_day
# => Mon, 09 Aug 2010 00:00:00 UTC <plus>00:00..Mon, 09 Aug 2010 23:59:59 UTC <plus>00:00
```
-Analogously, +all_week+, +all_month+, +all_quarter+ and +all_year+ all serve the purpose of generating time ranges.
+Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges.
```ruby
now = Time.current
@@ -3627,7 +3627,7 @@ now.all_year
### Time Constructors
-Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:
+Active Support defines `Time.current` to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`:
```ruby
Time.zone_default
@@ -3636,9 +3636,9 @@ Time.current
# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
```
-Analogously to +DateTime+, the predicates +past?+, and +future?+ are relative to +Time.current+.
+Analogously to `DateTime`, the predicates `past?`, and `future?` are relative to `Time.current`.
-Use the +local_time+ class method to create time objects honoring the user time zone:
+Use the `local_time` class method to create time objects honoring the user time zone:
```ruby
Time.zone_default
@@ -3647,7 +3647,7 @@ Time.local_time(2010, 8, 15)
# => Sun Aug 15 00:00:00 +0200 2010
```
-The +utc_time+ class method returns a time in UTC:
+The `utc_time` class method returns a time in UTC:
```ruby
Time.zone_default
@@ -3656,9 +3656,9 @@ Time.utc_time(2010, 8, 15)
# => Sun Aug 15 00:00:00 UTC 2010
```
-Both +local_time+ and +utc_time+ accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.
+Both `local_time` and `utc_time` accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.
-If the time to be constructed lies beyond the range supported by +Time+ in the runtime platform, usecs are discarded and a +DateTime+ object is returned instead.
+If the time to be constructed lies beyond the range supported by `Time` in the runtime platform, usecs are discarded and a `DateTime` object is returned instead.
#### Durations
@@ -3673,23 +3673,23 @@ now - 1.week
# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
```
-They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:
+They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
```ruby
Time.utc_time(1582, 10, 3) + 5.days
# => Mon Oct 18 00:00:00 UTC 1582
```
-Extensions to +File+
+Extensions to `File`
--------------------
-### +atomic_write+
+### `atomic_write`
-With the class method +File.atomic_write+ you can write to a file in a way that will prevent any reader from seeing half-written content.
+With the class method `File.atomic_write` you can write to a file in a way that will prevent any reader from seeing half-written content.
-The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done +atomic_write+ closes the file handle and completes its job.
+The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done `atomic_write` closes the file handle and completes its job.
-For example, Action Pack uses this method to write asset cache files like +all.css+:
+For example, Action Pack uses this method to write asset cache files like `all.css`:
```ruby
File.atomic_write(joined_asset_path) do |cache|
@@ -3697,27 +3697,27 @@ File.atomic_write(joined_asset_path) do |cache|
end
```
-To accomplish this +atomic_write+ creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists +atomic_write+ overwrites it and keeps owners and permissions.
+To accomplish this `atomic_write` creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists `atomic_write` overwrites it and keeps owners and permissions.
-WARNING. Note you can't append with +atomic_write+.
+WARNING. Note you can't append with `atomic_write`.
The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.
-NOTE: Defined in +active_support/core_ext/file/atomic.rb+.
+NOTE: Defined in `active_support/core_ext/file/atomic.rb`.
-Extensions to +Logger+
+Extensions to `Logger`
----------------------
-### +around_[level]+
+### `around_[level]`
-Takes two arguments, a +before_message+ and +after_message+ and calls the current level method on the +Logger+ instance, passing in the +before_message+, then the specified message, then the +after_message+:
+Takes two arguments, a `before_message` and `after_message` and calls the current level method on the `Logger` instance, passing in the `before_message`, then the specified message, then the `after_message`:
```ruby
logger = Logger.new("log/development.log")
logger.around_info("before", "after") { |logger| logger.info("during") }
```
-### +silence+
+### `silence`
Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.
@@ -3729,9 +3729,9 @@ logger.silence(Logger::INFO) do
end
```
-### +datetime_format=+
+### `datetime_format=`
-Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a +datetime_format+ method then this is ignored.
+Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a `datetime_format` method then this is ignored.
```ruby
class Logger::FormatWithTime < Logger::Formatter
@@ -3747,18 +3747,18 @@ logger.formatter = Logger::FormatWithTime
logger.info("<- is the current time")
```
-NOTE: Defined in +active_support/core_ext/logger.rb+.
+NOTE: Defined in `active_support/core_ext/logger.rb`.
-Extensions to +NameError+
+Extensions to `NameError`
-------------------------
-Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument.
+Active Support adds `missing_name?` to `NameError`, which tests whether the exception was raised because of the name passed as argument.
The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.
-TIP: A symbol can represent a fully-qualified constant name as in +:"ActiveRecord::Base"+, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
+TIP: A symbol can represent a fully-qualified constant name as in `:"ActiveRecord::Base"`, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
-For example, when an action of +PostsController+ is called Rails tries optimistically to use +PostsHelper+. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that +posts_helper.rb+ raises a +NameError+ due to an actual unknown constant. That should be reraised. The method +missing_name?+ provides a way to distinguish both cases:
+For example, when an action of `PostsController` is called Rails tries optimistically to use `PostsHelper`. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that `posts_helper.rb` raises a `NameError` due to an actual unknown constant. That should be reraised. The method `missing_name?` provides a way to distinguish both cases:
```ruby
def default_helper_module!
@@ -3772,16 +3772,16 @@ rescue NameError => e
end
```
-NOTE: Defined in +active_support/core_ext/name_error.rb+.
+NOTE: Defined in `active_support/core_ext/name_error.rb`.
-Extensions to +LoadError+
+Extensions to `LoadError`
-------------------------
-Active Support adds +is_missing?+ to +LoadError+, and also assigns that class to the constant +MissingSourceFile+ for backwards compatibility.
+Active Support adds `is_missing?` to `LoadError`, and also assigns that class to the constant `MissingSourceFile` for backwards compatibility.
-Given a path name +is_missing?+ tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
+Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
-For example, when an action of +PostsController+ is called Rails tries to load +posts_helper.rb+, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method +is_missing?+ provides a way to distinguish both cases:
+For example, when an action of `PostsController` is called Rails tries to load `posts_helper.rb`, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method `is_missing?` provides a way to distinguish both cases:
```ruby
def default_helper_module!
@@ -3795,4 +3795,4 @@ rescue NameError => e
end
```
-NOTE: Defined in +active_support/core_ext/load_error.rb+.
+NOTE: Defined in `active_support/core_ext/load_error.rb`.