active_support_core_extensions.md 114.7 KB
Newer Older
1 2
Active Support Core Extensions
==============================
3

X
Xavier Noria 已提交
4
Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
5

X
Xavier Noria 已提交
6 7
It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.

8
After reading this guide, you will know:
9

10 11 12
* What Core Extensions are.
* How to load all extensions.
* How to cherry-pick just the extensions you want.
Y
Yves Senn 已提交
13
* What extensions Active Support provides.
14

15
--------------------------------------------------------------------------------
16

17 18
How to Load Core Extensions
---------------------------
19

20
### Stand-Alone Active Support
21

22
In order to have a near-zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.
23 24 25

Thus, after a simple require like:

26
```ruby
27
require 'active_support'
28
```
29

30
objects do not even respond to `blank?`. Let's see how to load its definition.
31

32
#### Cherry-picking a Definition
33

34
The most lightweight way to get `blank?` is to cherry-pick the file that defines it.
35

36
For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of `blank?` the note reads:
37

38
NOTE: Defined in `active_support/core_ext/object/blank.rb`.
39 40 41

That means that this single call is enough:

42
```ruby
43
require 'active_support/core_ext/object/blank'
44
```
45 46 47

Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.

48
#### Loading Grouped Core Extensions
49

50
The next level is to simply load all extensions to `Object`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
51

52
Thus, to load all extensions to `Object` (including `blank?`):
53

54
```ruby
55
require 'active_support/core_ext/object'
56
```
57

58
#### Loading All Core Extensions
59 60 61

You may prefer just to load all core extensions, there is a file for that:

62
```ruby
63
require 'active_support/core_ext'
64
```
65

66
#### Loading All Active Support
67 68 69

And finally, if you want to have all Active Support available just issue:

70
```ruby
71
require 'active_support/all'
72
```
73

74
That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via `autoload`, so it is only loaded if used.
75

76
### Active Support Within a Ruby on Rails Application
77

78
A Ruby on Rails application loads all Active Support unless `config.active_support.bare` is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.
79

80 81
Extensions to All Objects
-------------------------
82

83
### `blank?` and `present?`
84 85 86

The following values are considered to be blank in a Rails application:

87
* `nil` and `false`,
88

89
* strings composed only of whitespace (see note below),
90 91 92

* empty arrays and hashes, and

93
* any other object that responds to `empty?` and is empty.
94

95
INFO: The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.
96

A
Agis Anastasopoulos 已提交
97
WARNING: Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank.
98

99
For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses `blank?` for checking whether a token is present:
100

101
```ruby
102 103 104 105
def authenticate(controller, &login_procedure)
  token, options = token_and_options(controller.request)
  unless token.blank?
    login_procedure.call(token, options)
X
Xavier Noria 已提交
106
  end
107
end
108
```
109

110
The method `present?` is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`:
111

112
```ruby
X
Xavier Noria 已提交
113 114 115
def set_conditional_cache_control!
  return if self["Cache-Control"].present?
  ...
116
end
117
```
118

119
NOTE: Defined in `active_support/core_ext/object/blank.rb`.
120

121
### `presence`
X
Xavier Noria 已提交
122

123
The `presence` method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this:
X
Xavier Noria 已提交
124

125
```ruby
X
Xavier Noria 已提交
126
host = config[:host].presence || 'localhost'
127
```
X
Xavier Noria 已提交
128

129
NOTE: Defined in `active_support/core_ext/object/blank.rb`.
130

131
### `duplicable?`
132

133
A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:
134

135
```ruby
136 137
1.object_id                 # => 3
Math.cos(0).to_i.object_id  # => 3
138
```
139

140
Hence, there's no way these objects can be duplicated through `dup` or `clone`:
141

142
```ruby
143
true.dup  # => TypeError: can't dup TrueClass
144
```
145 146 147

Some numbers which are not singletons are not duplicable either:

148
```ruby
149 150
0.0.clone        # => allocator undefined for Float
(2**1024).clone  # => allocator undefined for Bignum
151
```
152

153
Active Support provides `duplicable?` to programmatically query an object about this property:
154

155
```ruby
A
Agis Anastasopoulos 已提交
156
"foo".duplicable? # => true
V
Vijay Dev 已提交
157
"".duplicable?     # => true
A
Agis Anastasopoulos 已提交
158
0.0.duplicable?   # => false
V
Vijay Dev 已提交
159
false.duplicable?  # => false
160
```
161

162
By definition all objects are `duplicable?` except `nil`, `false`, `true`, symbols, numbers, class, and module objects.
163

164
WARNING: Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case.
165

166
NOTE: Defined in `active_support/core_ext/object/duplicable.rb`.
167

168
### `deep_dup`
A
Alexey Gaziev 已提交
169

P
Prathamesh Sonpatki 已提交
170
The `deep_dup` method returns deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:
A
Alexey Gaziev 已提交
171

172
```ruby
173 174 175 176 177
array     = ['string']
duplicate = array.dup

duplicate.push 'another-string'

A
Agis Anastasopoulos 已提交
178
# the object was duplicated, so the element was added only to the duplicate
179 180 181 182 183
array     #=> ['string']
duplicate #=> ['string', 'another-string']

duplicate.first.gsub!('string', 'foo')

A
Agis Anastasopoulos 已提交
184
# first element was not duplicated, it will be changed in both arrays
185 186
array     #=> ['foo']
duplicate #=> ['foo', 'another-string']
187
```
A
Alexey Gaziev 已提交
188

A
Agis Anastasopoulos 已提交
189
As you can see, after duplicating the `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make deep copy, the string inside the array is still the same object.
A
Alexey Gaziev 已提交
190

191
If you need a deep copy of an object, you should use `deep_dup`. Here is an example:
A
Alexey Gaziev 已提交
192

193
```ruby
194
array     = ['string']
195
duplicate = array.deep_dup
196 197 198 199 200

duplicate.first.gsub!('string', 'foo')

array     #=> ['string']
duplicate #=> ['foo']
201
```
A
Alexey Gaziev 已提交
202

A
Agis Anastasopoulos 已提交
203
If the object is not duplicable, `deep_dup` will just return it:
A
Alexey Gaziev 已提交
204

205
```ruby
A
Alexey Gaziev 已提交
206
number = 1
A
Agis Anastasopoulos 已提交
207 208
duplicate = number.deep_dup
number.object_id == duplicate.object_id   # => true
209
```
A
Alexey Gaziev 已提交
210

211
NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
A
Alexey Gaziev 已提交
212

213
### `try`
214

215
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`.
216 217

Here is an example:
V
Vijay Dev 已提交
218

219
```ruby
220 221 222 223 224 225 226
# without try
unless @number.nil?
  @number.next
end

# with try
@number.try(:next)
227
```
228

229
Another example is this code from `ActiveRecord::ConnectionAdapters::AbstractAdapter` where `@logger` could be `nil`. You can see that the code uses `try` and avoids an unnecessary check.
230

231
```ruby
232 233 234 235 236 237
def log_info(sql, name, ms)
  if @logger.try(:debug?)
    name = '%s (%.1fms)' % [name || 'SQL', ms]
    @logger.debug(format_log_entry(name, sql.squeeze(' ')))
  end
end
238
```
239

240
`try` can also be called without arguments but a block, which will only be executed if the object is not nil:
J
José Valim 已提交
241

242
```ruby
J
José Valim 已提交
243
@person.try { |p| "#{p.first_name} #{p.last_name}" }
244
```
J
José Valim 已提交
245

246
NOTE: Defined in `active_support/core_ext/object/try.rb`.
247

248
### `class_eval(*args, &block)`
249

250
You can evaluate code in the context of any object's singleton class using `class_eval`:
251

252
```ruby
253 254
class Proc
  def bind(object)
255
    block, time = self, Time.current
256 257 258 259 260 261 262 263 264
    object.class_eval do
      method_name = "__bind_#{time.to_i}_#{time.usec}"
      define_method(method_name, &block)
      method = instance_method(method_name)
      remove_method(method_name)
      method
    end.bind(object)
  end
end
265
```
266

267
NOTE: Defined in `active_support/core_ext/kernel/singleton_class.rb`.
268

269
### `acts_like?(duck)`
270

271
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
272

273
```ruby
274 275
def acts_like_string?
end
276
```
277 278 279

which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:

280
```ruby
281
some_klass.acts_like?(:string)
282
```
283

284
Rails has classes that act like `Date` or `Time` and follow this contract.
285

286
NOTE: Defined in `active_support/core_ext/object/acts_like.rb`.
287

288
### `to_param`
289

290
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.
291

292
By default `to_param` just calls `to_s`:
293

294
```ruby
295
7.to_param # => "7"
296
```
297

298
The return value of `to_param` should **not** be escaped:
299

300
```ruby
301
"Tom & Jerry".to_param # => "Tom & Jerry"
302
```
303 304 305

Several classes in Rails overwrite this method.

306
For example `nil`, `true`, and `false` return themselves. `Array#to_param` calls `to_param` on the elements and joins the result with "/":
307

308
```ruby
309
[0, true, String].to_param # => "0/true/String"
310
```
311

312
Notably, the Rails routing system calls `to_param` on models to get a value for the `:id` placeholder. `ActiveRecord::Base#to_param` returns the `id` of a model, but you can redefine that method in your models. For example, given
313

314
```ruby
315 316 317 318 319
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
320
```
321 322 323

we get:

324
```ruby
325
user_path(@user) # => "/users/357-john-smith"
326
```
327

328
WARNING. Controllers need to be aware of any redefinition of `to_param` because when a request like that comes in "357-john-smith" is the value of `params[:id]`.
329

330
NOTE: Defined in `active_support/core_ext/object/to_param.rb`.
331

332
### `to_query`
333

334
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
335

336
```ruby
337 338 339 340 341
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
342
```
343 344 345

we get:

346
```ruby
347
current_user.to_query('user') # => user=357-john-smith
348
```
349 350 351

This method escapes whatever is needed, both for the key and the value:

352
```ruby
353
account.to_query('company[name]')
354
# => "company%5Bname%5D=Johnson+%26+Johnson"
355
```
356 357 358

so its output is ready to be used in a query string.

359
Arrays return the result of applying `to_query` to each element with `_key_[]` as key, and join the result with "&":
360

361
```ruby
362 363
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
364
```
365

366
Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":
367

368
```ruby
369
{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
370
```
371

372
The method `Hash#to_query` accepts an optional namespace for the keys:
373

374
```ruby
375
{id: 89, name: "John Smith"}.to_query('user')
376
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
377
```
378

379
NOTE: Defined in `active_support/core_ext/object/to_query.rb`.
380

381
### `with_options`
382

383
The method `with_options` provides a way to factor out common options in a series of method calls.
384

385
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:
386

387
```ruby
388
class Account < ActiveRecord::Base
389 390 391 392
  has_many :customers, dependent: :destroy
  has_many :products,  dependent: :destroy
  has_many :invoices,  dependent: :destroy
  has_many :expenses,  dependent: :destroy
393
end
394
```
395 396 397

this way:

398
```ruby
399
class Account < ActiveRecord::Base
400
  with_options dependent: :destroy do |assoc|
401 402 403 404 405 406
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end
407
```
408 409 410

That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:

411
```ruby
412
I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
413
  subject i18n.t :subject
414
  body    i18n.t :body, user_name: user.name
415
end
416
```
417

418
TIP: Since `with_options` forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
419

420
NOTE: Defined in `active_support/core_ext/object/with_options.rb`.
421

422 423
### JSON support

424
Active Support provides a better implemention of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash` and `OrderedHash` needs special handling in order to provide a proper JSON representation.
425

426
Active Support also provides an implementation of `as_json` for the `Process::Status` class.
427 428 429

NOTE: Defined in `active_support/core_ext/object/to_json.rb`.

430
### Instance Variables
431 432 433

Active Support provides several methods to ease access to instance variables.

434
#### `instance_values`
435

436
The method `instance_values` returns a hash that maps instance variable names without "@" to their
437
corresponding values. Keys are strings:
438

439
```ruby
440 441 442 443 444 445 446
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
447
```
448

449
NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
450

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
#### `instance_variable_names`

The method `instance_variable_names` returns an array.  Each name includes the "@" sign.

```ruby
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

C.new(0, 1).instance_variable_names # => ["@x", "@y"]
```

NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.

467
### Silencing Warnings, Streams, and Exceptions
468

469
The methods `silence_warnings` and `enable_warnings` change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:
470

471
```ruby
472
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
473
```
474

475
You can silence any stream while a block runs with `silence_stream`:
476

477
```ruby
478 479 480
silence_stream(STDOUT) do
  # STDOUT is silent here
end
481
```
482

483
The `quietly` method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
484

485
```ruby
486
quietly { system 'bundle install' }
487
```
488 489 490

For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.

491
Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is reraised:
492

493
```ruby
494 495 496 497
# If the user is locked the increment is lost, no big deal.
suppress(ActiveRecord::StaleObjectError) do
  current_user.increment! :visits
end
498
```
499

500
NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`.
501

502
### `in?`
503

504
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?`.
505

506
Examples of `in?`:
507

508
```ruby
V
Vijay Dev 已提交
509 510 511
1.in?([1,2])        # => true
"lo".in?("hello")   # => true
25.in?(30..50)      # => false
512
1.in?(1)            # => ArgumentError
513
```
514

515
NOTE: Defined in `active_support/core_ext/object/inclusion.rb`.
516

517
Extensions to `Module`
518
----------------------
519

520
### `alias_method_chain`
521 522 523

Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.

524
For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionController::TestCase#process` this way in `test/test_helper.rb`:
525

526
```ruby
527 528 529 530 531 532 533 534 535 536
ActionController::TestCase.class_eval do
  # save a reference to the original process method
  alias_method :original_process, :process

  # now redefine process and delegate to original_process
  def process(action, params=nil, session=nil, flash=nil, http_method='GET')
    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
    original_process(action, params, session, flash, http_method)
  end
end
537
```
538

539
That's the method `get`, `post`, etc., delegate the work to.
540

541
That technique has a risk, it could be the case that `:original_process` was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
542

543
```ruby
544 545 546 547 548 549 550 551
ActionController::TestCase.class_eval do
  def process_with_stringified_params(...)
    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
    process_without_stringified_params(action, params, session, flash, http_method)
  end
  alias_method :process_without_stringified_params, :process
  alias_method :process, :process_with_stringified_params
end
552
```
553

554
The method `alias_method_chain` provides a shortcut for that pattern:
555

556
```ruby
557 558 559 560 561 562 563
ActionController::TestCase.class_eval do
  def process_with_stringified_params(...)
    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
    process_without_stringified_params(action, params, session, flash, http_method)
  end
  alias_method_chain :process, :stringified_params
end
564
```
565

566
Rails uses `alias_method_chain` all over the code base. For example validations are added to `ActiveRecord::Base#save` by wrapping the method that way in a separate module specialized in validations.
567

568
NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
569

570
### Attributes
571

572
#### `alias_attribute`
573

V
Vijay Dev 已提交
574
Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment):
575

576
```ruby
577 578
class User < ActiveRecord::Base
  # let me refer to the email column as "login",
579
  # possibly meaningful for authentication code
580 581
  alias_attribute :login, :email
end
582
```
583

584
NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
585

586
#### Internal Attributes
587

R
comma  
rpq 已提交
588
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.
589

590
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.
591

592
The macro `attr_internal` is a synonym for `attr_internal_accessor`:
593

594
```ruby
595 596 597 598 599 600 601 602 603
# library
class ThirdPartyLibrary::Crawler
  attr_internal :log_level
end

# client code
class MyCrawler < ThirdPartyLibrary::Crawler
  attr_accessor :log_level
end
604
```
605

606
In the previous example it could be the case that `:log_level` does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own `:log_level`. Thanks to `attr_internal` there's no collision.
607

608
By default the internal instance variable is named with a leading underscore, `@_log_level` in the example above. That's configurable via `Module.attr_internal_naming_format` though, you can pass any `sprintf`-like format string with a leading `@` and a `%s` somewhere, which is where the name will be placed. The default is `"@_%s"`.
609 610 611

Rails uses internal attributes in a few spots, for examples for views:

612
```ruby
613 614 615 616 617 618 619
module ActionView
  class Base
    attr_internal :captures
    attr_internal :request, :layout
    attr_internal :controller, :template
  end
end
620
```
621

622
NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`.
623

624
#### Module Attributes
625

626
The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are analogous to the `cattr_*` macros defined for class. Check [Class Attributes](#class-attributes).
627 628 629

For example, the dependencies mechanism uses them:

630
```ruby
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646
module ActiveSupport
  module Dependencies
    mattr_accessor :warnings_on_first_load
    mattr_accessor :history
    mattr_accessor :loaded
    mattr_accessor :mechanism
    mattr_accessor :load_paths
    mattr_accessor :load_once_paths
    mattr_accessor :autoloaded_constants
    mattr_accessor :explicitly_unloadable_constants
    mattr_accessor :logger
    mattr_accessor :log_activity
    mattr_accessor :constant_watch_stack
    mattr_accessor :constant_watch_stack_mutex
  end
end
647
```
648

649
NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`.
650

651
### Parents
652

653
#### `parent`
654

655
The `parent` method on a nested named module returns the module that contains its corresponding constant:
656

657
```ruby
658 659 660 661 662 663 664 665 666 667
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.parent # => X::Y
M.parent       # => X::Y
668
```
669

670
If the module is anonymous or belongs to the top-level, `parent` returns `Object`.
671

672
WARNING: Note that in that case `parent_name` returns `nil`.
673

674
NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
675

676
#### `parent_name`
677

678
The `parent_name` method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
679

680
```ruby
681 682 683 684 685 686 687 688 689 690
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.parent_name # => "X::Y"
M.parent_name       # => "X::Y"
691
```
692

693
For top-level or anonymous modules `parent_name` returns `nil`.
694

695
WARNING: Note that in that case `parent` returns `Object`.
696

697
NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
698

699
#### `parents`
700

701
The method `parents` calls `parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top:
702

703
```ruby
704 705 706 707 708 709 710 711 712 713
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.parents # => [X::Y, X, Object]
M.parents       # => [X::Y, X, Object]
714
```
715

716
NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
717

718
### Constants
719

720
The method `local_constants` returns the names of the constants that have been
721
defined in the receiver module:
722

723
```ruby
724 725 726 727 728 729 730 731 732
module X
  X1 = 1
  X2 = 2
  module Y
    Y1 = :y1
    X1 = :overrides_X1_above
  end
end

733 734
X.local_constants    # => [:X1, :X2, :Y]
X::Y.local_constants # => [:Y1, :X1]
735
```
736

737
The names are returned as symbols. (The deprecated method `local_constant_names` returns strings.)
738

739
NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
740

741
#### Qualified Constant Names
742

743
The standard methods `const_defined?`, `const_get` , and `const_set` accept
744
bare constant names. Active Support extends this API to be able to pass
745
relative qualified constant names.
746

747 748
The new methods are `qualified_const_defined?`, `qualified_const_get`, and
`qualified_const_set`. Their arguments are assumed to be qualified constant
749 750
names relative to their receiver:

751
```ruby
752 753 754
Object.qualified_const_defined?("Math::PI")       # => true
Object.qualified_const_get("Math::PI")            # => 3.141592653589793
Object.qualified_const_set("Math::Phi", 1.618034) # => 1.618034
755
```
756 757 758

Arguments may be bare constant names:

759
```ruby
760
Math.qualified_const_get("E") # => 2.718281828459045
761
```
762 763

These methods are analogous to their builtin counterparts. In particular,
764
`qualified_constant_defined?` accepts an optional second argument to be
765
able to say whether you want the predicate to look in the ancestors.
766 767 768 769 770
This flag is taken into account for each constant in the expression while
walking down the path.

For example, given

771
```ruby
772 773 774 775 776 777 778 779 780
module M
  X = 1
end

module N
  class C
    include M
  end
end
781
```
782

783
`qualified_const_defined?` behaves this way:
784

785
```ruby
786 787 788
N.qualified_const_defined?("C::X", false) # => false
N.qualified_const_defined?("C::X", true)  # => true
N.qualified_const_defined?("C::X")        # => true
789
```
790

791
As the last example implies, the second argument defaults to true,
792
as in `const_defined?`.
793 794

For coherence with the builtin methods only relative paths are accepted.
795
Absolute qualified constant names like `::Math::PI` raise `NameError`.
796

797
NOTE: Defined in `active_support/core_ext/module/qualified_const.rb`.
798

799
### Reachable
800

801
A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
802

803
That is what ordinarily happens, if a module is called "M", the `M` constant exists and holds it:
804

805
```ruby
806 807 808 809
module M
end

M.reachable? # => true
810
```
811 812 813

But since constants and modules are indeed kind of decoupled, module objects can become unreachable:

814
```ruby
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
module M
end

orphan = Object.send(:remove_const, :M)

# The module object is orphan now but it still has a name.
orphan.name # => "M"

# You cannot reach it via the constant M because it does not even exist.
orphan.reachable? # => false

# Let's define a module called "M" again.
module M
end

# The constant M exists now again, and it stores a module
# object called "M", but it is a new instance.
orphan.reachable? # => false
833
```
834

835
NOTE: Defined in `active_support/core_ext/module/reachable.rb`.
836

837
### Anonymous
838 839 840

A module may or may not have a name:

841
```ruby
842 843 844 845 846 847 848
module M
end
M.name # => "M"

N = Module.new
N.name # => "N"

849
Module.new.name # => nil
850
```
851

852
You can check whether a module has a name with the predicate `anonymous?`:
853

854
```ruby
855 856 857 858 859
module M
end
M.anonymous? # => false

Module.new.anonymous? # => true
860
```
861 862 863

Note that being unreachable does not imply being anonymous:

864
```ruby
865 866 867 868 869 870 871
module M
end

m = Object.send(:remove_const, :M)

m.reachable? # => false
m.anonymous? # => false
872
```
873 874 875

though an anonymous module is unreachable by definition.

876
NOTE: Defined in `active_support/core_ext/module/anonymous.rb`.
877

878
### Method Delegation
879

880
The macro `delegate` offers an easy way to forward methods.
881

882
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:
883

884
```ruby
885 886 887
class User < ActiveRecord::Base
  has_one :profile
end
888
```
889

890
With that configuration you get a user's name via his profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:
891

892
```ruby
893 894 895 896 897 898 899
class User < ActiveRecord::Base
  has_one :profile

  def name
    profile.name
  end
end
900
```
901

902
That is what `delegate` does for you:
903

904
```ruby
905 906 907
class User < ActiveRecord::Base
  has_one :profile

908
  delegate :name, to: :profile
909
end
910
```
911

912 913
It is shorter, and the intention more obvious.

914 915
The method must be public in the target.

916
The `delegate` macro accepts several methods:
917

918
```ruby
919
delegate :name, :age, :address, :twitter, to: :profile
920
```
921

922
When interpolated into a string, the `:to` option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:
923

924
```ruby
925
# delegates to the Rails constant
926
delegate :logger, to: :Rails
927 928

# delegates to the receiver's class
929
delegate :table_name, to: :class
930
```
931

932
WARNING: If the `:prefix` option is `true` this is less generic, see below.
933

934
By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:
935

936
```ruby
937
delegate :name, to: :profile, allow_nil: true
938
```
939

940
With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
941

942
The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:
943

944
```ruby
945
delegate :street, to: :address, prefix: true
946
```
947

948
The previous example generates `address_street` rather than `street`.
949

950
WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the `:to` option must be a method name.
951 952 953

A custom prefix may also be configured:

954
```ruby
955
delegate :size, to: :attachment, prefix: :avatar
956
```
957

958
In the previous example the macro generates `avatar_size` rather than `size`.
959

960
NOTE: Defined in `active_support/core_ext/module/delegation.rb`
961

962
### Redefining Methods
963

964
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.
965

966
The method `redefine_method` prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association's API:
967

968
```ruby
969 970 971 972 973 974 975 976 977 978
redefine_method("#{reflection.name}=") do |new_value|
  association = association_instance_get(reflection.name)

  if association.nil? || association.target != new_value
    association = association_proxy_class.new(self, reflection)
  end

  association.replace(new_value)
  association_instance_set(reflection.name, new_value.nil? ? nil : association)
end
979
```
980

981
NOTE: Defined in `active_support/core_ext/module/remove_method.rb`
982

983
Extensions to `Class`
984
---------------------
985

986
### Class Attributes
987

988
#### `class_attribute`
989

990
The method `class_attribute` declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
991

992
```ruby
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
class A
  class_attribute :x
end

class B < A; end

class C < B; end

A.x = :a
B.x # => :a
C.x # => :a

B.x = :b
A.x # => :a
C.x # => :b

C.x = :c
A.x # => :a
B.x # => :b
1012
```
1013

1014
For example `ActionMailer::Base` defines:
1015

1016
```ruby
1017 1018
class_attribute :default_params
self.default_params = {
1019 1020 1021 1022
  mime_version: "1.0",
  charset: "UTF-8",
  content_type: "text/plain",
  parts_order: [ "text/plain", "text/enriched", "text/html" ]
1023
}.freeze
1024
```
1025

1026
They can be also accessed and overridden at the instance level.
1027

1028
```ruby
1029 1030 1031 1032 1033 1034 1035 1036
A.x = 1

a1 = A.new
a2 = A.new
a2.x = 2

a1.x # => 1, comes from A
a2.x # => 2, overridden in a2
1037
```
1038

1039
The generation of the writer instance method can be prevented by setting the option `:instance_writer` to `false`.
1040

1041
```ruby
V
Vijay Dev 已提交
1042
module ActiveRecord
1043
  class Base
1044
    class_attribute :table_name_prefix, instance_writer: false
1045 1046 1047
    self.table_name_prefix = ""
  end
end
1048
```
1049

1050 1051
A model may find that option useful as a way to prevent mass-assignment from setting the attribute.

1052
The generation of the reader instance method can be prevented by setting the option `:instance_reader` to `false`.
1053

1054
```ruby
1055
class A
1056
  class_attribute :x, instance_reader: false
1057 1058
end

1059
A.new.x = 1 # NoMethodError
1060
```
1061

1062
For convenience `class_attribute` also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called `x?`.
1063

1064
When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.
1065

1066
If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.
1067

1068
NOTE: Defined in `active_support/core_ext/class/attribute.rb`
1069

1070
#### `cattr_reader`, `cattr_writer`, and `cattr_accessor`
1071

1072
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:
1073

1074
```ruby
1075 1076 1077 1078 1079
class MysqlAdapter < AbstractAdapter
  # Generates class methods to access @@emulate_booleans.
  cattr_accessor :emulate_booleans
  self.emulate_booleans = true
end
1080
```
1081

1082
Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with `class_attribute` (see above). For example given
1083

1084
```ruby
1085
module ActionView
1086
  class Base
1087 1088
    cattr_accessor :field_error_proc
    @@field_error_proc = Proc.new{ ... }
1089 1090
  end
end
1091
```
1092

1093
we can access `field_error_proc` in views.
1094

1095
The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.
1096

1097
```ruby
1098 1099 1100
module A
  class B
    # No first_name instance reader is generated.
1101
    cattr_accessor :first_name, instance_reader: false
1102
    # No last_name= instance writer is generated.
1103
    cattr_accessor :last_name, instance_writer: false
1104
    # No surname instance reader or surname= writer is generated.
1105
    cattr_accessor :surname, instance_accessor: false
1106 1107
  end
end
1108
```
1109

1110
A model may find it useful to set `:instance_accessor` to `false` as a way to prevent mass-assignment from setting the attribute.
1111

1112
NOTE: Defined in `active_support/core_ext/class/attribute_accessors.rb`.
1113

1114
### Subclasses & Descendants
1115

1116
#### `subclasses`
1117

1118
The `subclasses` method returns the subclasses of the receiver:
1119

1120
```ruby
1121
class C; end
X
Xavier Noria 已提交
1122
C.subclasses # => []
1123

1124
class B < C; end
X
Xavier Noria 已提交
1125
C.subclasses # => [B]
1126

1127
class A < B; end
X
Xavier Noria 已提交
1128
C.subclasses # => [B]
1129

1130
class D < C; end
X
Xavier Noria 已提交
1131
C.subclasses # => [B, D]
1132
```
1133

X
Xavier Noria 已提交
1134
The order in which these classes are returned is unspecified.
1135

1136
NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
X
Xavier Noria 已提交
1137

1138
#### `descendants`
X
Xavier Noria 已提交
1139

1140
The `descendants` method returns all classes that are `<` than its receiver:
1141

1142
```ruby
1143
class C; end
X
Xavier Noria 已提交
1144
C.descendants # => []
1145 1146

class B < C; end
X
Xavier Noria 已提交
1147
C.descendants # => [B]
1148 1149

class A < B; end
X
Xavier Noria 已提交
1150
C.descendants # => [B, A]
1151 1152

class D < C; end
X
Xavier Noria 已提交
1153
C.descendants # => [B, A, D]
1154
```
1155

X
Xavier Noria 已提交
1156
The order in which these classes are returned is unspecified.
1157

1158
NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
1159

1160
Extensions to `String`
1161
----------------------
1162

1163
### Output Safety
1164

1165
#### Motivation
1166

1167
Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.
1168

1169
#### Safe Strings
1170

1171
Active Support has the concept of <i>(html) safe</i> strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
1172 1173 1174

Strings are considered to be <i>unsafe</i> by default:

1175
```ruby
1176
"".html_safe? # => false
1177
```
1178

1179
You can obtain a safe string from a given one with the `html_safe` method:
1180

1181
```ruby
1182 1183
s = "".html_safe
s.html_safe? # => true
1184
```
1185

1186
It is important to understand that `html_safe` performs no escaping whatsoever, it is just an assertion:
1187

1188
```ruby
1189 1190 1191
s = "<script>...</script>".html_safe
s.html_safe? # => true
s            # => "<script>...</script>"
1192
```
1193

1194
It is your responsibility to ensure calling `html_safe` on a particular string is fine.
1195

1196
If you append onto a safe string, either in-place with `concat`/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
1197

1198
```ruby
1199
"".html_safe + "<" # => "&lt;"
1200
```
1201 1202 1203

Safe arguments are directly appended:

1204
```ruby
1205
"".html_safe + "<".html_safe # => "<"
1206
```
1207

1208
These methods should not be used in ordinary views. Unsafe values are automatically escaped:
1209

1210
```erb
1211
<%= @review.title %> <%# fine, escaped if needed %>
1212
```
1213

1214
To insert something verbatim use the `raw` helper rather than calling `html_safe`:
1215

1216
```erb
1217
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
1218
```
X
Xavier Noria 已提交
1219

1220
or, equivalently, use `<%==`:
X
Xavier Noria 已提交
1221

1222
```erb
X
Xavier Noria 已提交
1223
<%== @cms.current_template %> <%# inserts @cms.current_template as is %>
1224
```
1225

1226
The `raw` helper calls `html_safe` for you:
1227

1228
```ruby
1229 1230 1231
def raw(stringish)
  stringish.to_s.html_safe
end
1232
```
1233

1234
NOTE: Defined in `active_support/core_ext/string/output_safety.rb`.
1235

1236
#### Transformation
1237

1238
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.
1239

1240
In the case of in-place transformations like `gsub!` the receiver itself becomes unsafe.
1241 1242 1243

INFO: The safety bit is lost always, no matter whether the transformation actually changed something.

1244
#### Conversion and Coercion
1245

1246
Calling `to_s` on a safe string returns a safe string, but coercion with `to_str` returns an unsafe string.
1247

1248
#### Copying
1249

1250
Calling `dup` or `clone` on safe strings yields safe strings.
1251

1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
### `remove`

The method `remove` will remove all occurrences of the pattern:

```ruby
"Hello World".remove(/Hello /) => "World"
```

There's also the destructive version `String#remove!`.

NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1263
### `squish`
1264

1265
The method `squish` strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
1266

1267
```ruby
1268
" \n  foo\n\r \t bar \n".squish # => "foo bar"
1269
```
1270

1271
There's also the destructive version `String#squish!`.
1272

1273 1274
Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).

1275
NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1276

1277
### `truncate`
1278

1279
The method `truncate` returns a copy of its receiver truncated after a given `length`:
1280

1281
```ruby
1282 1283
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
1284
```
1285

1286
Ellipsis can be customized with the `:omission` option:
1287

1288
```ruby
1289
"Oh dear! Oh dear! I shall be late!".truncate(20, omission: '&hellip;')
1290
# => "Oh dear! Oh &hellip;"
1291
```
1292 1293 1294

Note in particular that truncation takes into account the length of the omission string.

1295
Pass a `:separator` to truncate the string at a natural break:
1296

1297
```ruby
1298
"Oh dear! Oh dear! I shall be late!".truncate(18)
1299
# => "Oh dear! Oh dea..."
1300
"Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
1301
# => "Oh dear! Oh..."
1302
```
1303

1304
The option `:separator` can be a regexp:
A
Alexey Gaziev 已提交
1305

1306
```ruby
1307
"Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
A
Alexey Gaziev 已提交
1308
# => "Oh dear! Oh..."
1309
```
1310

1311
In above examples "dear" gets cut first, but then `:separator` prevents it.
1312

1313
NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1314

1315
### `inquiry`
1316

1317
The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier.
1318

1319
```ruby
1320 1321
"production".inquiry.production? # => true
"active".inquiry.inactive?       # => false
1322
```
1323

1324
### `starts_with?` and `ends_with?`
1325

1326
Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`:
1327

1328
```ruby
1329 1330
"foo".starts_with?("f") # => true
"foo".ends_with?("o")   # => true
1331
```
1332

1333
NOTE: Defined in `active_support/core_ext/string/starts_ends_with.rb`.
1334

1335
### `strip_heredoc`
X
Xavier Noria 已提交
1336

1337
The method `strip_heredoc` strips indentation in heredocs.
X
Xavier Noria 已提交
1338 1339 1340

For example in

1341
```ruby
X
Xavier Noria 已提交
1342 1343 1344 1345 1346 1347 1348 1349 1350
if options[:usage]
  puts <<-USAGE.strip_heredoc
    This command does such and such.

    Supported options are:
      -h         This message
      ...
  USAGE
end
1351
```
X
Xavier Noria 已提交
1352 1353 1354 1355 1356 1357

the user would see the usage message aligned against the left margin.

Technically, it looks for the least indented line in the whole string, and removes
that amount of leading whitespace.

1358
NOTE: Defined in `active_support/core_ext/string/strip.rb`.
X
Xavier Noria 已提交
1359

1360
### `indent`
1361 1362 1363

Indents the lines in the receiver:

1364
```ruby
1365 1366 1367 1368 1369 1370 1371 1372 1373
<<EOS.indent(2)
def some_method
  some_code
end
EOS
# =>
  def some_method
    some_code
  end
1374
```
1375

1376
The second argument, `indent_string`, specifies which indent string to use. The default is `nil`, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
1377

1378
```ruby
1379 1380 1381
"  foo".indent(2)        # => "    foo"
"foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
"foo".indent(2, "\t")    # => "\t\tfoo"
1382
```
1383

V
Vipul A M 已提交
1384
While `indent_string` is typically one space or tab, it may be any string.
1385

1386
The third argument, `indent_empty_lines`, is a flag that says whether empty lines should be indented. Default is false.
1387

1388
```ruby
1389 1390
"foo\n\nbar".indent(2)            # => "  foo\n\n  bar"
"foo\n\nbar".indent(2, nil, true) # => "  foo\n  \n  bar"
1391
```
1392

1393
The `indent!` method performs indentation in-place.
1394

1395
### Access
1396

1397
#### `at(position)`
1398

1399
Returns the character of the string at position `position`:
1400

1401
```ruby
1402 1403 1404
"hello".at(0)  # => "h"
"hello".at(4)  # => "o"
"hello".at(-1) # => "o"
1405
"hello".at(10) # => nil
1406
```
1407

1408
NOTE: Defined in `active_support/core_ext/string/access.rb`.
1409

1410
#### `from(position)`
1411

1412
Returns the substring of the string starting at position `position`:
1413

1414
```ruby
1415 1416 1417 1418
"hello".from(0)  # => "hello"
"hello".from(2)  # => "llo"
"hello".from(-2) # => "lo"
"hello".from(10) # => "" if < 1.9, nil in 1.9
1419
```
1420

1421
NOTE: Defined in `active_support/core_ext/string/access.rb`.
1422

1423
#### `to(position)`
1424

1425
Returns the substring of the string up to position `position`:
1426

1427
```ruby
1428 1429 1430 1431
"hello".to(0)  # => "h"
"hello".to(2)  # => "hel"
"hello".to(-2) # => "hell"
"hello".to(10) # => "hello"
1432
```
1433

1434
NOTE: Defined in `active_support/core_ext/string/access.rb`.
1435

1436
#### `first(limit = 1)`
1437

1438
The call `str.first(n)` is equivalent to `str.to(n-1)` if `n` > 0, and returns an empty string for `n` == 0.
1439

1440
NOTE: Defined in `active_support/core_ext/string/access.rb`.
1441

1442
#### `last(limit = 1)`
1443

1444
The call `str.last(n)` is equivalent to `str.from(-n)` if `n` > 0, and returns an empty string for `n` == 0.
1445

1446
NOTE: Defined in `active_support/core_ext/string/access.rb`.
1447

1448
### Inflections
1449

1450
#### `pluralize`
1451

1452
The method `pluralize` returns the plural of its receiver:
1453

1454
```ruby
1455 1456 1457
"table".pluralize     # => "tables"
"ruby".pluralize      # => "rubies"
"equipment".pluralize # => "equipment"
1458
```
1459

1460
As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in `config/initializers/inflections.rb`. That file is generated by the `rails` command and has instructions in comments.
1461

1462
`pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:
1463

1464
```ruby
1465 1466 1467
"dude".pluralize(0) # => "dudes"
"dude".pluralize(1) # => "dude"
"dude".pluralize(2) # => "dudes"
1468
```
1469

1470 1471
Active Record uses this method to compute the default table name that corresponds to a model:

1472
```ruby
1473
# active_record/model_schema.rb
1474 1475
def undecorated_table_name(class_name = base_class.name)
  table_name = class_name.to_s.demodulize.underscore
1476
  pluralize_table_names ? table_name.pluralize : table_name
1477
end
1478
```
1479

1480
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1481

1482
#### `singularize`
1483

1484
The inverse of `pluralize`:
1485

1486
```ruby
1487 1488 1489
"tables".singularize    # => "table"
"rubies".singularize    # => "ruby"
"equipment".singularize # => "equipment"
1490
```
1491 1492 1493

Associations compute the name of the corresponding default associated class using this method:

1494
```ruby
1495 1496 1497 1498 1499 1500
# active_record/reflection.rb
def derive_class_name
  class_name = name.to_s.camelize
  class_name = class_name.singularize if collection?
  class_name
end
1501
```
1502

1503
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1504

1505
#### `camelize`
1506

1507
The method `camelize` returns its receiver in camel case:
1508

1509
```ruby
1510 1511
"product".camelize    # => "Product"
"admin_user".camelize # => "AdminUser"
1512
```
1513 1514 1515

As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:

1516
```ruby
1517
"backoffice/session".camelize # => "Backoffice::Session"
1518
```
1519 1520 1521

For example, Action Pack uses this method to load the class that provides a certain session store:

1522
```ruby
1523 1524
# action_controller/metal/session_management.rb
def session_store=(store)
1525 1526 1527
  @@session_store = store.is_a?(Symbol) ?
    ActionDispatch::Session.const_get(store.to_s.camelize) :
    store
1528
end
1529
```
1530

1531
`camelize` accepts an optional argument, it can be `:upper` (default), or `:lower`. With the latter the first letter becomes lowercase:
1532

1533
```ruby
1534
"visual_effect".camelize(:lower) # => "visualEffect"
1535
```
1536 1537 1538

That may be handy to compute method names in a language that follows that convention, for example JavaScript.

1539
INFO: As a rule of thumb you can think of `camelize` as the inverse of `underscore`, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in `config/initializers/inflections.rb`:
1540

1541
```ruby
1542 1543 1544 1545 1546
ActiveSupport::Inflector.inflections do |inflect|
  inflect.acronym 'SSL'
end

"SSLError".underscore.camelize #=> "SSLError"
1547
```
1548

1549
`camelize` is aliased to `camelcase`.
1550

1551
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1552

1553
#### `underscore`
1554

1555
The method `underscore` goes the other way around, from camel case to paths:
1556

1557
```ruby
1558 1559
"Product".underscore   # => "product"
"AdminUser".underscore # => "admin_user"
1560
```
1561 1562 1563

Also converts "::" back to "/":

1564
```ruby
1565
"Backoffice::Session".underscore # => "backoffice/session"
1566
```
1567 1568 1569

and understands strings that start with lowercase:

1570
```ruby
1571
"visualEffect".underscore # => "visual_effect"
1572
```
1573

1574
`underscore` accepts no argument though.
1575

1576
Rails class and module autoloading uses `underscore` to infer the relative path without extension of a file that would define a given missing constant:
1577

1578
```ruby
1579 1580 1581 1582 1583 1584 1585
# active_support/dependencies.rb
def load_missing_constant(from_mod, const_name)
  ...
  qualified_name = qualified_name_for from_mod, const_name
  path_suffix = qualified_name.underscore
  ...
end
1586
```
1587

1588
INFO: As a rule of thumb you can think of `underscore` as the inverse of `camelize`, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
1589

1590
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1591

1592
#### `titleize`
1593

1594
The method `titleize` capitalizes the words in the receiver:
1595

1596
```ruby
1597 1598
"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize     # => "Fermat's Enigma"
1599
```
1600

1601
`titleize` is aliased to `titlecase`.
1602

1603
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1604

1605
#### `dasherize`
1606

1607
The method `dasherize` replaces the underscores in the receiver with dashes:
1608

1609
```ruby
1610 1611
"name".dasherize         # => "name"
"contact_data".dasherize # => "contact-data"
1612
```
1613 1614 1615

The XML serializer of models uses this method to dasherize node names:

1616
```ruby
1617 1618 1619 1620 1621
# active_model/serializers/xml.rb
def reformat_name(name)
  name = name.camelize if camelize?
  dasherize? ? name.dasherize : name
end
1622
```
1623

1624
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1625

1626
#### `demodulize`
1627

1628
Given a string with a qualified constant name, `demodulize` returns the very constant name, that is, the rightmost part of it:
1629

1630
```ruby
1631 1632 1633
"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
1634
```
1635 1636 1637

Active Record for example uses this method to compute the name of a counter cache column:

1638
```ruby
1639 1640 1641 1642 1643 1644 1645 1646
# active_record/reflection.rb
def counter_cache_column
  if options[:counter_cache] == true
    "#{active_record.name.demodulize.underscore.pluralize}_count"
  elsif options[:counter_cache]
    options[:counter_cache]
  end
end
1647
```
1648

1649
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1650

1651
#### `deconstantize`
1652

1653
Given a string with a qualified constant reference expression, `deconstantize` removes the rightmost segment, generally leaving the name of the constant's container:
1654

1655
```ruby
1656 1657 1658
"Product".deconstantize                        # => ""
"Backoffice::UsersController".deconstantize    # => "Backoffice"
"Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
1659
```
1660

1661
Active Support for example uses this method in `Module#qualified_const_set`:
1662

1663
```ruby
1664 1665 1666 1667 1668 1669 1670 1671
def qualified_const_set(path, value)
  QualifiedConstUtils.raise_if_absolute(path)

  const_name = path.demodulize
  mod_name = path.deconstantize
  mod = mod_name.empty? ? self : qualified_const_get(mod_name)
  mod.const_set(const_name, value)
end
1672
```
1673

1674
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1675

1676
#### `parameterize`
1677

1678
The method `parameterize` normalizes its receiver in a way that can be used in pretty URLs.
1679

1680
```ruby
1681 1682
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
1683
```
1684

1685
In fact, the result string is wrapped in an instance of `ActiveSupport::Multibyte::Chars`.
1686

1687
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1688

1689
#### `tableize`
1690

1691
The method `tableize` is `underscore` followed by `pluralize`.
1692

1693
```ruby
1694 1695
"Person".tableize      # => "people"
"Invoice".tableize     # => "invoices"
1696
"InvoiceLine".tableize # => "invoice_lines"
1697
```
1698

1699
As a rule of thumb, `tableize` returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight `tableize` indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
1700

1701
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1702

1703
#### `classify`
1704

1705
The method `classify` is the inverse of `tableize`. It gives you the class name corresponding to a table name:
1706

1707
```ruby
1708 1709 1710
"people".classify        # => "Person"
"invoices".classify      # => "Invoice"
"invoice_lines".classify # => "InvoiceLine"
1711
```
1712 1713 1714

The method understands qualified table names:

1715
```ruby
1716
"highrise_production.companies".classify # => "Company"
1717
```
1718

1719
Note that `classify` returns a class name as a string. You can get the actual class object invoking `constantize` on it, explained next.
1720

1721
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1722

1723
#### `constantize`
1724

1725
The method `constantize` resolves the constant reference expression in its receiver:
1726

1727
```ruby
1728 1729 1730 1731 1732 1733
"Fixnum".constantize # => Fixnum

module M
  X = 1
end
"M::X".constantize # => 1
1734
```
1735

1736
If the string evaluates to no known constant, or its content is not even a valid constant name, `constantize` raises `NameError`.
1737

1738
Constant name resolution by `constantize` starts always at the top-level `Object` even if there is no leading "::".
1739

1740
```ruby
1741 1742 1743 1744 1745 1746 1747 1748
X = :in_Object
module M
  X = :in_M

  X                 # => :in_M
  "::X".constantize # => :in_Object
  "X".constantize   # => :in_Object (!)
end
1749
```
1750 1751 1752

So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.

1753
Mailer test cases obtain the mailer being tested from the name of the test class using `constantize`:
1754

1755
```ruby
1756 1757 1758 1759 1760 1761
# action_mailer/test_case.rb
def determine_default_mailer(name)
  name.sub(/Test$/, '').constantize
rescue NameError => e
  raise NonInferrableMailerError.new(name)
end
1762
```
1763

1764
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1765

1766
#### `humanize`
1767

1768
The method `humanize` gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word:
1769

1770
```ruby
1771 1772 1773
"name".humanize           # => "Name"
"author_id".humanize      # => "Author"
"comments_count".humanize # => "Comments count"
1774
```
1775

1776
The helper method `full_messages` uses `humanize` as a fallback to include attribute names:
1777

1778
```ruby
1779 1780 1781 1782 1783 1784
def full_messages
  full_messages = []

  each do |attribute, messages|
    ...
    attr_name = attribute.to_s.gsub('.', '_').humanize
1785
    attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
1786 1787 1788 1789 1790
    ...
  end

  full_messages
end
1791
```
1792

1793
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1794

1795
#### `foreign_key`
1796

1797
The method `foreign_key` gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
1798

1799
```ruby
1800 1801 1802
"User".foreign_key           # => "user_id"
"InvoiceLine".foreign_key    # => "invoice_line_id"
"Admin::Session".foreign_key # => "session_id"
1803
```
1804 1805 1806

Pass a false argument if you do not want the underscore in "_id":

1807
```ruby
1808
"User".foreign_key(false) # => "userid"
1809
```
1810

1811
Associations use this method to infer foreign keys, for example `has_one` and `has_many` do this:
1812

1813
```ruby
1814 1815
# active_record/associations.rb
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
1816
```
1817

1818
NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1819

1820
### Conversions
1821

1822
#### `to_date`, `to_time`, `to_datetime`
1823

1824
The methods `to_date`, `to_time`, and `to_datetime` are basically convenience wrappers around `Date._parse`:
1825

1826
```ruby
1827 1828
"2010-07-27".to_date              # => Tue, 27 Jul 2010
"2010-07-27 23:37:00".to_time     # => Tue Jul 27 23:37:00 UTC 2010
1829
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
1830
```
1831

1832
`to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:
1833

1834
```ruby
1835 1836
"2010-07-27 23:42:00".to_time(:utc)   # => Tue Jul 27 23:42:00 UTC 2010
"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
1837
```
1838

1839
Default is `:utc`.
1840

1841
Please refer to the documentation of `Date._parse` for further details.
1842

1843
INFO: The three of them return `nil` for blank receivers.
1844

1845
NOTE: Defined in `active_support/core_ext/string/conversions.rb`.
1846

1847
Extensions to `Numeric`
1848
-----------------------
1849

1850
### Bytes
1851 1852 1853

All numbers respond to these methods:

1854
```ruby
1855 1856 1857 1858 1859 1860 1861
bytes
kilobytes
megabytes
gigabytes
terabytes
petabytes
exabytes
1862
```
1863 1864 1865

They return the corresponding amount of bytes, using a conversion factor of 1024:

1866
```ruby
1867 1868 1869 1870
2.kilobytes   # => 2048
3.megabytes   # => 3145728
3.5.gigabytes # => 3758096384
-4.exabytes   # => -4611686018427387904
1871
```
1872 1873 1874

Singular forms are aliased so you are able to say:

1875
```ruby
X
Xavier Noria 已提交
1876
1.megabyte # => 1048576
1877
```
1878

1879
NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`.
1880

1881
### Time
A
Alexey Gaziev 已提交
1882

1883
Enables the use of time calculations and declarations, like `45.minutes + 2.hours + 4.years`.
A
Alexey Gaziev 已提交
1884 1885 1886 1887

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:

1888
```ruby
1889
# equivalent to Time.current.advance(months: 1)
A
Alexey Gaziev 已提交
1890 1891
1.month.from_now

1892
# equivalent to Time.current.advance(years: 2)
A
Alexey Gaziev 已提交
1893 1894
2.years.from_now

1895
# equivalent to Time.current.advance(months: 4, years: 5)
A
Alexey Gaziev 已提交
1896
(4.months + 5.years).from_now
1897
```
A
Alexey Gaziev 已提交
1898 1899 1900 1901 1902

While these methods provide precise calculation when used as in the examples above, care
should be taken to note that this is not true if the result of `months', `years', etc is
converted before use:

1903
```ruby
A
Alexey Gaziev 已提交
1904 1905 1906 1907 1908
# equivalent to 30.days.to_i.from_now
1.month.to_i.from_now

# equivalent to 365.25.days.to_f.from_now
1.year.to_f.from_now
1909
```
A
Alexey Gaziev 已提交
1910

1911 1912
In such cases, Ruby's core [Date](http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html) and
[Time](http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html) should be used for precision
A
Alexey Gaziev 已提交
1913 1914
date and time arithmetic.

1915
NOTE: Defined in `active_support/core_ext/numeric/time.rb`.
A
Alexey Gaziev 已提交
1916

1917
### Formatting
1918 1919 1920 1921

Enables the formatting of numbers in a variety of ways.

Produce a string representation of a number as a telephone number:
1922

1923
```ruby
V
Vijay Dev 已提交
1924 1925 1926 1927
5551234.to_s(:phone)
# => 555-1234
1235551234.to_s(:phone)
# => 123-555-1234
1928
1235551234.to_s(:phone, area_code: true)
V
Vijay Dev 已提交
1929
# => (123) 555-1234
1930
1235551234.to_s(:phone, delimiter: " ")
V
Vijay Dev 已提交
1931
# => 123 555 1234
1932
1235551234.to_s(:phone, area_code: true, extension: 555)
V
Vijay Dev 已提交
1933
# => (123) 555-1234 x 555
1934
1235551234.to_s(:phone, country_code: 1)
V
Vijay Dev 已提交
1935
# => +1-123-555-1234
1936
```
1937 1938

Produce a string representation of a number as currency:
1939

1940
```ruby
1941 1942
1234567890.50.to_s(:currency)                 # => $1,234,567,890.50
1234567890.506.to_s(:currency)                # => $1,234,567,890.51
1943
1234567890.506.to_s(:currency, precision: 3)  # => $1,234,567,890.506
1944
```
1945 1946

Produce a string representation of a number as a percentage:
1947

1948
```ruby
V
Vijay Dev 已提交
1949 1950
100.to_s(:percentage)
# => 100.000%
1951
100.to_s(:percentage, precision: 0)
V
Vijay Dev 已提交
1952
# => 100%
1953
1000.to_s(:percentage, delimiter: '.', separator: ',')
V
Vijay Dev 已提交
1954
# => 1.000,000%
1955
302.24398923423.to_s(:percentage, precision: 5)
V
Vijay Dev 已提交
1956
# => 302.24399%
1957
```
1958 1959

Produce a string representation of a number in delimited form:
1960

1961
```ruby
1962 1963
12345678.to_s(:delimited)                     # => 12,345,678
12345678.05.to_s(:delimited)                  # => 12,345,678.05
1964 1965 1966
12345678.to_s(:delimited, delimiter: ".")     # => 12.345.678
12345678.to_s(:delimited, delimiter: ",")     # => 12,345,678
12345678.05.to_s(:delimited, separator: " ")  # => 12,345,678 05
1967
```
1968 1969

Produce a string representation of a number rounded to a precision:
1970

1971
```ruby
1972
111.2345.to_s(:rounded)                     # => 111.235
1973 1974 1975 1976
111.2345.to_s(:rounded, precision: 2)       # => 111.23
13.to_s(:rounded, precision: 5)             # => 13.00000
389.32314.to_s(:rounded, precision: 0)      # => 389
111.2345.to_s(:rounded, significant: true)  # => 111
1977
```
1978 1979

Produce a string representation of a number as a human-readable number of bytes:
1980

1981
```ruby
V
Vijay Dev 已提交
1982 1983 1984 1985 1986 1987
123.to_s(:human_size)            # => 123 Bytes
1234.to_s(:human_size)           # => 1.21 KB
12345.to_s(:human_size)          # => 12.1 KB
1234567.to_s(:human_size)        # => 1.18 MB
1234567890.to_s(:human_size)     # => 1.15 GB
1234567890123.to_s(:human_size)  # => 1.12 TB
1988
```
1989 1990

Produce a string representation of a number in human-readable words:
1991

1992
```ruby
V
Vijay Dev 已提交
1993 1994 1995 1996 1997 1998 1999
123.to_s(:human)               # => "123"
1234.to_s(:human)              # => "1.23 Thousand"
12345.to_s(:human)             # => "12.3 Thousand"
1234567.to_s(:human)           # => "1.23 Million"
1234567890.to_s(:human)        # => "1.23 Billion"
1234567890123.to_s(:human)     # => "1.23 Trillion"
1234567890123456.to_s(:human)  # => "1.23 Quadrillion"
2000
```
2001

2002
NOTE: Defined in `active_support/core_ext/numeric/conversions.rb`.
2003

2004
Extensions to `Integer`
2005
-----------------------
2006

2007
### `multiple_of?`
2008

2009
The method `multiple_of?` tests whether an integer is multiple of the argument:
2010

2011
```ruby
2012 2013
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false
2014
```
2015

2016
NOTE: Defined in `active_support/core_ext/integer/multiple.rb`.
2017

2018
### `ordinal`
2019

2020
The method `ordinal` returns the ordinal suffix string corresponding to the receiver integer:
2021

2022
```ruby
2023 2024 2025 2026 2027 2028
1.ordinal    # => "st"
2.ordinal    # => "nd"
53.ordinal   # => "rd"
2009.ordinal # => "th"
-21.ordinal  # => "st"
-134.ordinal # => "th"
2029
```
2030

2031
NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
2032

2033
### `ordinalize`
2034

2035
The method `ordinalize` returns the ordinal string corresponding to the receiver integer. In comparison, note that the `ordinal` method returns **only** the suffix string.
2036

2037
```ruby
2038 2039 2040 2041
1.ordinalize    # => "1st"
2.ordinalize    # => "2nd"
53.ordinalize   # => "53rd"
2009.ordinalize # => "2009th"
2042 2043
-21.ordinalize  # => "-21st"
-134.ordinalize # => "-134th"
2044
```
2045

2046
NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
2047

2048
Extensions to `BigDecimal`
2049
--------------------------
2050
### `to_s`
V
Vijay Dev 已提交
2051

2052 2053 2054 2055 2056 2057 2058
The method `to_s` is aliased to `to_formatted_s`. This provides a convenient way to display a BigDecimal value in floating-point notation:

```ruby
BigDecimal.new(5.00, 6).to_s  # => "5.0"
```

### `to_formatted_s`
V
Vijay Dev 已提交
2059

M
Mikhail Dieterle 已提交
2060
The method `to_formatted_s` provides a default specifier of "F".  This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation:
2061 2062 2063 2064 2065 2066

```ruby
BigDecimal.new(5.00, 6).to_formatted_s  # => "5.0"
```

and that symbol specifiers are also supported:
2067

2068 2069 2070 2071 2072 2073 2074 2075 2076
```ruby
BigDecimal.new(5.00, 6).to_formatted_s(:db)  # => "5.0"
```

Engineering notation is still supported:

```ruby
BigDecimal.new(5.00, 6).to_formatted_s("e")  # => "0.5E1"
```
2077

2078
Extensions to `Enumerable`
2079
--------------------------
2080

2081
### `sum`
2082

2083
The method `sum` adds the elements of an enumerable:
2084

2085
```ruby
2086 2087
[1, 2, 3].sum # => 6
(1..100).sum  # => 5050
2088
```
2089

2090
Addition only assumes the elements respond to `+`:
2091

2092
```ruby
2093 2094
[[1, 2], [2, 3], [3, 4]].sum    # => [1, 2, 2, 3, 3, 4]
%w(foo bar baz).sum             # => "foobarbaz"
2095
{a: 1, b: 2, c: 3}.sum # => [:b, 2, :c, 3, :a, 1]
2096
```
2097 2098 2099

The sum of an empty collection is zero by default, but this is customizable:

2100
```ruby
2101 2102
[].sum    # => 0
[].sum(1) # => 1
2103
```
2104

2105
If a block is given, `sum` becomes an iterator that yields the elements of the collection and sums the returned values:
2106

2107
```ruby
2108 2109
(1..5).sum {|n| n * 2 } # => 30
[2, 4, 6, 8, 10].sum    # => 30
2110
```
2111 2112 2113

The sum of an empty receiver can be customized in this form as well:

2114
```ruby
2115
[].sum(1) {|n| n**3} # => 1
2116
```
2117

2118
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2119

2120
### `index_by`
2121

2122
The method `index_by` generates a hash with the elements of an enumerable indexed by some key.
2123 2124 2125

It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:

2126
```ruby
2127 2128
invoices.index_by(&:number)
# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
2129
```
2130 2131 2132

WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.

2133
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2134

2135
### `many?`
2136

2137
The method `many?` is shorthand for `collection.size > 1`:
2138

2139
```erb
2140 2141 2142
<% if pages.many? %>
  <%= pagination_links %>
<% end %>
2143
```
2144

2145
If an optional block is given, `many?` only takes into account those elements that return true:
2146

2147
```ruby
2148
@see_more = videos.many? {|video| video.category == params[:category]}
2149
```
2150

2151
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2152

2153
### `exclude?`
2154

2155
The predicate `exclude?` tests whether a given object does **not** belong to the collection. It is the negation of the built-in `include?`:
2156

2157
```ruby
2158
to_visit << node if visited.exclude?(node)
2159
```
2160

2161
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2162

2163
Extensions to `Array`
2164
---------------------
2165

2166
### Accessing
2167

2168
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:
2169

2170
```ruby
2171 2172
%w(a b c d).to(2) # => %w(a b c)
[].to(7)          # => []
2173
```
2174

2175
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.
2176

2177
```ruby
2178
%w(a b c d).from(2)  # => %w(c d)
2179
%w(a b c d).from(10) # => []
X
Xavier Noria 已提交
2180
[].from(0)           # => []
2181
```
2182

2183
The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element (`first` is built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
2184

2185
```ruby
2186 2187
%w(a b c d).third # => c
%w(a b c d).fifth # => nil
2188
```
2189

2190
NOTE: Defined in `active_support/core_ext/array/access.rb`.
2191

2192
### Adding Elements
2193

2194
#### `prepend`
2195

2196
This method is an alias of `Array#unshift`.
2197

2198
```ruby
2199 2200
%w(a b c d).prepend('e')  # => %w(e a b c d)
[].prepend(10)            # => [10]
2201
```
2202

2203
NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
2204

2205
#### `append`
2206

2207
This method is an alias of `Array#<<`.
2208

2209
```ruby
2210 2211
%w(a b c d).append('e')  # => %w(a b c d e)
[].append([1,2])         # => [[1,2]]
2212
```
2213

2214
NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
2215

2216
### Options Extraction
2217

2218
When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets:
2219

2220
```ruby
2221
User.exists?(email: params[:email])
2222
```
2223 2224 2225

That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.

2226
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.
2227

2228
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.
2229

2230
Let's see for example the definition of the `caches_action` controller macro:
2231

2232
```ruby
2233 2234 2235 2236 2237
def caches_action(*actions)
  return unless cache_configured?
  options = actions.extract_options!
  ...
end
2238
```
2239

2240
This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to `extract_options!` you obtain the options hash and remove it from `actions` in a simple and explicit way.
2241

2242
NOTE: Defined in `active_support/core_ext/array/extract_options.rb`.
2243

2244
### Conversions
2245

2246
#### `to_sentence`
2247

2248
The method `to_sentence` turns an array into a string containing a sentence that enumerates its items:
2249

2250
```ruby
2251 2252 2253 2254
%w().to_sentence                # => ""
%w(Earth).to_sentence           # => "Earth"
%w(Earth Wind).to_sentence      # => "Earth and Wind"
%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
2255
```
2256 2257 2258

This method accepts three options:

2259 2260 2261
* `:two_words_connector`: What is used for arrays of length 2. Default is " and ".
* `:words_connector`: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
* `:last_word_connector`: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
2262

P
Prathamesh Sonpatki 已提交
2263
The defaults for these options can be localized, their keys are:
2264

2265 2266
| Option                 | I18n key                            |
| ---------------------- | ----------------------------------- |
2267 2268 2269
| `:two_words_connector` | `support.array.two_words_connector` |
| `:words_connector`     | `support.array.words_connector`     |
| `:last_word_connector` | `support.array.last_word_connector` |
2270

2271
Options `:connector` and `:skip_last_comma` are deprecated.
2272

2273
NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2274

2275
#### `to_formatted_s`
2276

2277
The method `to_formatted_s` acts like `to_s` by default.
2278

Y
Yves Senn 已提交
2279 2280 2281
If the array contains items that respond to `id`, however, the symbol
`:db` may be passed as argument. That's typically used with
collections of Active Record objects. Returned strings are:
2282

2283
```ruby
2284 2285 2286
[].to_formatted_s(:db)            # => "null"
[user].to_formatted_s(:db)        # => "8456"
invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
2287
```
2288

2289
Integers in the example above are supposed to come from the respective calls to `id`.
2290

2291
NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2292

2293
#### `to_xml`
2294

2295
The method `to_xml` returns a string containing an XML representation of its receiver:
2296

2297
```ruby
2298
Contributor.limit(2).order(:rank).to_xml
2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors type="array">
#   <contributor>
#     <id type="integer">4356</id>
#     <name>Jeremy Kemper</name>
#     <rank type="integer">1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id type="integer">4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank type="integer">2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
2315
```
2316

2317
To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise.
2318

2319
By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with `is_a?`) and they are not hashes. In the example above that's "contributors".
2320

A
Alexey Gaziev 已提交
2321
If there's any element that does not belong to the type of the first one the root node becomes "objects":
2322

2323
```ruby
2324 2325 2326
[Contributor.first, Commit.first].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
A
Alexey Gaziev 已提交
2327 2328
# <objects type="array">
#   <object>
2329 2330 2331 2332
#     <id type="integer">4583</id>
#     <name>Aaron Batalion</name>
#     <rank type="integer">53</rank>
#     <url-id>aaron-batalion</url-id>
A
Alexey Gaziev 已提交
2333 2334
#   </object>
#   <object>
2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
#     <author>Joshua Peek</author>
#     <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
#     <branch>origin/master</branch>
#     <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
#     <committer>Joshua Peek</committer>
#     <git-show nil="true"></git-show>
#     <id type="integer">190316</id>
#     <imported-from-svn type="boolean">false</imported-from-svn>
#     <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
#     <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
A
Alexey Gaziev 已提交
2345 2346
#   </object>
# </objects>
2347
```
2348

A
Alexey Gaziev 已提交
2349
If the receiver is an array of hashes the root element is by default also "objects":
2350

2351
```ruby
2352
[{a: 1, b: 2}, {c: 3}].to_xml
2353 2354
# =>
# <?xml version="1.0" encoding="UTF-8"?>
A
Alexey Gaziev 已提交
2355 2356
# <objects type="array">
#   <object>
2357 2358
#     <b type="integer">2</b>
#     <a type="integer">1</a>
A
Alexey Gaziev 已提交
2359 2360
#   </object>
#   <object>
2361
#     <c type="integer">3</c>
A
Alexey Gaziev 已提交
2362 2363
#   </object>
# </objects>
2364
```
2365

2366
WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the `:root` option to ensure a consistent root element.
2367

2368
The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option `:children` allows you to set these node names.
2369

2370
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
2371

2372
```ruby
2373
Contributor.limit(2).order(:rank).to_xml(skip_types: true)
2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors>
#   <contributor>
#     <id>4356</id>
#     <name>Jeremy Kemper</name>
#     <rank>1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id>4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank>2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
2390
```
2391

2392
NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2393

2394
### Wrapping
2395

2396
The method `Array.wrap` wraps its argument in an array unless it is already an array (or array-like).
2397 2398 2399

Specifically:

2400 2401
* If the argument is `nil` an empty list is returned.
* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
2402
* Otherwise, an array with the argument as its single element is returned.
2403

2404
```ruby
2405 2406 2407
Array.wrap(nil)       # => []
Array.wrap([1, 2, 3]) # => [1, 2, 3]
Array.wrap(0)         # => [0]
2408
```
2409

2410
This method is similar in purpose to `Kernel#Array`, but there are some differences:
2411

2412 2413 2414
* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
* It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
2415

2416
The last point is particularly worth comparing for some enumerables:
2417

2418
```ruby
2419
Array.wrap(foo: :bar) # => [{:foo=>:bar}]
2420
Array(foo: :bar)      # => [[:foo, :bar]]
2421
```
2422

2423 2424
There's also a related idiom that uses the splat operator:

2425
```ruby
2426
[*object]
2427
```
2428

2429
which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
2430

2431
Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s.
2432

2433
NOTE: Defined in `active_support/core_ext/array/wrap.rb`.
2434

2435
### Duplicating
A
Alexey Gaziev 已提交
2436

Y
Yves Senn 已提交
2437 2438
The method `Array.deep_dup` duplicates itself and all objects inside
recursively with Active Support method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside.
A
Alexey Gaziev 已提交
2439

2440
```ruby
A
Alexey Gaziev 已提交
2441 2442 2443 2444
array = [1, [2, 3]]
dup = array.deep_dup
dup[1][2] = 4
array[1][2] == nil   # => true
2445
```
A
Alexey Gaziev 已提交
2446

2447
NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
A
Alexey Gaziev 已提交
2448

2449
### Grouping
2450

2451
#### `in_groups_of(number, fill_with = nil)`
2452

2453
The method `in_groups_of` splits an array into consecutive groups of a certain size. It returns an array with the groups:
2454

2455
```ruby
2456
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
2457
```
2458 2459 2460

or yields them in turn if a block is passed:

2461
```html+erb
2462 2463
<% sample.in_groups_of(3) do |a, b, c| %>
  <tr>
2464 2465 2466
    <td><%= a %></td>
    <td><%= b %></td>
    <td><%= c %></td>
2467 2468
  </tr>
<% end %>
2469
```
2470

2471
The first example shows `in_groups_of` fills the last group with as many `nil` elements as needed to have the requested size. You can change this padding value using the second optional argument:
2472

2473
```ruby
2474
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
2475
```
2476

2477
And you can tell the method not to fill the last group passing `false`:
2478

2479
```ruby
2480
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
2481
```
2482

2483
As a consequence `false` can't be a used as a padding value.
2484

2485
NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2486

2487
#### `in_groups(number, fill_with = nil)`
2488

2489
The method `in_groups` splits an array into a certain number of groups. The method returns an array with the groups:
2490

2491
```ruby
2492 2493
%w(1 2 3 4 5 6 7).in_groups(3)
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
2494
```
2495 2496 2497

or yields them in turn if a block is passed:

2498
```ruby
2499 2500 2501 2502
%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
["1", "2", "3"]
["4", "5", nil]
["6", "7", nil]
2503
```
2504

2505
The examples above show that `in_groups` fills some groups with a trailing `nil` element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
2506 2507 2508

You can change this padding value using the second optional argument:

2509
```ruby
2510 2511
%w(1 2 3 4 5 6 7).in_groups(3, "0")
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
2512
```
2513

2514
And you can tell the method not to fill the smaller groups passing `false`:
2515

2516
```ruby
2517 2518
%w(1 2 3 4 5 6 7).in_groups(3, false)
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
2519
```
2520

2521
As a consequence `false` can't be a used as a padding value.
2522

2523
NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2524

2525
#### `split(value = nil)`
2526

2527
The method `split` divides an array by a separator and returns the resulting chunks.
2528 2529 2530

If a block is passed the separators are those elements of the array for which the block returns true:

2531
```ruby
2532 2533
(-5..5).to_a.split { |i| i.multiple_of?(4) }
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
2534
```
2535

2536
Otherwise, the value received as argument, which defaults to `nil`, is the separator:
2537

2538
```ruby
2539 2540
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
# => [[0], [-5], [], ["foo", "bar"]]
2541
```
2542

2543 2544
TIP: Observe in the previous example that consecutive separators result in empty arrays.

2545
NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2546

2547
Extensions to `Hash`
2548
--------------------
2549

2550
### Conversions
2551

2552
#### `to_xml`
2553

2554
The method `to_xml` returns a string containing an XML representation of its receiver:
2555

2556
```ruby
2557 2558 2559 2560 2561 2562 2563
{"foo" => 1, "bar" => 2}.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
#   <foo type="integer">1</foo>
#   <bar type="integer">2</bar>
# </hash>
2564
```
2565

2566
To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair `key`, `value`:
2567

2568
* If `value` is a hash there's a recursive call with `key` as `:root`.
2569

2570
* If `value` is an array there's a recursive call with `key` as `:root`, and `key` singularized as `:children`.
2571

2572
* If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. Its return value becomes a new node.
2573

2574
* If `value` responds to `to_xml` the method is invoked with `key` as `:root`.
2575

2576
* Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
2577

2578
```ruby
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590
XML_TYPE_NAMES = {
  "Symbol"     => "symbol",
  "Fixnum"     => "integer",
  "Bignum"     => "integer",
  "BigDecimal" => "decimal",
  "Float"      => "float",
  "TrueClass"  => "boolean",
  "FalseClass" => "boolean",
  "Date"       => "date",
  "DateTime"   => "datetime",
  "Time"       => "datetime"
}
2591
```
2592

2593
By default the root node is "hash", but that's configurable via the `:root` option.
2594

2595
The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.
2596

2597
NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
2598

2599
### Merging
2600

2601
Ruby has a built-in method `Hash#merge` that merges two hashes:
2602

2603
```ruby
2604
{a: 1, b: 1}.merge(a: 0, c: 2)
2605
# => {:a=>0, :b=>1, :c=>2}
2606
```
2607 2608 2609

Active Support defines a few more ways of merging hashes that may be convenient.

2610
#### `reverse_merge` and `reverse_merge!`
2611

2612
In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:
2613

2614
```ruby
2615
options = {length: 30, omission: "..."}.merge(options)
2616
```
2617

2618
Active Support defines `reverse_merge` in case you prefer this alternative notation:
2619

2620
```ruby
2621
options = options.reverse_merge(length: 30, omission: "...")
2622
```
2623

2624
And a bang version `reverse_merge!` that performs the merge in place:
2625

2626
```ruby
2627
options.reverse_merge!(length: 30, omission: "...")
2628
```
2629

2630
WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
2631

2632
NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
2633

2634
#### `reverse_update`
2635

2636
The method `reverse_update` is an alias for `reverse_merge!`, explained above.
2637

2638
WARNING. Note that `reverse_update` has no bang.
2639

2640
NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
2641

2642
#### `deep_merge` and `deep_merge!`
2643 2644 2645

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.

2646
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:
2647

2648
```ruby
2649
{a: {b: 1}}.deep_merge(a: {c: 2})
2650
# => {:a=>{:b=>1, :c=>2}}
2651
```
2652

2653
The method `deep_merge!` performs a deep merge in place.
2654

2655
NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
2656

2657
### Deep duplicating
A
Alexey Gaziev 已提交
2658

Y
Yves Senn 已提交
2659 2660
The method `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.
A
Alexey Gaziev 已提交
2661

2662
```ruby
2663
hash = { a: 1, b: { c: 2, d: [3, 4] } }
A
Alexey Gaziev 已提交
2664 2665 2666 2667 2668 2669 2670

dup = hash.deep_dup
dup[:b][:e] = 5
dup[:b][:d] << 5

hash[:b][:e] == nil      # => true
hash[:b][:d] == [3, 4]   # => true
2671
```
A
Alexey Gaziev 已提交
2672

2673
NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
A
Alexey Gaziev 已提交
2674

2675
### Working with Keys
2676

2677
#### `except` and `except!`
2678

2679
The method `except` returns a hash with the keys in the argument list removed, if present:
2680

2681
```ruby
2682
{a: 1, b: 2}.except(:a) # => {:b=>2}
2683
```
2684

2685
If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
2686

2687
```ruby
2688 2689
{a: 1}.with_indifferent_access.except(:a)  # => {}
{a: 1}.with_indifferent_access.except("a") # => {}
2690
```
2691

2692
There's also the bang variant `except!` that removes keys in the very receiver.
2693

2694
NOTE: Defined in `active_support/core_ext/hash/except.rb`.
2695

2696
#### `transform_keys` and `transform_keys!`
2697

2698
The method `transform_keys` accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
2699

2700
```ruby
2701
{nil => nil, 1 => 1, a: :a}.transform_keys{ |key| key.to_s.upcase }
2702
# => {"" => nil, "A" => :a, "1" => 1}
2703
```
2704 2705 2706

The result in case of collision is undefined:

2707
```ruby
2708
{"a" => 1, a: 2}.transform_keys{ |key| key.to_s.upcase }
2709
# => {"A" => 2}, in my test, can't rely on this result though
2710
```
2711

2712
This method may be useful for example to build specialized conversions. For instance `stringify_keys` and `symbolize_keys` use `transform_keys` to perform their key conversions:
2713

2714
```ruby
2715 2716 2717 2718 2719 2720 2721
def stringify_keys
  transform_keys{ |key| key.to_s }
end
...
def symbolize_keys
  transform_keys{ |key| key.to_sym rescue key }
end
2722
```
2723

2724
There's also the bang variant `transform_keys!` that applies the block operations to keys in the very receiver.
2725

2726
Besides that, one can use `deep_transform_keys` and `deep_transform_keys!` to perform the block operation on all the keys in the given hash and all the hashes nested into it. An example of the result is:
2727

2728
```ruby
2729
{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_transform_keys{ |key| key.to_s.upcase }
2730
# => {""=>nil, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
2731
```
2732

2733
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2734

2735
#### `stringify_keys` and `stringify_keys!`
2736

2737
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:
2738

2739
```ruby
2740
{nil => nil, 1 => 1, a: :a}.stringify_keys
2741
# => {"" => nil, "a" => :a, "1" => 1}
2742
```
2743 2744 2745

The result in case of collision is undefined:

2746
```ruby
2747
{"a" => 1, a: 2}.stringify_keys
2748
# => {"a" => 2}, in my test, can't rely on this result though
2749
```
2750

2751
This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines:
2752

2753
```ruby
2754 2755 2756 2757 2758
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
  options = options.stringify_keys
  options["type"] = "checkbox"
  ...
end
2759
```
2760

2761
The second line can safely access the "type" key, and let the user to pass either `:type` or "type".
2762

2763
There's also the bang variant `stringify_keys!` that stringifies keys in the very receiver.
2764

2765
Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to stringify all the keys in the given hash and all the hashes nested into it. An example of the result is:
2766

2767
```ruby
2768
{nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys
2769
# => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
2770
```
2771

2772
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2773

2774
#### `symbolize_keys` and `symbolize_keys!`
2775

2776
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:
2777

2778
```ruby
2779
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
2780
# => {1=>1, nil=>nil, :a=>"a"}
2781
```
2782 2783 2784 2785 2786

WARNING. Note in the previous example only one key was symbolized.

The result in case of collision is undefined:

2787
```ruby
2788
{"a" => 1, a: 2}.symbolize_keys
2789
# => {:a=>2}, in my test, can't rely on this result though
2790
```
2791

2792
This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
2793

2794
```ruby
2795 2796 2797 2798 2799
def rewrite_path(options)
  options = options.symbolize_keys
  options.update(options[:params].symbolize_keys) if options[:params]
  ...
end
2800
```
2801

2802
The second line can safely access the `:params` key, and let the user to pass either `:params` or "params".
2803

2804
There's also the bang variant `symbolize_keys!` that symbolizes keys in the very receiver.
2805

2806
Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to symbolize all the keys in the given hash and all the hashes nested into it. An example of the result is:
2807

2808
```ruby
2809
{nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys
2810
# => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
2811
```
2812

2813
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2814

2815
#### `to_options` and `to_options!`
2816

2817
The methods `to_options` and `to_options!` are respectively aliases of `symbolize_keys` and `symbolize_keys!`.
2818

2819
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2820

2821
#### `assert_valid_keys`
2822

2823
The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does `ArgumentError` is raised.
2824

2825
```ruby
2826 2827
{a: 1}.assert_valid_keys(:a)  # passes
{a: 1}.assert_valid_keys("a") # ArgumentError
2828
```
2829

2830
Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
2831

2832
NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2833

2834
### Slicing
2835

2836
Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
2837

2838
```ruby
2839
{a: 1, b: 2, c: 3}.slice(:a, :c)
2840
# => {:c=>3, :a=>1}
2841

2842
{a: 1, b: 2, c: 3}.slice(:b, :X)
2843
# => {:b=>2} # non-existing keys are ignored
2844
```
2845

2846
If the receiver responds to `convert_key` keys are normalized:
2847

2848
```ruby
2849
{a: 1, b: 2}.with_indifferent_access.slice("a")
2850
# => {:a=>1}
2851
```
2852 2853 2854

NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.

2855
There's also `slice!` which in addition to perform a slice in place returns what's removed:
2856

2857
```ruby
2858
hash = {a: 1, b: 2}
2859 2860
rest = hash.slice!(:a) # => {:b=>2}
hash                   # => {:a=>1}
2861
```
2862

2863
NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
2864

2865
### Extracting
S
Sebastian Martinez 已提交
2866

2867
The method `extract!` removes and returns the key/value pairs matching the given keys.
S
Sebastian Martinez 已提交
2868

2869
```ruby
2870
hash = {a: 1, b: 2}
2871 2872
rest = hash.extract!(:a) # => {:a=>1}
hash                     # => {:b=>2}
2873 2874 2875 2876 2877
```

The method `extract!` returns the same subclass of Hash, that the receiver is.

```ruby
2878
hash = {a: 1, b: 2}.with_indifferent_access
2879 2880
rest = hash.extract!(:a).class
# => ActiveSupport::HashWithIndifferentAccess
2881
```
S
Sebastian Martinez 已提交
2882

2883
NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
S
Sebastian Martinez 已提交
2884

2885
### Indifferent Access
2886

2887
The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
2888

2889
```ruby
2890
{a: 1}.with_indifferent_access["a"] # => 1
2891
```
2892

2893
NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
2894

2895
Extensions to `Regexp`
2896
----------------------
2897

2898
### `multiline?`
2899

2900
The method `multiline?` says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines.
2901

2902
```ruby
2903 2904 2905 2906 2907
%r{.}.multiline?  # => false
%r{.}m.multiline? # => true

Regexp.new('.').multiline?                    # => false
Regexp.new('.', Regexp::MULTILINE).multiline? # => true
2908
```
2909 2910 2911

Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.

2912
```ruby
2913 2914 2915 2916 2917 2918 2919
def assign_route_options(segments, defaults, requirements)
  ...
  if requirement.multiline?
    raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
  end
  ...
end
2920
```
2921

2922
NOTE: Defined in `active_support/core_ext/regexp.rb`.
2923

2924
Extensions to `Range`
2925
---------------------
2926

2927
### `to_s`
2928

2929
Active Support extends the method `Range#to_s` so that it understands an optional format argument. As of this writing the only supported non-default format is `:db`:
2930

2931
```ruby
2932 2933 2934 2935 2936
(Date.today..Date.tomorrow).to_s
# => "2009-10-25..2009-10-26"

(Date.today..Date.tomorrow).to_s(:db)
# => "BETWEEN '2009-10-25' AND '2009-10-26'"
2937
```
2938

2939
As the example depicts, the `:db` format generates a `BETWEEN` SQL clause. That is used by Active Record in its support for range values in conditions.
2940

2941
NOTE: Defined in `active_support/core_ext/range/conversions.rb`.
2942

2943
### `include?`
2944

2945
The methods `Range#include?` and `Range#===` say whether some value falls between the ends of a given instance:
2946

2947
```ruby
2948
(2..3).include?(Math::E) # => true
2949
```
2950

A
Alexey Gaziev 已提交
2951
Active Support extends these methods so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:
2952

2953
```ruby
2954 2955 2956 2957 2958
(1..10).include?(3..7)  # => true
(1..10).include?(0..7)  # => false
(1..10).include?(3..11) # => false
(1...9).include?(3..9)  # => false

A
Alexey Gaziev 已提交
2959 2960 2961 2962
(1..10) === (3..7)  # => true
(1..10) === (0..7)  # => false
(1..10) === (3..11) # => false
(1...9) === (3..9)  # => false
2963
```
2964

2965
NOTE: Defined in `active_support/core_ext/range/include_range.rb`.
2966

2967
### `overlaps?`
2968

2969
The method `Range#overlaps?` says whether any two given ranges have non-void intersection:
2970

2971
```ruby
2972 2973 2974
(1..10).overlaps?(7..11)  # => true
(1..10).overlaps?(0..7)   # => true
(1..10).overlaps?(11..27) # => false
2975
```
2976

2977
NOTE: Defined in `active_support/core_ext/range/overlaps.rb`.
2978

2979
Extensions to `Proc`
2980
--------------------
2981

2982
### `bind`
X
Xavier Noria 已提交
2983

2984
As you surely know Ruby has an `UnboundMethod` class whose instances are methods that belong to the limbo of methods without a self. The method `Module#instance_method` returns an unbound method for example:
X
Xavier Noria 已提交
2985

2986
```ruby
X
Xavier Noria 已提交
2987
Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
2988
```
X
Xavier Noria 已提交
2989

2990
An unbound method is not callable as is, you need to bind it first to an object with `bind`:
X
Xavier Noria 已提交
2991

2992
```ruby
X
Xavier Noria 已提交
2993
clear = Hash.instance_method(:clear)
2994
clear.bind({a: 1}).call # => {}
2995
```
X
Xavier Noria 已提交
2996

2997
Active Support defines `Proc#bind` with an analogous purpose:
X
Xavier Noria 已提交
2998

2999
```ruby
X
Xavier Noria 已提交
3000
Proc.new { size }.bind([]).call # => 0
3001
```
X
Xavier Noria 已提交
3002

3003
As you see that's callable and bound to the argument, the return value is indeed a `Method`.
X
Xavier Noria 已提交
3004

3005
NOTE: To do so `Proc#bind` actually creates a method under the hood. If you ever see a method with a weird name like `__bind_1256598120_237302` in a stack trace you know now where it comes from.
X
Xavier Noria 已提交
3006

3007
Action Pack uses this trick in `rescue_from` for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by `handler_for_rescue`, thus simplifying the code in the caller:
X
Xavier Noria 已提交
3008

3009
```ruby
X
Xavier Noria 已提交
3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021
def handler_for_rescue(exception)
  _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
    ...
  end

  case rescuer
  when Symbol
    method(rescuer)
  when Proc
    rescuer.bind(self)
  end
end
3022
```
3023

3024
NOTE: Defined in `active_support/core_ext/proc.rb`.
3025

3026
Extensions to `Date`
3027
--------------------
3028

3029
### Calculations
3030

3031
NOTE: All the following methods are defined in `active_support/core_ext/date/calculations.rb`.
3032

3033
INFO: The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, `Date.new(1582, 10, 4).tomorrow` returns `Date.new(1582, 10, 15)` and so on. Please check `test/core_ext/date_ext_test.rb` in the Active Support test suite for expected behavior.
3034

3035
#### `Date.current`
3036

3037
Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Date.current`.
3038

3039
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`.
3040

3041
#### Named dates
3042

3043
##### `prev_year`, `next_year`
3044

3045
In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year:
3046

3047
```ruby
3048
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3049
d.prev_year              # => Fri, 08 May 2009
3050
d.next_year              # => Sun, 08 May 2011
3051
```
3052 3053 3054

If date is the 29th of February of a leap year, you obtain the 28th:

3055
```ruby
3056
d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
3057
d.prev_year               # => Sun, 28 Feb 1999
3058
d.next_year               # => Wed, 28 Feb 2001
3059
```
3060

3061
`prev_year` is aliased to `last_year`.
3062

3063
##### `prev_month`, `next_month`
3064

3065
In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month:
3066

3067
```ruby
3068
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3069
d.prev_month             # => Thu, 08 Apr 2010
3070
d.next_month             # => Tue, 08 Jun 2010
3071
```
3072 3073 3074

If such a day does not exist, the last day of the corresponding month is returned:

3075
```ruby
3076 3077
Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
3078 3079
Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
3080
```
3081

3082
`prev_month` is aliased to `last_month`.
3083

3084
##### `prev_quarter`, `next_quarter`
3085

3086
Same as `prev_month` and `next_month`. It returns the date with the same day in the previous or next quarter:
3087

3088
```ruby
3089 3090 3091
t = Time.local(2010, 5, 8) # => Sat, 08 May 2010
t.prev_quarter             # => Mon, 08 Feb 2010
t.next_quarter             # => Sun, 08 Aug 2010
3092
```
3093 3094 3095

If such a day does not exist, the last day of the corresponding month is returned:

3096
```ruby
3097 3098 3099 3100
Time.local(2000, 7, 31).prev_quarter  # => Sun, 30 Apr 2000
Time.local(2000, 5, 31).prev_quarter  # => Tue, 29 Feb 2000
Time.local(2000, 10, 31).prev_quarter # => Mon, 30 Oct 2000
Time.local(2000, 11, 31).next_quarter # => Wed, 28 Feb 2001
3101
```
3102

3103
`prev_quarter` is aliased to `last_quarter`.
3104

3105
##### `beginning_of_week`, `end_of_week`
3106

3107
The methods `beginning_of_week` and `end_of_week` return the dates for the
3108
beginning and end of the week, respectively. Weeks are assumed to start on
3109 3110
Monday, but that can be changed passing an argument, setting thread local
`Date.beginning_of_week` or `config.beginning_of_week`.
3111

3112
```ruby
3113 3114 3115 3116 3117
d = Date.new(2010, 5, 8)     # => Sat, 08 May 2010
d.beginning_of_week          # => Mon, 03 May 2010
d.beginning_of_week(:sunday) # => Sun, 02 May 2010
d.end_of_week                # => Sun, 09 May 2010
d.end_of_week(:sunday)       # => Sat, 08 May 2010
3118
```
3119

3120
`beginning_of_week` is aliased to `at_beginning_of_week` and `end_of_week` is aliased to `at_end_of_week`.
3121

3122
##### `monday`, `sunday`
V
Vijay Dev 已提交
3123

3124 3125
The methods `monday` and `sunday` return the dates for the previous Monday and
next Sunday, respectively.
V
Vijay Dev 已提交
3126

3127
```ruby
V
Vijay Dev 已提交
3128 3129 3130
d = Date.new(2010, 5, 8)     # => Sat, 08 May 2010
d.monday                     # => Mon, 03 May 2010
d.sunday                     # => Sun, 09 May 2010
3131 3132 3133 3134 3135 3136

d = Date.new(2012, 9, 10)    # => Mon, 10 Sep 2012
d.monday                     # => Mon, 10 Sep 2012

d = Date.new(2012, 9, 16)    # => Sun, 16 Sep 2012
d.sunday                     # => Sun, 16 Sep 2012
3137
```
V
Vijay Dev 已提交
3138

3139
##### `prev_week`, `next_week`
3140

X
Xavier Noria 已提交
3141
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.
3142

3143
```ruby
3144 3145 3146
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.next_week              # => Mon, 10 May 2010
d.next_week(:saturday)   # => Sat, 15 May 2010
3147
```
3148

3149
The method `prev_week` is analogous:
3150

3151
```ruby
3152 3153 3154
d.prev_week              # => Mon, 26 Apr 2010
d.prev_week(:saturday)   # => Sat, 01 May 2010
d.prev_week(:friday)     # => Fri, 30 Apr 2010
3155
```
3156

3157
`prev_week` is aliased to `last_week`.
X
Xavier Noria 已提交
3158 3159

Both `next_week` and `prev_week` work as expected when `Date.beginning_of_week` or `config.beginning_of_week` are set.
3160

3161
##### `beginning_of_month`, `end_of_month`
3162

3163
The methods `beginning_of_month` and `end_of_month` return the dates for the beginning and end of the month:
3164

3165
```ruby
3166 3167 3168
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_month     # => Sat, 01 May 2010
d.end_of_month           # => Mon, 31 May 2010
3169
```
3170

3171
`beginning_of_month` is aliased to `at_beginning_of_month`, and `end_of_month` is aliased to `at_end_of_month`.
3172

3173
##### `beginning_of_quarter`, `end_of_quarter`
3174

3175
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:
3176

3177
```ruby
3178 3179 3180
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_quarter   # => Thu, 01 Apr 2010
d.end_of_quarter         # => Wed, 30 Jun 2010
3181
```
3182

3183
`beginning_of_quarter` is aliased to `at_beginning_of_quarter`, and `end_of_quarter` is aliased to `at_end_of_quarter`.
3184

3185
##### `beginning_of_year`, `end_of_year`
3186

3187
The methods `beginning_of_year` and `end_of_year` return the dates for the beginning and end of the year:
3188

3189
```ruby
3190 3191 3192
d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
d.beginning_of_year      # => Fri, 01 Jan 2010
d.end_of_year            # => Fri, 31 Dec 2010
3193
```
3194

3195
`beginning_of_year` is aliased to `at_beginning_of_year`, and `end_of_year` is aliased to `at_end_of_year`.
3196

3197
#### Other Date Computations
3198

3199
##### `years_ago`, `years_since`
3200

3201
The method `years_ago` receives a number of years and returns the same date those many years ago:
3202

3203
```ruby
3204 3205
date = Date.new(2010, 6, 7)
date.years_ago(10) # => Wed, 07 Jun 2000
3206
```
3207

3208
`years_since` moves forward in time:
3209

3210
```ruby
3211 3212
date = Date.new(2010, 6, 7)
date.years_since(10) # => Sun, 07 Jun 2020
3213
```
3214 3215 3216

If such a day does not exist, the last day of the corresponding month is returned:

3217
```ruby
3218 3219
Date.new(2012, 2, 29).years_ago(3)     # => Sat, 28 Feb 2009
Date.new(2012, 2, 29).years_since(3)   # => Sat, 28 Feb 2015
3220
```
3221

3222
##### `months_ago`, `months_since`
3223

3224
The methods `months_ago` and `months_since` work analogously for months:
3225

3226
```ruby
3227 3228
Date.new(2010, 4, 30).months_ago(2)   # => Sun, 28 Feb 2010
Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
3229
```
3230 3231 3232

If such a day does not exist, the last day of the corresponding month is returned:

3233
```ruby
3234 3235
Date.new(2010, 4, 30).months_ago(2)    # => Sun, 28 Feb 2010
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
3236
```
3237

3238
##### `weeks_ago`
3239

3240
The method `weeks_ago` works analogously for weeks:
3241

3242
```ruby
3243 3244
Date.new(2010, 5, 24).weeks_ago(1)    # => Mon, 17 May 2010
Date.new(2010, 5, 24).weeks_ago(2)    # => Mon, 10 May 2010
3245
```
3246

3247
##### `advance`
3248

3249
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:
3250

3251
```ruby
3252
date = Date.new(2010, 6, 6)
3253 3254
date.advance(years: 1, weeks: 2)  # => Mon, 20 Jun 2011
date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
3255
```
3256 3257 3258 3259 3260

Note in the previous example that increments may be negative.

To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.

3261
The method `advance` advances first one month, and then one day, the result is:
3262

3263
```ruby
3264
Date.new(2010, 2, 28).advance(months: 1, days: 1)
3265
# => Sun, 29 Mar 2010
3266
```
3267 3268 3269

While if it did it the other way around the result would be different:

3270
```ruby
3271
Date.new(2010, 2, 28).advance(days: 1).advance(months: 1)
3272
# => Thu, 01 Apr 2010
3273
```
3274

3275
#### Changing Components
3276

3277
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:
3278

3279
```ruby
3280
Date.new(2010, 12, 23).change(year: 2011, month: 11)
3281
# => Wed, 23 Nov 2011
3282
```
3283

3284
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
3285

3286
```ruby
3287
Date.new(2010, 1, 31).change(month: 2)
3288
# => ArgumentError: invalid date
3289
```
3290

3291
#### Durations
3292

E
Evan Farrar 已提交
3293
Durations can be added to and subtracted from dates:
3294

3295
```ruby
3296 3297 3298 3299 3300 3301
d = Date.current
# => Mon, 09 Aug 2010
d + 1.year
# => Tue, 09 Aug 2011
d - 3.hours
# => Sun, 08 Aug 2010 21:00:00 UTC +00:00
3302
```
3303

3304
They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3305

3306
```ruby
3307 3308
Date.new(1582, 10, 4) + 1.day
# => Fri, 15 Oct 1582
3309
```
3310

3311
#### Timestamps
3312

3313
INFO: The following methods return a `Time` object if possible, otherwise a `DateTime`. If set, they honor the user time zone.
3314

3315
##### `beginning_of_day`, `end_of_day`
3316

3317
The method `beginning_of_day` returns a timestamp at the beginning of the day (00:00:00):
3318

3319
```ruby
3320
date = Date.new(2010, 6, 7)
3321
date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010
3322
```
3323

3324
The method `end_of_day` returns a timestamp at the end of the day (23:59:59):
3325

3326
```ruby
3327
date = Date.new(2010, 6, 7)
3328
date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010
3329
```
3330

3331
`beginning_of_day` is aliased to `at_beginning_of_day`, `midnight`, `at_midnight`.
3332

3333
##### `beginning_of_hour`, `end_of_hour`
3334

3335
The method `beginning_of_hour` returns a timestamp at the beginning of the hour (hh:00:00):
3336

3337
```ruby
3338 3339
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010
3340
```
3341

3342
The method `end_of_hour` returns a timestamp at the end of the hour (hh:59:59):
3343

3344
```ruby
3345 3346
date = DateTime.new(2010, 6, 7, 19, 55, 25)
date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010
3347
```
3348

3349
`beginning_of_hour` is aliased to `at_beginning_of_hour`.
3350

3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369
##### `beginning_of_minute`, `end_of_minute`

The method `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):

```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`.

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.
3370

3371
##### `ago`, `since`
3372

3373
The method `ago` receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
3374

3375
```ruby
3376
date = Date.current # => Fri, 11 Jun 2010
3377
date.ago(1)         # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
3378
```
3379

3380
Similarly, `since` moves forward:
3381

3382
```ruby
3383
date = Date.current # => Fri, 11 Jun 2010
3384
date.since(1)       # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
3385
```
3386

3387
#### Other Time Computations
3388

3389
### Conversions
3390

3391
Extensions to `DateTime`
3392
------------------------
3393

3394
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.
3395

3396
### Calculations
3397

3398
NOTE: All the following methods are defined in `active_support/core_ext/date_time/calculations.rb`.
3399

3400
The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ext/date/calculations.rb` you inherit these methods and their aliases, except that they will always return datetimes:
3401

3402
```ruby
3403 3404
yesterday
tomorrow
3405
beginning_of_week (at_beginning_of_week)
V
Vijay Dev 已提交
3406
end_of_week (at_end_of_week)
3407 3408
monday
sunday
3409
weeks_ago
3410
prev_week (last_week)
3411 3412 3413
next_week
months_ago
months_since
3414 3415
beginning_of_month (at_beginning_of_month)
end_of_month (at_end_of_month)
3416
prev_month (last_month)
3417
next_month
3418 3419 3420 3421
beginning_of_quarter (at_beginning_of_quarter)
end_of_quarter (at_end_of_quarter)
beginning_of_year (at_beginning_of_year)
end_of_year (at_end_of_year)
3422 3423
years_ago
years_since
3424
prev_year (last_year)
3425
next_year
3426
```
3427

3428
The following methods are reimplemented so you do **not** need to load `active_support/core_ext/date/calculations.rb` for these ones:
3429

3430
```ruby
3431
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
3432 3433
end_of_day
ago
3434
since (in)
3435
```
3436

3437
On the other hand, `advance` and `change` are also defined and support more options, they are documented below.
3438

3439
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:
3440

3441
```ruby
3442 3443
beginning_of_hour (at_beginning_of_hour)
end_of_hour
3444
```
3445

3446
#### Named Datetimes
3447

3448
##### `DateTime.current`
3449

3450
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`.
3451

3452
#### Other Extensions
3453

3454
##### `seconds_since_midnight`
3455

3456
The method `seconds_since_midnight` returns the number of seconds since midnight:
3457

3458
```ruby
3459 3460
now = DateTime.current     # => Mon, 07 Jun 2010 20:26:36 +0000
now.seconds_since_midnight # => 73596
3461
```
3462

3463
##### `utc`
3464

3465
The method `utc` gives you the same datetime in the receiver expressed in UTC.
3466

3467
```ruby
3468 3469
now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
now.utc                # => Mon, 07 Jun 2010 23:27:52 +0000
3470
```
3471

3472
This method is also aliased as `getutc`.
3473

3474
##### `utc?`
3475

3476
The predicate `utc?` says whether the receiver has UTC as its time zone:
3477

3478
```ruby
3479 3480 3481
now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
now.utc?           # => false
now.utc.utc?       # => true
3482
```
3483

3484
##### `advance`
3485

3486
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.
3487

3488
```ruby
3489 3490
d = DateTime.current
# => Thu, 05 Aug 2010 11:33:31 +0000
3491
d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
3492
# => Tue, 06 Sep 2011 12:34:32 +0000
3493
```
3494

3495
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.
3496 3497 3498

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:

3499
```ruby
3500 3501
d = DateTime.new(2010, 2, 28, 23, 59, 59)
# => Sun, 28 Feb 2010 23:59:59 +0000
3502
d.advance(months: 1, seconds: 1)
3503
# => Mon, 29 Mar 2010 00:00:00 +0000
3504
```
3505 3506 3507

but if we computed them the other way around, the result would be different:

3508
```ruby
3509
d.advance(seconds: 1).advance(months: 1)
3510
# => Thu, 01 Apr 2010 00:00:00 +0000
3511
```
3512

3513
WARNING: Since `DateTime` is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
3514

3515
#### Changing Components
3516

3517
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`:
3518

3519
```ruby
3520 3521
now = DateTime.current
# => Tue, 08 Jun 2010 01:56:22 +0000
3522
now.change(year: 2011, offset: Rational(-6, 24))
3523
# => Wed, 08 Jun 2011 01:56:22 -0600
3524
```
3525 3526 3527

If hours are zeroed, then minutes and seconds are too (unless they have given values):

3528
```ruby
3529
now.change(hour: 0)
3530
# => Tue, 08 Jun 2010 00:00:00 +0000
3531
```
3532 3533 3534

Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):

3535
```ruby
3536
now.change(min: 0)
3537
# => Tue, 08 Jun 2010 01:00:00 +0000
3538
```
3539

3540
This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
3541

3542
```ruby
3543
DateTime.current.change(month: 2, day: 30)
3544
# => ArgumentError: invalid date
3545
```
3546

3547
#### Durations
3548

E
Evan Farrar 已提交
3549
Durations can be added to and subtracted from datetimes:
3550

3551
```ruby
3552 3553 3554 3555 3556 3557
now = DateTime.current
# => Mon, 09 Aug 2010 23:15:17 +0000
now + 1.year
# => Tue, 09 Aug 2011 23:15:17 +0000
now - 1.week
# => Mon, 02 Aug 2010 23:15:17 +0000
3558
```
3559

3560
They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3561

3562
```ruby
3563 3564
DateTime.new(1582, 10, 4, 23) + 1.hour
# => Fri, 15 Oct 1582 00:00:00 +0000
3565
```
3566

3567
Extensions to `Time`
3568
--------------------
3569

3570
### Calculations
3571

3572
NOTE: All the following methods are defined in `active_support/core_ext/time/calculations.rb`.
3573

3574
Active Support adds to `Time` many of the methods available for `DateTime`:
3575

3576
```ruby
3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588
past?
today?
future?
yesterday
tomorrow
seconds_since_midnight
change
advance
ago
since (in)
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
end_of_day
3589 3590
beginning_of_hour (at_beginning_of_hour)
end_of_hour
3591
beginning_of_week (at_beginning_of_week)
V
Vijay Dev 已提交
3592
end_of_week (at_end_of_week)
3593
monday
V
Vijay Dev 已提交
3594
sunday
3595
weeks_ago
3596
prev_week (last_week)
3597 3598 3599 3600 3601
next_week
months_ago
months_since
beginning_of_month (at_beginning_of_month)
end_of_month (at_end_of_month)
3602
prev_month (last_month)
3603 3604 3605 3606 3607 3608 3609
next_month
beginning_of_quarter (at_beginning_of_quarter)
end_of_quarter (at_end_of_quarter)
beginning_of_year (at_beginning_of_year)
end_of_year (at_end_of_year)
years_ago
years_since
3610
prev_year (last_year)
3611
next_year
3612
```
3613 3614 3615

They are analogous. Please refer to their documentation above and take into account the following differences:

3616 3617
* `change` accepts an additional `:usec` option.
* `Time` understands DST, so you get correct DST calculations as in
3618

3619
```ruby
3620 3621 3622
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>

3623
# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
3624
t = Time.local(2010, 3, 28, 1, 59, 59)
V
Vijay Dev 已提交
3625
# => Sun Mar 28 01:59:59 +0100 2010
3626
t.advance(seconds: 1)
V
Vijay Dev 已提交
3627
# => Sun Mar 28 03:00:00 +0200 2010
3628
```
3629

3630
* If `since` or `ago` jump to a time that can't be expressed with `Time` a `DateTime` object is returned instead.
3631

3632
#### `Time.current`
3633

3634
Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines `Time.yesterday` and `Time.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Time.current`.
3635

3636
When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` and not `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.today` uses by default. This means `Time.now` may equal `Time.yesterday`.
3637

3638
#### `all_day`, `all_week`, `all_month`, `all_quarter` and `all_year`
3639

3640
The method `all_day` returns a range representing the whole day of the current time.
3641

3642
```ruby
3643
now = Time.current
V
Vijay Dev 已提交
3644
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
3645
now.all_day
3646
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
3647
```
3648

3649
Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges.
3650

3651
```ruby
3652
now = Time.current
V
Vijay Dev 已提交
3653
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
3654
now.all_week
3655
# => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
3656 3657
now.all_week(:sunday)
# => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +00:00
3658
now.all_month
3659
# => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
3660
now.all_quarter
3661
# => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
3662
now.all_year
3663
# => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
3664
```
3665

3666
### Time Constructors
3667

3668
Active Support defines `Time.current` to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`:
3669

3670
```ruby
3671 3672 3673
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
Time.current
V
Vijay Dev 已提交
3674
# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
3675
```
3676

3677
Analogously to `DateTime`, the predicates `past?`, and `future?` are relative to `Time.current`.
3678

3679
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.
3680

3681
#### Durations
3682

E
Evan Farrar 已提交
3683
Durations can be added to and subtracted from time objects:
3684

3685
```ruby
3686 3687 3688 3689 3690 3691
now = Time.current
# => Mon, 09 Aug 2010 23:20:05 UTC +00:00
now + 1.year
#  => Tue, 09 Aug 2011 23:21:11 UTC +00:00
now - 1.week
# => Mon, 02 Aug 2010 23:21:11 UTC +00:00
3692
```
3693

3694
They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3695

3696
```ruby
3697
Time.utc(1582, 10, 3) + 5.days
3698
# => Mon Oct 18 00:00:00 UTC 1582
3699
```
3700

3701
Extensions to `File`
3702
--------------------
3703

3704
### `atomic_write`
3705

3706
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.
3707

3708
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.
3709

3710
For example, Action Pack uses this method to write asset cache files like `all.css`:
3711

3712
```ruby
3713 3714 3715
File.atomic_write(joined_asset_path) do |cache|
  cache.write(join_asset_file_contents(asset_paths))
end
3716
```
3717

3718 3719 3720
To accomplish this `atomic_write` creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists `atomic_write` overwrites it and keeps owners and permissions. However there are a few cases where `atomic_write` cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is accessible to the processes that need it.

NOTE. Due to the chmod operation `atomic_write` performs, if the target file has an ACL set on it this ACL will be recalculated/modified.
3721

3722
WARNING. Note you can't append with `atomic_write`.
3723 3724 3725

The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.

3726
NOTE: Defined in `active_support/core_ext/file/atomic.rb`.
3727

3728
Extensions to `Marshal`
X
Xavier Noria 已提交
3729
-----------------------
3730 3731 3732

### `load`

X
Xavier Noria 已提交
3733
Active Support adds constant autoloading support to `load`.
3734

3735
For example, the file cache store deserializes this way:
3736 3737 3738 3739 3740

```ruby
File.open(file_name) { |f| Marshal.load(f) }
```

3741
If the cached data refers to a constant that is unknown at that point, the autoloading mechanism is triggered and if it succeeds the deserialization is retried transparently.
3742

X
Xavier Noria 已提交
3743
WARNING. If the argument is an `IO` it needs to respond to `rewind` to be able to retry. Regular files respond to `rewind`.
3744 3745 3746

NOTE: Defined in `active_support/core_ext/marshal.rb`.

3747
Extensions to `Logger`
3748
----------------------
3749

3750
### `around_[level]`
3751

3752
Takes two arguments, a `before_message` and `after_message` and calls the current level method on the `Logger` instance, passing in the `before_message`, then the specified message, then the `after_message`:
3753

3754
```ruby
V
Vijay Dev 已提交
3755 3756
logger = Logger.new("log/development.log")
logger.around_info("before", "after") { |logger| logger.info("during") }
3757
```
3758

3759
### `silence`
3760 3761 3762

Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.

3763
```ruby
V
Vijay Dev 已提交
3764 3765 3766 3767 3768
logger = Logger.new("log/development.log")
logger.silence(Logger::INFO) do
  logger.debug("In space, no one can hear you scream.")
  logger.info("Scream all you want, small mailman!")
end
3769
```
3770

3771
### `datetime_format=`
3772

3773
Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a `datetime_format` method then this is ignored.
3774

3775
```ruby
V
Vijay Dev 已提交
3776 3777
class Logger::FormatWithTime < Logger::Formatter
  cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
V
Vijay Dev 已提交
3778

V
Vijay Dev 已提交
3779 3780
  def self.call(severity, timestamp, progname, msg)
    "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
3781
  end
V
Vijay Dev 已提交
3782
end
V
Vijay Dev 已提交
3783

V
Vijay Dev 已提交
3784 3785 3786
logger = Logger.new("log/development.log")
logger.formatter = Logger::FormatWithTime
logger.info("<- is the current time")
3787
```
3788

3789
NOTE: Defined in `active_support/core_ext/logger.rb`.
3790

3791
Extensions to `NameError`
3792
-------------------------
3793

3794
Active Support adds `missing_name?` to `NameError`, which tests whether the exception was raised because of the name passed as argument.
3795 3796 3797

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.

3798
TIP: A symbol can represent a fully-qualified constant name as in `:"ActiveRecord::Base"`, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
3799

3800
For example, when an action of `PostsController` is called Rails tries optimistically to use `PostsHelper`. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that `posts_helper.rb` raises a `NameError` due to an actual unknown constant. That should be reraised. The method `missing_name?` provides a way to distinguish both cases:
3801

3802
```ruby
3803 3804 3805 3806 3807
def default_helper_module!
  module_name = name.sub(/Controller$/, '')
  module_path = module_name.underscore
  helper module_path
rescue MissingSourceFile => e
3808
  raise e unless e.is_missing? "helpers/#{module_path}_helper"
3809 3810 3811
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
3812
```
3813

3814
NOTE: Defined in `actionpack/lib/abstract_controller/helpers.rb`.
3815

3816
Extensions to `LoadError`
3817
-------------------------
3818

3819
Active Support adds `is_missing?` to `LoadError`, and also assigns that class to the constant `MissingSourceFile` for backwards compatibility.
3820

3821
Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
3822

3823
For example, when an action of `PostsController` is called Rails tries to load `posts_helper.rb`, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method `is_missing?` provides a way to distinguish both cases:
3824

3825
```ruby
3826 3827 3828 3829 3830
def default_helper_module!
  module_name = name.sub(/Controller$/, '')
  module_path = module_name.underscore
  helper module_path
rescue MissingSourceFile => e
3831
  raise e unless e.is_missing? "helpers/#{module_path}_helper"
3832 3833 3834
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
3835
```
3836

3837
NOTE: Defined in `actionpack/lib/abstract_controller/helpers.rb`.