diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 60f4afc8f6..ab2ef60f2b 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -29,7 +29,7 @@ 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?`][Object#blank?]. Let's see how to load its definition. #### Cherry-picking a Definition @@ -101,7 +101,7 @@ INFO: The predicate for strings uses the Unicode-aware character class `[:space: WARNING: Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank. -For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses `blank?` for checking whether a token is present: +For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses [`blank?`][Object#blank?] for checking whether a token is present: ```ruby def authenticate(controller, &login_procedure) @@ -112,7 +112,7 @@ def authenticate(controller, &login_procedure) end ``` -The method `present?` is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`: +The method [`present?`][Object#present?] is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`: ```ruby def set_conditional_cache_control! @@ -123,9 +123,12 @@ end NOTE: Defined in `active_support/core_ext/object/blank.rb`. +[Object#blank?]: https://api.rubyonrails.org/classes/Object.html#method-i-blank-3F +[Object#present?]: https://api.rubyonrails.org/classes/Object.html#method-i-present-3F + ### `presence` -The `presence` method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this: +The [`presence`][Object#presence] method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this: ```ruby host = config[:host].presence || 'localhost' @@ -133,6 +136,8 @@ host = config[:host].presence || 'localhost' NOTE: Defined in `active_support/core_ext/object/blank.rb`. +[Object#presence]: https://api.rubyonrails.org/classes/Object.html#method-i-presence + ### `duplicable?` As of Ruby 2.5, most objects can be duplicated via `dup` or `clone`: @@ -145,7 +150,7 @@ Complex(0).dup # => (0+0i) 1.method(:+).dup # => TypeError (allocator undefined for Method) ``` -Active Support provides `duplicable?` to query an object about this: +Active Support provides [`duplicable?`][Object#duplicable?] to query an object about this: ```ruby "foo".duplicable? # => true @@ -159,9 +164,11 @@ WARNING: Any class can disallow duplication by removing `dup` and `clone` or rai NOTE: Defined in `active_support/core_ext/object/duplicable.rb`. +[Object#duplicable?]: https://api.rubyonrails.org/classes/Object.html#method-i-duplicable-3F + ### `deep_dup` -The `deep_dup` method returns a deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this: +The [`deep_dup`][Object#deep_dup] method returns a deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this: ```ruby array = ['string'] @@ -204,9 +211,11 @@ number.object_id == duplicate.object_id # => true NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`. +[Object#deep_dup]: https://api.rubyonrails.org/classes/Object.html#method-i-deep_dup + ### `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`][Object#try]. `try` is like `Object#send` except that it returns `nil` if sent to `nil`. Here is an example: @@ -237,7 +246,7 @@ end @person.try { |p| "#{p.first_name} #{p.last_name}" } ``` -Note that `try` will swallow no-method errors, returning nil instead. If you want to protect against typos, use `try!` instead: +Note that `try` will swallow no-method errors, returning nil instead. If you want to protect against typos, use [`try!`][Object#try!] instead: ```ruby @number.try(:nest) # => nil @@ -246,9 +255,12 @@ Note that `try` will swallow no-method errors, returning nil instead. If you wan NOTE: Defined in `active_support/core_ext/object/try.rb`. +[Object#try]: https://api.rubyonrails.org/classes/Object.html#method-i-try +[Object#try!]: https://api.rubyonrails.org/classes/Object.html#method-i-try-21 + ### `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`][Kernel#class_eval]: ```ruby class Proc @@ -267,9 +279,11 @@ end NOTE: Defined in `active_support/core_ext/kernel/singleton_class.rb`. +[Kernel#class_eval]: https://api.rubyonrails.org/classes/Kernel.html#method-i-class_eval + ### `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?`][Object#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? @@ -286,9 +300,11 @@ Rails has classes that act like `Date` or `Time` and follow this contract. NOTE: Defined in `active_support/core_ext/object/acts_like.rb`. +[Object#acts_like?]: https://api.rubyonrails.org/classes/Object.html#method-i-acts_like-3F + ### `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`][Object#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`: @@ -304,7 +320,7 @@ 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`][Array#to_param] calls `to_param` on the elements and joins the result with "/": ```ruby [0, true, String].to_param # => "0/true/String" @@ -330,9 +346,12 @@ WARNING. Controllers need to be aware of any redefinition of `to_param` because NOTE: Defined in `active_support/core_ext/object/to_param.rb`. +[Array#to_param]: https://api.rubyonrails.org/classes/Array.html#method-i-to_param +[Object#to_param]: https://api.rubyonrails.org/classes/Object.html#method-i-to_param + ### `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 +The [`to_query`][Object#to_query] method constructs a query string that associates a given `key` with the return value of `to_param`. For example, with the following `to_param` definition: ```ruby class User @@ -370,7 +389,7 @@ Hashes also respond to `to_query` but with a different signature. If no argument {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`][Hash#to_query] accepts an optional namespace for the keys: ```ruby {id: 89, name: "John Smith"}.to_query('user') @@ -379,9 +398,12 @@ The method `Hash#to_query` accepts an optional namespace for the keys: NOTE: Defined in `active_support/core_ext/object/to_query.rb`. +[Hash#to_query]: https://api.rubyonrails.org/classes/Hash.html#method-i-to_query +[Object#to_query]: https://api.rubyonrails.org/classes/Object.html#method-i-to_query + ### `with_options` -The method `with_options` provides a way to factor out common options in a series of method calls. +The method [`with_options`][Object#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: @@ -420,6 +442,8 @@ TIP: Since `with_options` forwards calls to its receiver they can be nested. Eac NOTE: Defined in `active_support/core_ext/object/with_options.rb`. +[Object#with_options]: https://api.rubyonrails.org/classes/Object.html#method-i-with_options + ### JSON support Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash`, `OrderedHash` and `Process::Status` need special handling in order to provide a proper JSON representation. @@ -432,7 +456,7 @@ Active Support provides several methods to ease access to instance variables. #### `instance_values` -The method `instance_values` returns a hash that maps instance variable names without "@" to their +The method [`instance_values`][Object#instance_values] returns a hash that maps instance variable names without "@" to their corresponding values. Keys are strings: ```ruby @@ -447,9 +471,11 @@ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`. +[Object#instance_values]: https://api.rubyonrails.org/classes/Object.html#method-i-instance_values + #### `instance_variable_names` -The method `instance_variable_names` returns an array. Each name includes the "@" sign. +The method [`instance_variable_names`][Object#instance_variable_names] returns an array. Each name includes the "@" sign. ```ruby class C @@ -463,15 +489,17 @@ C.new(0, 1).instance_variable_names # => ["@x", "@y"] NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`. +[Object#instance_variable_names]: https://api.rubyonrails.org/classes/Object.html#method-i-instance_variable_names + ### Silencing Warnings 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`][Kernel#silence_warnings] and [`enable_warnings`][Kernel#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 } ``` -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 not captured: +Silencing exceptions is also possible with [`suppress`][Kernel#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 not captured: ```ruby # If the user is locked, the increment is lost, no big deal. @@ -482,9 +510,13 @@ end NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`. +[Kernel#enable_warnings]: https://api.rubyonrails.org/classes/Kernel.html#method-i-enable_warnings +[Kernel#silence_warnings]: https://api.rubyonrails.org/classes/Kernel.html#method-i-silence_warnings +[Kernel#suppress]: https://api.rubyonrails.org/classes/Kernel.html#method-i-suppress + ### `in?` -The predicate `in?` tests if an object is included in another object. An `ArgumentError` exception will be raised if the argument passed does not respond to `include?`. +The predicate [`in?`][Object#in?] tests if an object is included in another object. An `ArgumentError` exception will be raised if the argument passed does not respond to `include?`. Examples of `in?`: @@ -497,6 +529,8 @@ Examples of `in?`: NOTE: Defined in `active_support/core_ext/object/inclusion.rb`. +[Object#in?]: https://api.rubyonrails.org/classes/Object.html#method-i-in-3F + Extensions to `Module` ---------------------- @@ -504,7 +538,7 @@ Extensions to `Module` #### `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 (one mnemonic is that they go in the same order as if you did an assignment): +Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods all defined for you by using [`alias_attribute`][Module#alias_attribute]. As in other aliasing methods, the new name is the first argument, and the old name is the second (one mnemonic is that they go in the same order as if you did an assignment): ```ruby class User < ApplicationRecord @@ -516,13 +550,15 @@ end NOTE: Defined in `active_support/core_ext/module/aliasing.rb`. +[Module#alias_attribute]: https://api.rubyonrails.org/classes/Module.html#method-i-alias_attribute + #### 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`][Module#attr_internal_reader], [`attr_internal_writer`][Module#attr_internal_writer], and [`attr_internal_accessor`][Module#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`][Module#attr_internal] is a synonym for `attr_internal_accessor`: ```ruby # library @@ -554,9 +590,14 @@ end NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`. +[Module#attr_internal]: https://api.rubyonrails.org/classes/Module.html#method-i-attr_internal +[Module#attr_internal_accessor]: https://api.rubyonrails.org/classes/Module.html#method-i-attr_internal_accessor +[Module#attr_internal_reader]: https://api.rubyonrails.org/classes/Module.html#method-i-attr_internal_reader +[Module#attr_internal_writer]: https://api.rubyonrails.org/classes/Module.html#method-i-attr_internal_writer + #### Module Attributes -The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are the same as the `cattr_*` macros defined for class. In fact, the `cattr_*` macros are just aliases for the `mattr_*` macros. Check [Class Attributes](#class-attributes). +The macros [`mattr_reader`][Module#mattr_reader], [`mattr_writer`][Module#mattr_writer], and [`mattr_accessor`][Module#mattr_accessor] are the same as the `cattr_*` macros defined for class. In fact, the `cattr_*` macros are just aliases for the `mattr_*` macros. Check [Class Attributes](#class-attributes). For example, the dependencies mechanism uses them: @@ -579,11 +620,15 @@ end NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`. +[Module#mattr_accessor]: https://api.rubyonrails.org/classes/Module.html#method-i-mattr_accessor +[Module#mattr_reader]: https://api.rubyonrails.org/classes/Module.html#method-i-mattr_reader +[Module#mattr_writer]: https://api.rubyonrails.org/classes/Module.html#method-i-mattr_writer + ### Parents #### `module_parent` -The `module_parent` method on a nested named module returns the module that contains its corresponding constant: +The [`module_parent`][Module#module_parent] method on a nested named module returns the module that contains its corresponding constant: ```ruby module X @@ -604,9 +649,11 @@ WARNING: Note that in that case `module_parent_name` returns `nil`. NOTE: Defined in `active_support/core_ext/module/introspection.rb`. +[Module#module_parent]: https://api.rubyonrails.org/classes/Module.html#method-i-module_parent + #### `module_parent_name` -The `module_parent_name` method on a nested named module returns the fully qualified name of the module that contains its corresponding constant: +The [`module_parent_name`][Module#module_parent_name] method on a nested named module returns the fully qualified name of the module that contains its corresponding constant: ```ruby module X @@ -627,9 +674,11 @@ WARNING: Note that in that case `module_parent` returns `Object`. NOTE: Defined in `active_support/core_ext/module/introspection.rb`. +[Module#module_parent_name]: https://api.rubyonrails.org/classes/Module.html#method-i-module_parent_name + #### `module_parents` -The method `module_parents` calls `module_parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top: +The method [`module_parents`][Module#module_parents] calls `module_parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top: ```ruby module X @@ -646,6 +695,8 @@ M.module_parents # => [X::Y, X, Object] NOTE: Defined in `active_support/core_ext/module/introspection.rb`. +[Module#module_parents]: https://api.rubyonrails.org/classes/Module.html#method-i-module_parents + ### Anonymous A module may or may not have a name: @@ -661,7 +712,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?`][Module#anonymous?]: ```ruby module M @@ -686,11 +737,13 @@ though an anonymous module is unreachable by definition. NOTE: Defined in `active_support/core_ext/module/anonymous.rb`. +[Module#anonymous?]: https://api.rubyonrails.org/classes/Module.html#method-i-anonymous-3F + ### Method Delegation #### `delegate` -The macro `delegate` offers an easy way to forward methods. +The macro [`delegate`][Module#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: @@ -780,10 +833,12 @@ The delegated methods are public by default. Pass `private: true` to change that NOTE: Defined in `active_support/core_ext/module/delegation.rb` +[Module#delegate]: https://api.rubyonrails.org/classes/Module.html#method-i-delegate + #### `delegate_missing_to` Imagine you would like to delegate everything missing from the `User` object, -to the `Profile` one. The `delegate_missing_to` macro lets you implement this +to the `Profile` one. The [`delegate_missing_to`][Module#delegate_missing_to] macro lets you implement this in a breeze: ```ruby @@ -799,18 +854,23 @@ methods, constants, etc. Only the public methods of the target are delegated. NOTE: Defined in `active_support/core_ext/module/delegation.rb`. +[Module#delegate_missing_to]: https://api.rubyonrails.org/classes/Module.html#method-i-delegate_missing_to + ### 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. -The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. +The method [`redefine_method`][Module#redefine_method] prevents such a potential warning, removing the existing method before if needed. -You can also use `silence_redefinition_of_method` if you need to define +You can also use [`silence_redefinition_of_method`][Module#silence_redefinition_of_method] if you need to define the replacement method yourself (because you're using `delegate`, for example). NOTE: Defined in `active_support/core_ext/module/redefine_method.rb`. +[Module#redefine_method]: https://api.rubyonrails.org/classes/Module.html#method-i-redefine_method +[Module#silence_redefinition_of_method]: https://api.rubyonrails.org/classes/Module.html#method-i-silence_redefinition_of_method + Extensions to `Class` --------------------- @@ -818,7 +878,7 @@ Extensions to `Class` #### `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`][Class#class_attribute] declares one or more inheritable class attributes that can be overridden at any level down the hierarchy. ```ruby class A @@ -898,9 +958,11 @@ If you do not want the instance predicate, pass `instance_predicate: false` and NOTE: Defined in `active_support/core_ext/class/attribute.rb`. +[Class#class_attribute]: https://api.rubyonrails.org/classes/Class.html#method-i-class_attribute + #### `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`][Module#cattr_reader], [`cattr_writer`][Module#cattr_writer], and [`cattr_accessor`][Module#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 @@ -949,11 +1011,15 @@ A model may find it useful to set `:instance_accessor` to `false` as a way to pr NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`. +[Module#cattr_accessor]: https://api.rubyonrails.org/classes/Module.html#method-i-cattr_accessor +[Module#cattr_reader]: https://api.rubyonrails.org/classes/Module.html#method-i-cattr_reader +[Module#cattr_writer]: https://api.rubyonrails.org/classes/Module.html#method-i-cattr_writer + ### Subclasses & Descendants #### `subclasses` -The `subclasses` method returns the subclasses of the receiver: +The [`subclasses`][Class#subclasses] method returns the subclasses of the receiver: ```ruby class C; end @@ -973,9 +1039,11 @@ The order in which these classes are returned is unspecified. NOTE: Defined in `active_support/core_ext/class/subclasses.rb`. +[Class#subclasses]: https://api.rubyonrails.org/classes/Class.html#method-i-subclasses + #### `descendants` -The `descendants` method returns all classes that are `<` than its receiver: +The [`descendants`][Class#descendants] method returns all classes that are `<` than its receiver: ```ruby class C; end @@ -995,6 +1063,8 @@ The order in which these classes are returned is unspecified. NOTE: Defined in `active_support/core_ext/class/subclasses.rb`. +[Class#descendants]: https://api.rubyonrails.org/classes/Class.html#method-i-descendants + Extensions to `String` ---------------------- @@ -1014,7 +1084,7 @@ Strings are considered to be _unsafe_ 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`][String#html_safe] method: ```ruby s = "".html_safe @@ -1049,7 +1119,7 @@ These methods should not be used in ordinary views. Unsafe values are automatica <%= @review.title %> <%# fine, 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 %> @@ -1071,6 +1141,9 @@ end NOTE: Defined in `active_support/core_ext/string/output_safety.rb`. +[`raw`]: https://api.rubyonrails.org/classes/ActionView/Helpers/OutputSafetyHelper.html#method-i-raw +[String#html_safe]: https://api.rubyonrails.org/classes/String.html#method-i-html_safe + #### 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. @@ -1089,7 +1162,7 @@ Calling `dup` or `clone` on safe strings yields safe strings. ### `remove` -The method `remove` will remove all occurrences of the pattern: +The method [`remove`][String#remove] will remove all occurrences of the pattern: ```ruby "Hello World".remove(/Hello /) # => "World" @@ -1099,9 +1172,11 @@ There's also the destructive version `String#remove!`. NOTE: Defined in `active_support/core_ext/string/filters.rb`. +[String#remove]: https://api.rubyonrails.org/classes/String.html#method-i-remove + ### `squish` -The method `squish` strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each: +The method [`squish`][String#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" @@ -1113,9 +1188,11 @@ Note that it handles both ASCII and Unicode whitespace. NOTE: Defined in `active_support/core_ext/string/filters.rb`. +[String#squish]: https://api.rubyonrails.org/classes/String.html#method-i-squish + ### `truncate` -The method `truncate` returns a copy of its receiver truncated after a given `length`: +The method [`truncate`][String#truncate] returns a copy of its receiver truncated after a given `length`: ```ruby "Oh dear! Oh dear! I shall be late!".truncate(20) @@ -1151,9 +1228,11 @@ In above examples "dear" gets cut first, but then `:separator` prevents it. NOTE: Defined in `active_support/core_ext/string/filters.rb`. +[String#truncate]: https://api.rubyonrails.org/classes/String.html#method-i-truncate + ### `truncate_bytes` -The method `truncate_bytes` returns a copy of its receiver truncated to at most `bytesize` bytes: +The method [`truncate_bytes`][String#truncate_bytes] returns a copy of its receiver truncated to at most `bytesize` bytes: ```ruby "👍👍👍👍".truncate_bytes(15) @@ -1169,9 +1248,11 @@ Ellipsis can be customized with the `:omission` option: NOTE: Defined in `active_support/core_ext/string/filters.rb`. +[String#truncate_bytes]: https://api.rubyonrails.org/classes/String.html#method-i-truncate_bytes + ### `truncate_words` -The method `truncate_words` returns a copy of its receiver truncated after a given number of words: +The method [`truncate_words`][String#truncate_words] returns a copy of its receiver truncated after a given number of words: ```ruby "Oh dear! Oh dear! I shall be late!".truncate_words(4) @@ -1201,9 +1282,11 @@ The option `:separator` can be a regexp: NOTE: Defined in `active_support/core_ext/string/filters.rb`. +[String#truncate_words]: https://api.rubyonrails.org/classes/String.html#method-i-truncate_words + ### `inquiry` -The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier. +The [`inquiry`][String#inquiry] method converts a string into a `StringInquirer` object making equality checks prettier. ```ruby "production".inquiry.production? # => true @@ -1212,6 +1295,8 @@ The `inquiry` method converts a string into a `StringInquirer` object making equ NOTE: Defined in `active_support/core_ext/string/inquiry.rb`. +[String#inquiry]: https://api.rubyonrails.org/classes/String.html#method-i-inquiry + ### `starts_with?` and `ends_with?` Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`: @@ -1225,7 +1310,7 @@ NOTE: Defined in `active_support/core_ext/string/starts_ends_with.rb`. ### `strip_heredoc` -The method `strip_heredoc` strips indentation in heredocs. +The method [`strip_heredoc`][String#strip_heredoc] strips indentation in heredocs. For example in @@ -1248,9 +1333,11 @@ that amount of leading whitespace. NOTE: Defined in `active_support/core_ext/string/strip.rb`. +[String#strip_heredoc]: https://api.rubyonrails.org/classes/String.html#method-i-strip_heredoc + ### `indent` -Indents the lines in the receiver: +The [`indent`][String#indent] method indents the lines in the receiver: ```ruby < " foo\n \n bar" ``` -The `indent!` method performs indentation in-place. +The [`indent!`][String#indent!] method performs indentation in-place. NOTE: Defined in `active_support/core_ext/string/indent.rb`. +[String#indent!]: https://api.rubyonrails.org/classes/String.html#method-i-indent-21 +[String#indent]: https://api.rubyonrails.org/classes/String.html#method-i-indent + ### Access #### `at(position)` -Returns the character of the string at position `position`: +The [`at`][String#at] method returns the character of the string at position `position`: ```ruby "hello".at(0) # => "h" @@ -1300,9 +1390,11 @@ Returns the character of the string at position `position`: NOTE: Defined in `active_support/core_ext/string/access.rb`. +[String#at]: https://api.rubyonrails.org/classes/String.html#method-i-at + #### `from(position)` -Returns the substring of the string starting at position `position`: +The [`from`][String#from] method returns the substring of the string starting at position `position`: ```ruby "hello".from(0) # => "hello" @@ -1313,9 +1405,11 @@ Returns the substring of the string starting at position `position`: NOTE: Defined in `active_support/core_ext/string/access.rb`. +[String#from]: https://api.rubyonrails.org/classes/String.html#method-i-from + #### `to(position)` -Returns the substring of the string up to position `position`: +The [`to`][String#to] method returns the substring of the string up to position `position`: ```ruby "hello".to(0) # => "h" @@ -1326,23 +1420,33 @@ Returns the substring of the string up to position `position`: NOTE: Defined in `active_support/core_ext/string/access.rb`. +[String#to]: https://api.rubyonrails.org/classes/String.html#method-i-to + #### `first(limit = 1)` +The [`first`][String#first] method returns a substring containing the first `limit` characters of the string. + 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`. +[String#first]: https://api.rubyonrails.org/classes/String.html#method-i-first + #### `last(limit = 1)` +The [`last`][String#last] method returns a substring containing the last `limit` characters of the string. + 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`. +[String#last]: https://api.rubyonrails.org/classes/String.html#method-i-last + ### Inflections #### `pluralize` -The method `pluralize` returns the plural of its receiver: +The method [`pluralize`][String#pluralize] returns the plural of its receiver: ```ruby "table".pluralize # => "tables" @@ -1372,9 +1476,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#pluralize]: https://api.rubyonrails.org/classes/String.html#method-i-pluralize + #### `singularize` -The inverse of `pluralize`: +The [`singularize`][String#singularize] method is the inverse of `pluralize`: ```ruby "tables".singularize # => "table" @@ -1395,9 +1501,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#singularize]: https://api.rubyonrails.org/classes/String.html#method-i-singularize + #### `camelize` -The method `camelize` returns its receiver in camel case: +The method [`camelize`][String#camelize] returns its receiver in camel case: ```ruby "product".camelize # => "Product" @@ -1439,13 +1547,16 @@ end "SSLError".underscore.camelize # => "SSLError" ``` -`camelize` is aliased to `camelcase`. +`camelize` is aliased to [`camelcase`][String#camelcase]. NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#camelcase]: https://api.rubyonrails.org/classes/String.html#method-i-camelcase +[String#camelize]: https://api.rubyonrails.org/classes/String.html#method-i-camelize + #### `underscore` -The method `underscore` goes the other way around, from camel case to paths: +The method [`underscore`][String#underscore] goes the other way around, from camel case to paths: ```ruby "Product".underscore # => "product" @@ -1482,22 +1593,27 @@ INFO: As a rule of thumb you can think of `underscore` as the inverse of `cameli NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#underscore]: https://api.rubyonrails.org/classes/String.html#method-i-underscore + #### `titleize` -The method `titleize` capitalizes the words in the receiver: +The method [`titleize`][String#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`][String#titlecase]. NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#titlecase]: https://api.rubyonrails.org/classes/String.html#method-i-titlecase +[String#titleize]: https://api.rubyonrails.org/classes/String.html#method-i-titleize + #### `dasherize` -The method `dasherize` replaces the underscores in the receiver with dashes: +The method [`dasherize`][String#dasherize] replaces the underscores in the receiver with dashes: ```ruby "name".dasherize # => "name" @@ -1516,9 +1632,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#dasherize]: https://api.rubyonrails.org/classes/String.html#method-i-dasherize + #### `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`][String#demodulize] returns the very constant name, that is, the rightmost part of it: ```ruby "Product".demodulize # => "Product" @@ -1544,9 +1662,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#demodulize]: https://api.rubyonrails.org/classes/String.html#method-i-demodulize + #### `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`][String#deconstantize] removes the rightmost segment, generally leaving the name of the constant's container: ```ruby "Product".deconstantize # => "" @@ -1556,9 +1676,11 @@ Given a string with a qualified constant reference expression, `deconstantize` r NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#deconstantize]: https://api.rubyonrails.org/classes/String.html#method-i-deconstantize + #### `parameterize` -The method `parameterize` normalizes its receiver in a way that can be used in pretty URLs. +The method [`parameterize`][String#parameterize] normalizes its receiver in a way that can be used in pretty URLs. ```ruby "John Smith".parameterize # => "john-smith" @@ -1581,9 +1703,11 @@ To use a custom separator, override the `separator` argument. NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#parameterize]: https://api.rubyonrails.org/classes/String.html#method-i-parameterize + #### `tableize` -The method `tableize` is `underscore` followed by `pluralize`. +The method [`tableize`][String#tableize] is `underscore` followed by `pluralize`. ```ruby "Person".tableize # => "people" @@ -1595,9 +1719,11 @@ As a rule of thumb, `tableize` returns the table name that corresponds to a give NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#tableize]: https://api.rubyonrails.org/classes/String.html#method-i-tableize + #### `classify` -The method `classify` is the inverse of `tableize`. It gives you the class name corresponding to a table name: +The method [`classify`][String#classify] is the inverse of `tableize`. It gives you the class name corresponding to a table name: ```ruby "people".classify # => "Person" @@ -1615,9 +1741,11 @@ Note that `classify` returns a class name as a string. You can get the actual cl NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#classify]: https://api.rubyonrails.org/classes/String.html#method-i-classify + #### `constantize` -The method `constantize` resolves the constant reference expression in its receiver: +The method [`constantize`][String#constantize] resolves the constant reference expression in its receiver: ```ruby "Integer".constantize # => Integer @@ -1658,9 +1786,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#constantize]: https://api.rubyonrails.org/classes/String.html#method-i-constantize + #### `humanize` -The method `humanize` tweaks an attribute name for display to end users. +The method [`humanize`][String#humanize] tweaks an attribute name for display to end users. Specifically, it performs these transformations: @@ -1706,9 +1836,11 @@ end NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#humanize]: https://api.rubyonrails.org/classes/String.html#method-i-humanize + #### `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`][String#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" @@ -1731,11 +1863,13 @@ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key NOTE: Defined in `active_support/core_ext/string/inflections.rb`. +[String#foreign_key]: https://api.rubyonrails.org/classes/String.html#method-i-foreign_key + ### Conversions #### `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`][String#to_date], [`to_time`][String#to_time], and [`to_datetime`][String#to_datetime] are basically convenience wrappers around `Date._parse`: ```ruby "2010-07-27".to_date # => Tue, 27 Jul 2010 @@ -1758,6 +1892,10 @@ INFO: The three of them return `nil` for blank receivers. NOTE: Defined in `active_support/core_ext/string/conversions.rb`. +[String#to_date]: https://api.rubyonrails.org/classes/String.html#method-i-to_date +[String#to_datetime]: https://api.rubyonrails.org/classes/String.html#method-i-to_datetime +[String#to_time]: https://api.rubyonrails.org/classes/String.html#method-i-to_time + Extensions to `Symbol` ---------------------- @@ -1779,15 +1917,13 @@ Extensions to `Numeric` All numbers respond to these methods: -```ruby -bytes -kilobytes -megabytes -gigabytes -terabytes -petabytes -exabytes -``` +* [`bytes`][Numeric#bytes] +* [`kilobytes`][Numeric#kilobytes] +* [`megabytes`][Numeric#megabytes] +* [`gigabytes`][Numeric#gigabytes] +* [`terabytes`][Numeric#terabytes] +* [`petabytes`][Numeric#petabytes] +* [`exabytes`][Numeric#exabytes] They return the corresponding amount of bytes, using a conversion factor of 1024: @@ -1806,28 +1942,53 @@ Singular forms are aliased so you are able to say: NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`. +[Numeric#bytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-bytes +[Numeric#exabytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-exabytes +[Numeric#gigabytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-gigabytes +[Numeric#kilobytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-kilobytes +[Numeric#megabytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-megabytes +[Numeric#petabytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-petabytes +[Numeric#terabytes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-terabytes + ### Time -Enables the use of time calculations and declarations, like `45.minutes + 2.hours + 4.weeks`. +The following methods: -These methods use Time#advance for precise date calculations when using from_now, ago, etc. -as well as adding or subtracting their results from a Time object. For example: +* [`seconds`][Numeric#seconds] +* [`minutes`][Numeric#minutes] +* [`hours`][Numeric#hours] +* [`days`][Numeric#days] +* [`weeks`][Numeric#weeks] +* [`fortnights`][Numeric#fortnights] + +enable time declarations and calculations, like `45.minutes + 2.hours + 4.weeks`. Their return values can also be added to or subtracted from Time objects. + +These methods can be combined with [`from_now`][Duration#from_now], [`ago`][Duration#ago], etc, for precise date calculations. For example: ```ruby -# equivalent to Time.current.advance(months: 1) -1.month.from_now +# equivalent to Time.current.advance(days: 1) +1.day.from_now # equivalent to Time.current.advance(weeks: 2) 2.weeks.from_now -# equivalent to Time.current.advance(months: 4, weeks: 5) -(4.months + 5.weeks).from_now +# equivalent to Time.current.advance(days: 4, weeks: 5) +(4.days + 5.weeks).from_now ``` WARNING. For other durations please refer to the time extensions to `Integer`. NOTE: Defined in `active_support/core_ext/numeric/time.rb`. +[Duration#ago]: https://api.rubyonrails.org/classes/ActiveSupport/Duration.html#method-i-ago +[Duration#from_now]: https://api.rubyonrails.org/classes/ActiveSupport/Duration.html#method-i-from_now +[Numeric#days]: https://api.rubyonrails.org/classes/Numeric.html#method-i-days +[Numeric#fortnights]: https://api.rubyonrails.org/classes/Numeric.html#method-i-fortnights +[Numeric#hours]: https://api.rubyonrails.org/classes/Numeric.html#method-i-hours +[Numeric#minutes]: https://api.rubyonrails.org/classes/Numeric.html#method-i-minutes +[Numeric#seconds]: https://api.rubyonrails.org/classes/Numeric.html#method-i-seconds +[Numeric#weeks]: https://api.rubyonrails.org/classes/Numeric.html#method-i-weeks + ### Formatting Enables the formatting of numbers in a variety of ways. @@ -1922,7 +2083,7 @@ Extensions to `Integer` ### `multiple_of?` -The method `multiple_of?` tests whether an integer is multiple of the argument: +The method [`multiple_of?`][Integer#multiple_of?] tests whether an integer is multiple of the argument: ```ruby 2.multiple_of?(1) # => true @@ -1931,9 +2092,11 @@ The method `multiple_of?` tests whether an integer is multiple of the argument: NOTE: Defined in `active_support/core_ext/integer/multiple.rb`. +[Integer#multiple_of?]: https://api.rubyonrails.org/classes/Integer.html#method-i-multiple_of-3F + ### `ordinal` -The method `ordinal` returns the ordinal suffix string corresponding to the receiver integer: +The method [`ordinal`][Integer#ordinal] returns the ordinal suffix string corresponding to the receiver integer: ```ruby 1.ordinal # => "st" @@ -1946,9 +2109,11 @@ The method `ordinal` returns the ordinal suffix string corresponding to the rece NOTE: Defined in `active_support/core_ext/integer/inflections.rb`. +[Integer#ordinal]: https://api.rubyonrails.org/classes/Integer.html#method-i-ordinal + ### `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`][Integer#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" @@ -1961,12 +2126,18 @@ The method `ordinalize` returns the ordinal string corresponding to the receiver NOTE: Defined in `active_support/core_ext/integer/inflections.rb`. +[Integer#ordinalize]: https://api.rubyonrails.org/classes/Integer.html#method-i-ordinalize + ### Time -Enables the use of time calculations and declarations, like `4.months + 5.years`. +The following methods: -These methods use Time#advance for precise date calculations when using from_now, ago, etc. -as well as adding or subtracting their results from a Time object. For example: +* [`months`][Integer#months] +* [`years`][Integer#years] + +enable time declarations and calculations, like `4.months + 5.years`. Their return values can also be added to or subtracted from Time objects. + +These methods can be combined with [`from_now`][Duration#from_now], [`ago`][Duration#ago], etc, for precise date calculations. For example: ```ruby # equivalent to Time.current.advance(months: 1) @@ -1983,6 +2154,9 @@ WARNING. For other durations please refer to the time extensions to `Numeric`. NOTE: Defined in `active_support/core_ext/integer/time.rb`. +[Integer#months]: https://api.rubyonrails.org/classes/Integer.html#method-i-months +[Integer#years]: https://api.rubyonrails.org/classes/Integer.html#method-i-years + Extensions to `BigDecimal` -------------------------- ### `to_s` @@ -2010,7 +2184,7 @@ Extensions to `Enumerable` ### `sum` -The method `sum` adds the elements of an enumerable: +The method [`sum`][Enumerable#sum] adds the elements of an enumerable: ```ruby [1, 2, 3].sum # => 6 @@ -2047,9 +2221,11 @@ The sum of an empty receiver can be customized in this form as well: NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#sum]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-sum + ### `index_by` -The method `index_by` generates a hash with the elements of an enumerable indexed by some key. +The method [`index_by`][Enumerable#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: @@ -2062,9 +2238,11 @@ WARNING. Keys should normally be unique. If the block returns the same value for NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#index_by]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-index_by + ### `index_with` -The method `index_with` generates a hash with the elements of an enumerable as keys. The value +The method [`index_with`][Enumerable#index_with] generates a hash with the elements of an enumerable as keys. The value is either a passed default or returned in a block. ```ruby @@ -2079,9 +2257,11 @@ WEEKDAYS.index_with(Interval.all_day) NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#index_with]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-index_with + ### `many?` -The method `many?` is shorthand for `collection.size > 1`: +The method [`many?`][Enumerable#many?] is shorthand for `collection.size > 1`: ```erb <% if pages.many? %> @@ -2097,9 +2277,11 @@ If an optional block is given, `many?` only takes into account those elements th NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#many?]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-many-3F + ### `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?`][Enumerable#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) @@ -2107,9 +2289,11 @@ to_visit << node if visited.exclude?(node) NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#exclude?]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-exclude-3F + ### `including` -The method `including` returns a new enumerable that includes the passed elements: +The method [`including`][Enumerable#including] returns a new enumerable that includes the passed elements: ```ruby [ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] @@ -2118,22 +2302,27 @@ The method `including` returns a new enumerable that includes the passed element NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#including]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-including + ### `excluding` -The method `excluding` returns a copy of an enumerable with the specified elements +The method [`excluding`][Enumerable#excluding] returns a copy of an enumerable with the specified elements removed: ```ruby ["David", "Rafael", "Aaron", "Todd"].excluding("Aaron", "Todd") # => ["David", "Rafael"] ``` -`excluding` is aliased to `without`. +`excluding` is aliased to [`without`][Enumerable#without]. NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#excluding]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-excluding +[Enumerable#without]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-without + ### `pluck` -The method `pluck` extracts the given key from each element: +The method [`pluck`][Enumerable#pluck] extracts the given key from each element: ```ruby [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pluck(:name) # => ["David", "Rafael", "Aaron"] @@ -2142,9 +2331,11 @@ The method `pluck` extracts the given key from each element: NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#pluck]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-pluck + ### `pick` -The method `pick` extracts the given key from the first element: +The method [`pick`][Enumerable#pick] extracts the given key from the first element: ```ruby [{ name: "David" }, { name: "Rafael" }, { name: "Aaron" }].pick(:name) # => "David" @@ -2153,19 +2344,21 @@ The method `pick` extracts the given key from the first element: NOTE: Defined in `active_support/core_ext/enumerable.rb`. +[Enumerable#pick]: https://api.rubyonrails.org/classes/Enumerable.html#method-i-pick + 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`][Array#to] returns the subarray of elements up to the one at the passed index: ```ruby %w(a b c d).to(2) # => ["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`][Array#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) # => ["c", "d"] @@ -2173,14 +2366,14 @@ Similarly, `from` returns the tail from the element at the passed index to the e [].from(0) # => [] ``` -The method `including` returns a new array that includes the passed elements: +The method [`including`][Array#including] returns a new array that includes the passed elements: ```ruby [ 1, 2, 3 ].including(4, 5) # => [ 1, 2, 3, 4, 5 ] [ [ 0, 1 ] ].including([ [ 1, 0 ] ]) # => [ [ 0, 1 ], [ 1, 0 ] ] ``` -The method `excluding` returns a copy of the Array excluding the specified elements. +The method [`excluding`][Array#excluding] returns a copy of the Array excluding the specified elements. This is an optimization of `Enumerable#excluding` that uses `Array#-` instead of `Array#reject` for performance reasons. @@ -2189,7 +2382,7 @@ instead of `Array#reject` for performance reasons. [ [ 0, 1 ], [ 1, 0 ] ].excluding([ [ 1, 0 ] ]) # => [ [ 0, 1 ] ] ``` -The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element, as do `second_to_last` and `third_to_last` (`first` and `last` are built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available. +The methods [`second`][Array#second], [`third`][Array#third], [`fourth`][Array#fourth], and [`fifth`][Array#fifth] return the corresponding element, as do [`second_to_last`][Array#second_to_last] and [`third_to_last`][Array#third_to_last] (`first` and `last` are built-in). Thanks to social wisdom and positive constructiveness all around, [`forty_two`][Array#forty_two] is also available. ```ruby %w(a b c d).third # => "c" @@ -2198,9 +2391,21 @@ The methods `second`, `third`, `fourth`, and `fifth` return the corresponding el NOTE: Defined in `active_support/core_ext/array/access.rb`. +[Array#excluding]: https://api.rubyonrails.org/classes/Array.html#method-i-excluding +[Array#fifth]: https://api.rubyonrails.org/classes/Array.html#method-i-fifth +[Array#forty_two]: https://api.rubyonrails.org/classes/Array.html#method-i-forty_two +[Array#fourth]: https://api.rubyonrails.org/classes/Array.html#method-i-fourth +[Array#from]: https://api.rubyonrails.org/classes/Array.html#method-i-from +[Array#including]: https://api.rubyonrails.org/classes/Array.html#method-i-including +[Array#second]: https://api.rubyonrails.org/classes/Array.html#method-i-second +[Array#second_to_last]: https://api.rubyonrails.org/classes/Array.html#method-i-second_to_last +[Array#third]: https://api.rubyonrails.org/classes/Array.html#method-i-third +[Array#third_to_last]: https://api.rubyonrails.org/classes/Array.html#method-i-third_to_last +[Array#to]: https://api.rubyonrails.org/classes/Array.html#method-i-to + ### Extracting -The method `extract!` removes and returns the elements for which the block returns a true value. +The method [`extract!`][Array#extract!] removes and returns the elements for which the block returns a true value. If no block is given, an Enumerator is returned instead. ```ruby @@ -2211,6 +2416,8 @@ numbers # => [0, 2, 4, 6, 8] NOTE: Defined in `active_support/core_ext/array/extract.rb`. +[Array#extract!]: https://api.rubyonrails.org/classes/Array.html#method-i-extract-21 + ### 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: @@ -2223,7 +2430,7 @@ 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!`][Array#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: @@ -2239,11 +2446,13 @@ This method receives an arbitrary number of action names, and an optional hash o NOTE: Defined in `active_support/core_ext/array/extract_options.rb`. +[Array#extract_options!]: https://api.rubyonrails.org/classes/Array.html#method-i-extract_options-21 + ### Conversions #### `to_sentence` -The method `to_sentence` turns an array into a string containing a sentence that enumerates its items: +The method [`to_sentence`][Array#to_sentence] turns an array into a string containing a sentence that enumerates its items: ```ruby %w().to_sentence # => "" @@ -2268,9 +2477,11 @@ The defaults for these options can be localized, their keys are: NOTE: Defined in `active_support/core_ext/array/conversions.rb`. +[Array#to_sentence]: https://api.rubyonrails.org/classes/Array.html#method-i-to_sentence + #### `to_formatted_s` -The method `to_formatted_s` acts like `to_s` by default. +The method [`to_formatted_s`][Array#to_formatted_s] acts like `to_s` by default. If the array contains items that respond to `id`, however, the symbol `:db` may be passed as argument. That's typically used with @@ -2286,9 +2497,11 @@ Integers in the example above are supposed to come from the respective calls to NOTE: Defined in `active_support/core_ext/array/conversions.rb`. +[Array#to_formatted_s]: https://api.rubyonrails.org/classes/Array.html#method-i-to_formatted_s + #### `to_xml` -The method `to_xml` returns a string containing an XML representation of its receiver: +The method [`to_xml`][Array#to_xml] returns a string containing an XML representation of its receiver: ```ruby Contributor.limit(2).order(:rank).to_xml @@ -2387,9 +2600,11 @@ Contributor.limit(2).order(:rank).to_xml(skip_types: true) NOTE: Defined in `active_support/core_ext/array/conversions.rb`. +[Array#to_xml]: https://api.rubyonrails.org/classes/Array.html#method-i-to_xml + ### Wrapping -The method `Array.wrap` wraps its argument in an array unless it is already an array (or array-like). +The method [`Array.wrap`][Array.wrap] wraps its argument in an array unless it is already an array (or array-like). Specifically: @@ -2424,9 +2639,11 @@ There's also a related idiom that uses the splat operator: NOTE: Defined in `active_support/core_ext/array/wrap.rb`. +[Array.wrap]: https://api.rubyonrails.org/classes/Array.html#method-c-wrap + ### Duplicating -The method `Array#deep_dup` duplicates itself and all objects inside +The method [`Array#deep_dup`][Array#deep_dup] duplicates itself and all objects inside recursively with the Active Support method `Object#deep_dup`. It works like `Array#map`, sending `deep_dup` method to each object inside. ```ruby @@ -2438,11 +2655,13 @@ array[1][2] == nil # => true NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`. +[Array#deep_dup]: https://api.rubyonrails.org/classes/Array.html#method-i-deep_dup + ### Grouping #### `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`][Array#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]] @@ -2476,9 +2695,11 @@ As a consequence `false` can't be used as a padding value. NOTE: Defined in `active_support/core_ext/array/grouping.rb`. +[Array#in_groups_of]: https://api.rubyonrails.org/classes/Array.html#method-i-in_groups_of + #### `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`][Array#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) @@ -2514,9 +2735,11 @@ As a consequence `false` can't be used as a padding value. NOTE: Defined in `active_support/core_ext/array/grouping.rb`. +[Array#in_groups]: https://api.rubyonrails.org/classes/Array.html#method-i-in_groups + #### `split(value = nil)` -The method `split` divides an array by a separator and returns the resulting chunks. +The method [`split`][Array#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: @@ -2536,6 +2759,8 @@ TIP: Observe in the previous example that consecutive separators result in empty NOTE: Defined in `active_support/core_ext/array/grouping.rb`. +[Array#split]: https://api.rubyonrails.org/classes/Array.html#method-i-split + Extensions to `Hash` -------------------- @@ -2543,7 +2768,7 @@ Extensions to `Hash` #### `to_xml` -The method `to_xml` returns a string containing an XML representation of its receiver: +The method [`to_xml`][Hash#to_xml] returns a string containing an XML representation of its receiver: ```ruby {"foo" => 1, "bar" => 2}.to_xml @@ -2587,6 +2812,8 @@ The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can con NOTE: Defined in `active_support/core_ext/hash/conversions.rb`. +[Hash#to_xml]: https://api.rubyonrails.org/classes/Hash.html#method-i-to_xml + ### Merging Ruby has a built-in method `Hash#merge` that merges two hashes: @@ -2606,13 +2833,13 @@ In case of collision the key in the hash of the argument wins in `merge`. You ca options = {length: 30, omission: "..."}.merge(options) ``` -Active Support defines `reverse_merge` in case you prefer this alternative notation: +Active Support defines [`reverse_merge`][Hash#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!`][Hash#reverse_merge!] that performs the merge in place: ```ruby options.reverse_merge!(length: 30, omission: "...") @@ -2622,32 +2849,40 @@ WARNING. Take into account that `reverse_merge!` may change the hash in the call NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`. +[Hash#reverse_merge!]: https://api.rubyonrails.org/classes/Hash.html#method-i-reverse_merge-21 +[Hash#reverse_merge]: https://api.rubyonrails.org/classes/Hash.html#method-i-reverse_merge + #### `reverse_update` -The method `reverse_update` is an alias for `reverse_merge!`, explained above. +The method [`reverse_update`][Hash#reverse_update] is an alias for `reverse_merge!`, explained above. WARNING. Note that `reverse_update` has no bang. NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`. +[Hash#reverse_update]: https://api.rubyonrails.org/classes/Hash.html#method-i-reverse_update + #### `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`][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!`][Hash#deep_merge!] performs a deep merge in place. NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`. +[Hash#deep_merge!]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_merge-21 +[Hash#deep_merge]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_merge + ### Deep duplicating -The method `Hash#deep_dup` duplicates itself and all keys and values +The method [`Hash#deep_dup`][Hash#deep_dup] duplicates itself and all keys and values inside recursively with Active Support method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside. ```ruby @@ -2663,11 +2898,13 @@ hash[:b][:d] == [3, 4] # => true NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`. +[Hash#deep_dup]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_dup + ### Working with Keys #### `except` and `except!` -The method `except` returns a hash with the keys in the argument list removed, if present: +The method [`except`][Hash#except] returns a hash with the keys in the argument list removed, if present: ```ruby {a: 1, b: 2}.except(:a) # => {:b=>2} @@ -2680,13 +2917,16 @@ If the receiver responds to `convert_key`, the method is called on each of the a {a: 1}.with_indifferent_access.except("a") # => {} ``` -There's also the bang variant `except!` that removes keys in place. +There's also the bang variant [`except!`][Hash#except!] that removes keys in place. NOTE: Defined in `active_support/core_ext/hash/except.rb`. +[Hash#except!]: https://api.rubyonrails.org/classes/Hash.html#method-i-except-21 +[Hash#except]: https://api.rubyonrails.org/classes/Hash.html#method-i-except + #### `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`][Hash#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 @@ -2713,9 +2953,9 @@ end 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 place. +There's also the bang variant [`stringify_keys!`][Hash#stringify_keys!] that stringifies keys in place. -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 in it. An example of the result is: +Besides that, one can use [`deep_stringify_keys`][Hash#deep_stringify_keys] and [`deep_stringify_keys!`][Hash#deep_stringify_keys!] to stringify all the keys in the given hash and all the hashes nested in it. An example of the result is: ```ruby {nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys @@ -2724,9 +2964,14 @@ Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to st NOTE: Defined in `active_support/core_ext/hash/keys.rb`. +[Hash#deep_stringify_keys!]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_stringify_keys-21 +[Hash#deep_stringify_keys]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_stringify_keys +[Hash#stringify_keys!]: https://api.rubyonrails.org/classes/Hash.html#method-i-stringify_keys-21 +[Hash#stringify_keys]: https://api.rubyonrails.org/classes/Hash.html#method-i-stringify_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`][Hash#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 @@ -2756,9 +3001,9 @@ end The third line can safely access the `:input` key, and let the user to pass either `:input` or "input". -There's also the bang variant `symbolize_keys!` that symbolizes keys in place. +There's also the bang variant [`symbolize_keys!`][Hash#symbolize_keys!] that symbolizes keys in place. -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 in it. An example of the result is: +Besides that, one can use [`deep_symbolize_keys`][Hash#deep_symbolize_keys] and [`deep_symbolize_keys!`][Hash#deep_symbolize_keys!] to symbolize all the keys in the given hash and all the hashes nested in it. An example of the result is: ```ruby {nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys @@ -2767,15 +3012,23 @@ Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to sy NOTE: Defined in `active_support/core_ext/hash/keys.rb`. +[Hash#deep_symbolize_keys!]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_symbolize_keys-21 +[Hash#deep_symbolize_keys]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_symbolize_keys +[Hash#symbolize_keys!]: https://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys-21 +[Hash#symbolize_keys]: https://api.rubyonrails.org/classes/Hash.html#method-i-symbolize_keys + #### `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`][Hash#to_options] and [`to_options!`][Hash#to_options!] are respectively aliases of `symbolize_keys` and `symbolize_keys!`. NOTE: Defined in `active_support/core_ext/hash/keys.rb`. +[Hash#to_options!]: https://api.rubyonrails.org/classes/Hash.html#method-i-to_options-21 +[Hash#to_options]: https://api.rubyonrails.org/classes/Hash.html#method-i-to_options + #### `assert_valid_keys` -The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that list. If it does `ArgumentError` is raised. +The method [`assert_valid_keys`][Hash#assert_valid_keys] receives an arbitrary number of arguments, and checks whether the receiver has any key outside that list. If it does `ArgumentError` is raised. ```ruby {a: 1}.assert_valid_keys(:a) # passes @@ -2786,11 +3039,13 @@ Active Record does not accept unknown options when building associations, for ex NOTE: Defined in `active_support/core_ext/hash/keys.rb`. +[Hash#assert_valid_keys]: https://api.rubyonrails.org/classes/Hash.html#method-i-assert_valid_keys + ### Working with Values #### `deep_transform_values` and `deep_transform_values!` -The method `deep_transform_values` returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays. +The method [`deep_transform_values`][Hash#deep_transform_values] returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays. ```ruby hash = { person: { name: 'Rob', age: '28' } } @@ -2799,13 +3054,16 @@ hash.deep_transform_values{ |value| value.to_s.upcase } # => {person: {name: "ROB", age: "28"}} ``` -There's also the bang variant `deep_transform_values!` that destructively converts all values by using the block operation. +There's also the bang variant [`deep_transform_values!`][Hash#deep_transform_values!] that destructively converts all values by using the block operation. NOTE: Defined in `active_support/core_ext/hash/deep_transform_values.rb`. +[Hash#deep_transform_values!]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_transform_values-21 +[Hash#deep_transform_values]: https://api.rubyonrails.org/classes/Hash.html#method-i-deep_transform_values + ### Slicing -The method `slice!` replaces the hash with only the given keys and returns a hash containing the removed key/value pairs. +The method [`slice!`][Hash#slice!] replaces the hash with only the given keys and returns a hash containing the removed key/value pairs. ```ruby hash = {a: 1, b: 2} @@ -2815,9 +3073,11 @@ hash # => {:a=>1} NOTE: Defined in `active_support/core_ext/hash/slice.rb`. +[Hash#slice!]: https://api.rubyonrails.org/classes/Hash.html#method-i-slice-21 + ### Extracting -The method `extract!` removes and returns the key/value pairs matching the given keys. +The method [`extract!`][Hash#extract!] removes and returns the key/value pairs matching the given keys. ```ruby hash = {a: 1, b: 2} @@ -2835,9 +3095,11 @@ rest = hash.extract!(:a).class NOTE: Defined in `active_support/core_ext/hash/slice.rb`. +[Hash#extract!]: https://api.rubyonrails.org/classes/Hash.html#method-i-extract-21 + ### Indifferent Access -The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver: +The method [`with_indifferent_access`][Hash#with_indifferent_access] returns an [`ActiveSupport::HashWithIndifferentAccess`][ActiveSupport::HashWithIndifferentAccess] out of its receiver: ```ruby {a: 1}.with_indifferent_access["a"] # => 1 @@ -2845,12 +3107,15 @@ The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndiffer NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`. +[ActiveSupport::HashWithIndifferentAccess]: https://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html +[Hash#with_indifferent_access]: https://api.rubyonrails.org/classes/Hash.html#method-i-with_indifferent_access + Extensions to `Regexp` ---------------------- ### `multiline?` -The method `multiline?` says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines. +The method [`multiline?`][Regexp#multiline?] says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines. ```ruby %r{.}.multiline? # => false @@ -2874,6 +3139,8 @@ end NOTE: Defined in `active_support/core_ext/regexp.rb`. +[Regexp#multiline?]: https://api.rubyonrails.org/classes/Regexp.html#method-i-multiline-3F + Extensions to `Range` --------------------- @@ -2924,7 +3191,7 @@ NOTE: Defined in `active_support/core_ext/range/compare_range.rb`. ### `overlaps?` -The method `Range#overlaps?` says whether any two given ranges have non-void intersection: +The method [`Range#overlaps?`][Range#overlaps?] says whether any two given ranges have non-void intersection: ```ruby (1..10).overlaps?(7..11) # => true @@ -2934,6 +3201,8 @@ The method `Range#overlaps?` says whether any two given ranges have non-void int NOTE: Defined in `active_support/core_ext/range/overlaps.rb`. +[Range#overlaps?]: https://api.rubyonrails.org/classes/Range.html#method-i-overlaps-3F + Extensions to `Date` -------------------- @@ -2943,17 +3212,25 @@ INFO: The following calculation methods have edge cases in October 1582, since d #### `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?`, `tomorrow?`, `next_day?`, `yesterday?`, `prev_day?`, `future?`, `on_weekday?` and `on_weekend?`, all of them relative to `Date.current`. +Active Support defines [`Date.current`][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`][Date.yesterday] and [`Date.tomorrow`][Date.tomorrow], and the instance predicates [`past?`][DateAndTime::Calculations#past?], [`today?`][DateAndTime::Calculations#today?], [`tomorrow?`][DateAndTime::Calculations#tomorrow?], [`next_day?`][DateAndTime::Calculations#next_day?], [`yesterday?`][DateAndTime::Calculations#yesterday?], [`prev_day?`][DateAndTime::Calculations#prev_day?], [`future?`][DateAndTime::Calculations#future?], [`on_weekday?`][DateAndTime::Calculations#on_weekday?] and [`on_weekend?`][DateAndTime::Calculations#on_weekend?], 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`. NOTE: Defined in `active_support/core_ext/date/calculations.rb`. +[Date.current]: https://api.rubyonrails.org/classes/Date.html#method-c-current +[Date.tomorrow]: https://api.rubyonrails.org/classes/Date.html#method-c-tomorrow +[Date.yesterday]: https://api.rubyonrails.org/classes/Date.html#method-c-yesterday +[DateAndTime::Calculations#future?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-future-3F +[DateAndTime::Calculations#on_weekday?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-on_weekday-3F +[DateAndTime::Calculations#on_weekend?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-on_weekend-3F +[DateAndTime::Calculations#past?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-past-3F + #### Named dates ##### `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`][DateAndTime::Calculations#beginning_of_week] and [`end_of_week`][DateAndTime::Calculations#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, setting thread local `Date.beginning_of_week` or `config.beginning_of_week`. @@ -2966,13 +3243,18 @@ 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`][DateAndTime::Calculations#at_beginning_of_week] and `end_of_week` is aliased to [`at_end_of_week`][DateAndTime::Calculations#at_end_of_week]. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#at_beginning_of_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_week +[DateAndTime::Calculations#at_end_of_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_end_of_week +[DateAndTime::Calculations#beginning_of_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-beginning_of_week +[DateAndTime::Calculations#end_of_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-end_of_week + ##### `monday`, `sunday` -The methods `monday` and `sunday` return the dates for the previous Monday and +The methods [`monday`][DateAndTime::Calculations#monday] and [`sunday`][DateAndTime::Calculations#sunday] return the dates for the previous Monday and next Sunday, respectively. ```ruby @@ -2989,9 +3271,12 @@ d.sunday # => Sun, 16 Sep 2012 NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#monday]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-monday +[DateAndTime::Calculations#sunday]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-sunday + ##### `prev_week`, `next_week` -The method `next_week` receives a symbol with a day name in English (default is the thread local `Date.beginning_of_week`, or `config.beginning_of_week`, or `:monday`) and it returns the date corresponding to that day. +The method [`next_week`][DateAndTime::Calculations#next_week] receives a symbol with a day name in English (default is the thread local [`Date.beginning_of_week`][Date.beginning_of_week], or `config.beginning_of_week`, or `:monday`) and it returns the date corresponding to that day. ```ruby d = Date.new(2010, 5, 9) # => Sun, 09 May 2010 @@ -2999,7 +3284,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`][DateAndTime::Calculations#prev_week] is analogous: ```ruby d.prev_week # => Mon, 26 Apr 2010 @@ -3007,15 +3292,20 @@ 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`][DateAndTime::Calculations#last_week]. Both `next_week` and `prev_week` work as expected when `Date.beginning_of_week` or `config.beginning_of_week` are set. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[Date.beginning_of_week]: https://api.rubyonrails.org/classes/Date.html#method-c-beginning_of_week +[DateAndTime::Calculations#last_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-last_week +[DateAndTime::Calculations#next_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-next_week +[DateAndTime::Calculations#prev_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-prev_week + ##### `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`][DateAndTime::Calculations#beginning_of_month] and [`end_of_month`][DateAndTime::Calculations#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 @@ -3023,13 +3313,18 @@ 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`][DateAndTime::Calculations#at_beginning_of_month], and `end_of_month` is aliased to [`at_end_of_month`][DateAndTime::Calculations#at_end_of_month]. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#at_beginning_of_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_month +[DateAndTime::Calculations#at_end_of_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_end_of_month +[DateAndTime::Calculations#beginning_of_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-beginning_of_month +[DateAndTime::Calculations#end_of_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-end_of_month + ##### `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`][DateAndTime::Calculations#beginning_of_quarter] and [`end_of_quarter`][DateAndTime::Calculations#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 @@ -3037,13 +3332,18 @@ 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`][DateAndTime::Calculations#at_beginning_of_quarter], and `end_of_quarter` is aliased to [`at_end_of_quarter`][DateAndTime::Calculations#at_end_of_quarter]. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#at_beginning_of_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_quarter +[DateAndTime::Calculations#at_end_of_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_end_of_quarter +[DateAndTime::Calculations#beginning_of_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-beginning_of_quarter +[DateAndTime::Calculations#end_of_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-end_of_quarter + ##### `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`][DateAndTime::Calculations#beginning_of_year] and [`end_of_year`][DateAndTime::Calculations#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 @@ -3051,22 +3351,27 @@ 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`][DateAndTime::Calculations#at_beginning_of_year], and `end_of_year` is aliased to [`at_end_of_year`][DateAndTime::Calculations#at_end_of_year]. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#at_beginning_of_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_beginning_of_year +[DateAndTime::Calculations#at_end_of_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-at_end_of_year +[DateAndTime::Calculations#beginning_of_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-beginning_of_year +[DateAndTime::Calculations#end_of_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-end_of_year + #### Other Date Computations ##### `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`][DateAndTime::Calculations#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`][DateAndTime::Calculations#years_since] moves forward in time: ```ruby date = Date.new(2010, 6, 7) @@ -3080,13 +3385,17 @@ Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009 Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015 ``` -`last_year` is short-hand for `#years_ago(1)`. +[`last_year`][DateAndTime::Calculations#last_year] is short-hand for `#years_ago(1)`. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#last_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-last_year +[DateAndTime::Calculations#years_ago]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-years_ago +[DateAndTime::Calculations#years_since]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-years_since + ##### `months_ago`, `months_since` -The methods `months_ago` and `months_since` work analogously for months: +The methods [`months_ago`][DateAndTime::Calculations#months_ago] and [`months_since`][DateAndTime::Calculations#months_since] work analogously for months: ```ruby Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 @@ -3100,13 +3409,17 @@ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010 Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010 ``` -`last_month` is short-hand for `#months_ago(1)`. +[`last_month`][DateAndTime::Calculations#last_month] is short-hand for `#months_ago(1)`. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#last_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-last_month +[DateAndTime::Calculations#months_ago]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-months_ago +[DateAndTime::Calculations#months_since]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-months_since + ##### `weeks_ago` -The method `weeks_ago` works analogously for weeks: +The method [`weeks_ago`][DateAndTime::Calculations#weeks_ago] works analogously for weeks: ```ruby Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010 @@ -3115,9 +3428,11 @@ Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010 NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#weeks_ago]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-weeks_ago + ##### `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`][Date#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) @@ -3145,9 +3460,11 @@ Date.new(2010, 2, 28).advance(days: 1).advance(months: 1) NOTE: Defined in `active_support/core_ext/date/calculations.rb`. +[Date#advance]: https://api.rubyonrails.org/classes/Date.html#method-i-advance + #### 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`][Date#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) @@ -3163,9 +3480,11 @@ Date.new(2010, 1, 31).change(month: 2) NOTE: Defined in `active_support/core_ext/date/calculations.rb`. +[Date#change]: https://api.rubyonrails.org/classes/Date.html#method-i-change + #### Durations -Durations can be added to and subtracted from dates: +[`Duration`][ActiveSupport::Duration] objects can be added to and subtracted from dates: ```ruby d = Date.current @@ -3183,82 +3502,94 @@ Date.new(1582, 10, 4) + 1.day # => Fri, 15 Oct 1582 ``` +[ActiveSupport::Duration]: https://api.rubyonrails.org/classes/ActiveSupport/Duration.html + #### Timestamps 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` -The method `beginning_of_day` returns a timestamp at the beginning of the day (00:00:00): +The method [`beginning_of_day`][Date#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`][Date#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`][Date#at_beginning_of_day], [`midnight`][Date#midnight], [`at_midnight`][Date#at_midnight]. NOTE: Defined in `active_support/core_ext/date/calculations.rb`. +[Date#at_beginning_of_day]: https://api.rubyonrails.org/classes/Date.html#method-i-at_beginning_of_day +[Date#at_midnight]: https://api.rubyonrails.org/classes/Date.html#method-i-at_midnight +[Date#beginning_of_day]: https://api.rubyonrails.org/classes/Date.html#method-i-beginning_of_day +[Date#end_of_day]: https://api.rubyonrails.org/classes/Date.html#method-i-end_of_day +[Date#midnight]: https://api.rubyonrails.org/classes/Date.html#method-i-midnight + ##### `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`][DateTime#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`][DateTime#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`][DateTime#at_beginning_of_hour]. NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. ##### `beginning_of_minute`, `end_of_minute` -The method `beginning_of_minute` returns a timestamp at the beginning of the minute (hh:mm:00): +The method [`beginning_of_minute`][DateTime#beginning_of_minute] returns a timestamp at the beginning of the minute (hh:mm:00): ```ruby date = DateTime.new(2010, 6, 7, 19, 55, 25) date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010 ``` -The method `end_of_minute` returns a timestamp at the end of the minute (hh:mm:59): +The method [`end_of_minute`][DateTime#end_of_minute] returns a timestamp at the end of the minute (hh:mm:59): ```ruby date = DateTime.new(2010, 6, 7, 19, 55, 25) date.end_of_minute # => Mon Jun 07 19:55:59 +0200 2010 ``` -`beginning_of_minute` is aliased to `at_beginning_of_minute`. +`beginning_of_minute` is aliased to [`at_beginning_of_minute`][DateTime#at_beginning_of_minute]. INFO: `beginning_of_hour`, `end_of_hour`, `beginning_of_minute` and `end_of_minute` are implemented for `Time` and `DateTime` but **not** `Date` as it does not make sense to request the beginning or end of an hour or minute on a `Date` instance. NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#at_beginning_of_minute]: https://api.rubyonrails.org/classes/DateTime.html#method-i-at_beginning_of_minute +[DateTime#beginning_of_minute]: https://api.rubyonrails.org/classes/DateTime.html#method-i-beginning_of_minute +[DateTime#end_of_minute]: https://api.rubyonrails.org/classes/DateTime.html#method-i-end_of_minute + ##### `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`][Date#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`][Date#since] moves forward: ```ruby date = Date.current # => Fri, 11 Jun 2010 @@ -3267,6 +3598,9 @@ date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00 NOTE: Defined in `active_support/core_ext/date/calculations.rb`. +[Date#ago]: https://api.rubyonrails.org/classes/Date.html#method-i-ago +[Date#since]: https://api.rubyonrails.org/classes/Date.html#method-i-since + #### Other Time Computations ### Conversions @@ -3274,7 +3608,7 @@ NOTE: Defined in `active_support/core_ext/date/calculations.rb`. 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`][DateTime#seconds_since_midnight] might not return the real amount in such a day. ### Calculations @@ -3282,35 +3616,44 @@ The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ 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) -end_of_day -ago -since (in) -``` +* [`beginning_of_day`][DateTime#beginning_of_day] / [`midnight`][DateTime#midnight] / [`at_midnight`][DateTime#at_midnight] / [`at_beginning_of_day`][DateTime#at_beginning_of_day] +* [`end_of_day`][DateTime#end_of_day] +* [`ago`][DateTime#ago] +* [`since`][DateTime#since] / [`in`][DateTime#in] -On the other hand, `advance` and `change` are also defined and support more options, they are documented below. +On the other hand, [`advance`][DateTime#advance] and [`change`][DateTime#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: -```ruby -beginning_of_hour (at_beginning_of_hour) -end_of_hour -``` +* [`beginning_of_hour`][DateTime#beginning_of_hour] / [`at_beginning_of_hour`][DateTime#at_beginning_of_hour] +* [`end_of_hour`][DateTime#end_of_hour] + +[DateTime#ago]: https://api.rubyonrails.org/classes/DateTime.html#method-i-ago +[DateTime#at_beginning_of_day]: https://api.rubyonrails.org/classes/DateTime.html#method-i-at_beginning_of_day +[DateTime#at_beginning_of_hour]: https://api.rubyonrails.org/classes/DateTime.html#method-i-at_beginning_of_hour +[DateTime#at_midnight]: https://api.rubyonrails.org/classes/DateTime.html#method-i-at_midnight +[DateTime#beginning_of_day]: https://api.rubyonrails.org/classes/DateTime.html#method-i-beginning_of_day +[DateTime#beginning_of_hour]: https://api.rubyonrails.org/classes/DateTime.html#method-i-beginning_of_hour +[DateTime#end_of_day]: https://api.rubyonrails.org/classes/DateTime.html#method-i-end_of_day +[DateTime#end_of_hour]: https://api.rubyonrails.org/classes/DateTime.html#method-i-end_of_hour +[DateTime#in]: https://api.rubyonrails.org/classes/DateTime.html#method-i-in +[DateTime#midnight]: https://api.rubyonrails.org/classes/DateTime.html#method-i-midnight #### Named Datetimes ##### `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`][DateTime.current] to be like `Time.now.to_datetime`, except that it honors the user time zone, if defined. The instance predicates [`past?`][DateAndTime::Calculations#past?] and [`future?`][DateAndTime::Calculations#future?] are defined relative to `DateTime.current`. NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime.current]: https://api.rubyonrails.org/classes/DateTime.html#method-c-current + #### Other Extensions ##### `seconds_since_midnight` -The method `seconds_since_midnight` returns the number of seconds since midnight: +The method [`seconds_since_midnight`][DateTime#seconds_since_midnight] returns the number of seconds since midnight: ```ruby now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000 @@ -3319,22 +3662,27 @@ now.seconds_since_midnight # => 73596 NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#seconds_since_midnight]: https://api.rubyonrails.org/classes/DateTime.html#method-i-seconds_since_midnight + ##### `utc` -The method `utc` gives you the same datetime in the receiver expressed in UTC. +The method [`utc`][DateTime#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`][DateTime#getutc]. NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#getutc]: https://api.rubyonrails.org/classes/DateTime.html#method-i-getutc +[DateTime#utc]: https://api.rubyonrails.org/classes/DateTime.html#method-i-utc + ##### `utc?` -The predicate `utc?` says whether the receiver has UTC as its time zone: +The predicate [`utc?`][DateTime#utc?] says whether the receiver has UTC as its time zone: ```ruby now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400 @@ -3344,9 +3692,11 @@ now.utc.utc? # => true NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#utc?]: https://api.rubyonrails.org/classes/DateTime.html#method-i-utc-3F + ##### `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`][DateTime#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 @@ -3355,7 +3705,7 @@ d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1) # => 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`][DateTime#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: @@ -3377,9 +3727,12 @@ WARNING: Since `DateTime` is not DST-aware you can end up in a non-existing poin NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#advance]: https://api.rubyonrails.org/classes/DateTime.html#method-i-advance +[DateTime#since]: https://api.rubyonrails.org/classes/DateTime.html#method-i-since + #### 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`][DateTime#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 @@ -3411,9 +3764,11 @@ DateTime.current.change(month: 2, day: 30) NOTE: Defined in `active_support/core_ext/date_time/calculations.rb`. +[DateTime#change]: https://api.rubyonrails.org/classes/DateTime.html#method-i-change + #### Durations -Durations can be added to and subtracted from datetimes: +[`Duration`][ActiveSupport::Duration] objects can be added to and subtracted from datetimes: ```ruby now = DateTime.current @@ -3438,7 +3793,7 @@ Extensions to `Time` They are analogous. Please refer to their documentation above and take into account the following differences: -* `change` accepts an additional `:usec` option. +* [`change`][Time#change] accepts an additional `:usec` option. * `Time` understands DST, so you get correct DST calculations as in ```ruby @@ -3452,19 +3807,29 @@ 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`][Time#since] or [`ago`][Time#ago] jump to a time that can't be expressed with `Time` a `DateTime` object is returned instead. + +[Time#ago]: https://api.rubyonrails.org/classes/Time.html#method-i-ago +[Time#change]: https://api.rubyonrails.org/classes/Time.html#method-i-change +[Time#since]: https://api.rubyonrails.org/classes/Time.html#method-i-since #### `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 the instance predicates `past?`, `today?`, `tomorrow?`, `next_day?`, `yesterday?`, `prev_day?` and `future?`, all of them relative to `Time.current`. +Active Support defines [`Time.current`][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 the instance predicates [`past?`][DateAndTime::Calculations#past?], [`today?`][DateAndTime::Calculations#today?], [`tomorrow?`][DateAndTime::Calculations#tomorrow?], [`next_day?`][DateAndTime::Calculations#next_day?], [`yesterday?`][DateAndTime::Calculations#yesterday?], [`prev_day?`][DateAndTime::Calculations#prev_day?] and [`future?`][DateAndTime::Calculations#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` instead of `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.now` uses by default. This means `Time.now.to_date` may equal `Date.yesterday`. NOTE: Defined in `active_support/core_ext/time/calculations.rb`. +[DateAndTime::Calculations#next_day?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-next_day-3F +[DateAndTime::Calculations#prev_day?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-prev_day-3F +[DateAndTime::Calculations#today?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-today-3F +[DateAndTime::Calculations#tomorrow?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-tomorrow-3F +[DateAndTime::Calculations#yesterday?]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-yesterday-3F + #### `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`][DateAndTime::Calculations#all_day] returns a range representing the whole day of the current time. ```ruby now = Time.current @@ -3473,7 +3838,7 @@ now.all_day # => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00 ``` -Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges. +Analogously, [`all_week`][DateAndTime::Calculations#all_week], [`all_month`][DateAndTime::Calculations#all_month], [`all_quarter`][DateAndTime::Calculations#all_quarter] and [`all_year`][DateAndTime::Calculations#all_year] all serve the purpose of generating time ranges. ```ruby now = Time.current @@ -3492,9 +3857,16 @@ now.all_year NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#all_day]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-all_day +[DateAndTime::Calculations#all_month]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-all_month +[DateAndTime::Calculations#all_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-all_quarter +[DateAndTime::Calculations#all_week]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-all_week +[DateAndTime::Calculations#all_year]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-all_year +[Time.current]: https://api.rubyonrails.org/classes/Time.html#method-c-current + #### `prev_day`, `next_day` -`prev_day` and `next_day` return the time in the last or next day: +[`prev_day`][Time#prev_day] and [`next_day`][Time#next_day] return the time in the last or next day: ```ruby t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 @@ -3504,9 +3876,12 @@ t.next_day # => 2010-05-09 00:00:00 +0900 NOTE: Defined in `active_support/core_ext/time/calculations.rb`. +[Time#next_day]: https://api.rubyonrails.org/classes/Time.html#method-i-next_day +[Time#prev_day]: https://api.rubyonrails.org/classes/Time.html#method-i-prev_day + #### `prev_month`, `next_month` -`prev_month` and `next_month` return the time with the same day in the last or next month: +[`prev_month`][Time#prev_month] and [`next_month`][Time#next_month] return the time with the same day in the last or next month: ```ruby t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 @@ -3525,9 +3900,12 @@ Time.new(2000, 1, 31).next_month # => 2000-02-29 00:00:00 +0900 NOTE: Defined in `active_support/core_ext/time/calculations.rb`. +[Time#next_month]: https://api.rubyonrails.org/classes/Time.html#method-i-next_month +[Time#prev_month]: https://api.rubyonrails.org/classes/Time.html#method-i-prev_month + #### `prev_year`, `next_year` -`prev_year` and `next_year` return a time with the same day/month in the last or next year: +[`prev_year`][Time#prev_year] and [`next_year`][Time#next_year] return a time with the same day/month in the last or next year: ```ruby t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 @@ -3545,9 +3923,12 @@ t.next_year # => 2001-02-28 00:00:00 +0900 NOTE: Defined in `active_support/core_ext/time/calculations.rb`. +[Time#next_year]: https://api.rubyonrails.org/classes/Time.html#method-i-next_year +[Time#prev_year]: https://api.rubyonrails.org/classes/Time.html#method-i-prev_year + #### `prev_quarter`, `next_quarter` -`prev_quarter` and `next_quarter` return the date with the same day in the previous or next quarter: +[`prev_quarter`][DateAndTime::Calculations#prev_quarter] and [`next_quarter`][DateAndTime::Calculations#next_quarter] return the date with the same day in the previous or next quarter: ```ruby t = Time.local(2010, 5, 8) # => 2010-05-08 00:00:00 +0300 @@ -3564,13 +3945,17 @@ Time.local(2000, 10, 31).prev_quarter # => 2000-07-31 00:00:00 +0300 Time.local(2000, 11, 31).next_quarter # => 2001-03-01 00:00:00 +0200 ``` -`prev_quarter` is aliased to `last_quarter`. +`prev_quarter` is aliased to [`last_quarter`][DateAndTime::Calculations#last_quarter]. NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +[DateAndTime::Calculations#last_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-last_quarter +[DateAndTime::Calculations#next_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-next_quarter +[DateAndTime::Calculations#prev_quarter]: https://api.rubyonrails.org/classes/DateAndTime/Calculations.html#method-i-prev_quarter + ### 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`][Time.current] to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`: ```ruby Time.zone_default @@ -3579,13 +3964,13 @@ 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?`][DateAndTime::Calculations#past?], and [`future?`][DateAndTime::Calculations#future?] are relative to `Time.current`. 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 -Durations can be added to and subtracted from time objects: +[`Duration`][ActiveSupport::Duration] objects can be added to and subtracted from time objects: ```ruby now = Time.current @@ -3608,7 +3993,7 @@ Extensions to `File` ### `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`][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. @@ -3630,6 +4015,8 @@ The auxiliary file is written in a standard directory for temporary files, but y NOTE: Defined in `active_support/core_ext/file/atomic.rb`. +[File.atomic_write]: https://api.rubyonrails.org/classes/File.html#method-c-atomic_write + Extensions to `Marshal` ----------------------- @@ -3652,7 +4039,7 @@ NOTE: Defined in `active_support/core_ext/marshal.rb`. 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?`][NameError#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. @@ -3674,10 +4061,12 @@ end NOTE: Defined in `active_support/core_ext/name_error.rb`. +[NameError#missing_name?]: https://api.rubyonrails.org/classes/NameError.html#method-i-missing_name-3F + Extensions to `LoadError` ------------------------- -Active Support adds `is_missing?` to `LoadError`. +Active Support adds [`is_missing?`][LoadError#is_missing?] to `LoadError`. Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension). @@ -3696,3 +4085,5 @@ end ``` NOTE: Defined in `active_support/core_ext/load_error.rb`. + +[LoadError#is_missing?]: https://api.rubyonrails.org/classes/LoadError.html#method-i-is_missing-3F