active_support_core_extensions.textile 107.3 KB
Newer Older
1 2
h2. Active Support Core Extensions

3
Active Support is the Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff. It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Rails itself.
4 5 6 7 8

By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Rails.

endprologue.

9 10
h3. How to Load Core Extensions

11 12
h4. Stand-Alone Active Support

13 14 15 16 17 18 19 20 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 may load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.

Thus, after a simple require like:

<ruby>
require 'active_support'
</ruby>

objects do not even respond to +blank?+, let's see how to load its definition.

23
h5. Cherry-picking a Definition
24 25 26

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

27
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:
28 29 30 31 32 33 34 35 36 37 38

NOTE: Defined in +active_support/core_ext/object/blank.rb+.

That means that this single call is enough:

<ruby>
require 'active_support/core_ext/object/blank'
</ruby>

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

39
h5. Loading Grouped Core Extensions
40 41 42 43 44 45 46 47 48

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

Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+:

<ruby>
require 'active_support/core_ext/object'
</ruby>

49
h5. Loading All Core Extensions
50 51 52 53 54 55 56

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

<ruby>
require 'active_support/core_ext'
</ruby>

57
h5. Loading All Active Support
58 59 60 61 62 63 64 65 66

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

<ruby>
require 'active_support/all'
</ruby>

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.

67 68 69 70
h4. Active Support Within a Ruby on Rails Application

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

71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
h3. Extensions to All Objects

h4. +blank?+ and +present?+

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

* +nil+ and +false+,

* strings composed only of whitespace, i.e. matching +/\A\s*\z/+,

* empty arrays and hashes, and

* any other object that responds to +empty?+ and it is empty.

WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.

For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot:

<ruby>
def charset
  charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
  charset.blank? ? nil : charset.strip.split("=")[1]
end
</ruby>

That's a typical use case for +blank?+.

Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none:

<ruby>
def instantiate_observers
  return if @observers.blank?
  # ...
end
</ruby>

The method +present?+ is equivalent to +!blank?+:

<ruby>
assert @response.body.present? # same as !@response.body.blank?
</ruby>

113 114
NOTE: Defined in +active_support/core_ext/object/blank.rb+.

X
Xavier Noria 已提交
115 116 117 118 119 120 121 122
h4. +presence+

The +presence+ method returns its receiver if +present?+, and +nil+ otherwise. It is useful for idioms like this:

<ruby>
host = config[:host].presence || 'localhost'
</ruby>

123 124
NOTE: Defined in +active_support/core_ext/object/blank.rb+.

125 126
h4. +duplicable?+

127
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:
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157

<ruby>
1.object_id                 # => 3
Math.cos(0).to_i.object_id  # => 3
</ruby>

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

<ruby>
true.dup  # => TypeError: can't dup TrueClass
</ruby>

Some numbers which are not singletons are not duplicable either:

<ruby>
0.0.clone        # => allocator undefined for Float
(2**1024).clone  # => allocator undefined for Bignum
</ruby>

Active Support provides +duplicable?+ to programmatically query an object about this property:

<ruby>
"".duplicable?     # => true
false.duplicable?  # => false
</ruby>

By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects.

WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded list. Classes have means to disallow duplication like removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell.

158 159
NOTE: Defined in +active_support/core_ext/object/duplicable.rb+.

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
h4. +try+

Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first.

For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+:

<ruby>
def log_info(sql, name, ms)
  if @logger && @logger.debug?
    name = '%s (%.1fms)' % [name || 'SQL', ms]
    @logger.debug(format_log_entry(name, sql.squeeze(' ')))
  end
end
</ruby>

175
You can shorten that using +Object#try+. This method is a synonym for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as:
176 177 178 179 180 181 182 183 184 185

<ruby>
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
</ruby>

186 187
NOTE: Defined in +active_support/core_ext/object/try.rb+.

188
h4. +singleton_class+
189

190
The method +singleton_class+ returns the singleton class of the receiver:
191 192

<ruby>
193 194
String.singleton_class     # => #<Class:String>
String.new.singleton_class # => #<Class:#<String:0x17a1d1c>>
195 196
</ruby>

197
WARNING: Fixnums and symbols have no singleton classes, +singleton_class+ raises +TypeError+ on them. Moreover, the singleton classes of +nil+, +true+, and +false+, are +NilClass+, +TrueClass+, and +FalseClass+, respectively.
198

199
NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
200

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
h4. +class_eval(*args, &block)+

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

<ruby>
class Proc
  def bind(object)
    block, time = self, Time.now
    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
</ruby>

220
NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+.
221

222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
h4. +acts_like?(duck)+

The method +acts_like+ provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as +String+ defines

<ruby>
def acts_like_string?
end
</ruby>

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

<ruby>
some_klass.acts_like?(:string)
</ruby>

Rails has classes that act like +Date+ or +Time+ and follow this contract.

239 240
NOTE: Defined in +active_support/core_ext/object/acts_like.rb+.

241 242
h4. +to_param+

R
rohit 已提交
243
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.
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280

By default +to_param+ just calls +to_s+:

<ruby>
7.to_param # => "7"
</ruby>

The return value of +to_param+ should *not* be escaped:

<ruby>
"Tom & Jerry".to_param # => "Tom & Jerry"
</ruby>

Several classes in Rails overwrite this method.

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

<ruby>
[0, true, String].to_param # => "0/true/String"
</ruby>

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

<ruby>
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
</ruby>

we get:

<ruby>
user_path(@user) # => "/users/357-john-smith"
</ruby>

281
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]+.
282

283 284
NOTE: Defined in +active_support/core_ext/object/to_param.rb+.

285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
h4. +to_query+

Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given

<ruby>
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
</ruby>

we get:

<ruby>
current_user.to_query('user') # => user=357-john-smith
</ruby>

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

<ruby>
account.to_query('company[name]')
# => "company%5Bname%5D=Johnson+%26+Johnson"
</ruby>

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

Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "&":

<ruby>
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
</ruby>

319
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 "&":
320 321 322 323 324 325 326 327 328 329 330 331

<ruby>
{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
</ruby>

The method +Hash#to_query+ accepts an optional namespace for the keys:

<ruby>
{:id => 89, :name => "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
</ruby>

332 333
NOTE: Defined in +active_support/core_ext/object/to_query.rb+.

334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
h4. +with_options+

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

Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:

<ruby>
class Account < ActiveRecord::Base
  has_many :customers, :dependent => :destroy
  has_many :products,  :dependent => :destroy
  has_many :invoices,  :dependent => :destroy
  has_many :expenses,  :dependent => :destroy
end
</ruby>

this way:

<ruby>
class Account < ActiveRecord::Base
  with_options :dependent => :destroy do |assoc|
    assoc.has_many :customers
    assoc.has_many :products
    assoc.has_many :invoices
    assoc.has_many :expenses
  end
end
</ruby>

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

<ruby>
I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, :user_name => user.name 
end
</ruby>

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.

373 374
NOTE: Defined in +active_support/core_ext/object/with_options.rb+.

375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392
h4. Instance Variables

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

h5. +instance_variable_names+

Ruby 1.8 and 1.9 have a method called +instance_variables+ that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines +instance_variable_names+ as a portable way to obtain them as strings:

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

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

X
Xavier Noria 已提交
393
WARNING: The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter.
394

395 396
NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.

397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
h5. +instance_values+

The method +instance_values+ returns a hash that maps instance variable names without "@" to their
corresponding values. Keys are strings both in Ruby 1.8 and 1.9:

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

C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
</ruby>

412 413
NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.

414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
h5. +copy_instance_variables_from(object, exclude = [])+

Copies the instance variables of +object+ into +self+.

Instance variable names in the +exclude+ array are ignored. If +object+
responds to +protected_instance_variables+ the ones returned are
also ignored. For example, Rails controllers implement that method.

In both arrays strings and symbols are understood, and they have to include
the at sign.

<ruby>
class C
  def initialize(x, y, z)
    @x, @y, @z = x, y, z
  end

  def protected_instance_variables
    %w(@z)
  end
end

a = C.new(0, 1, 2)
b = C.new(3, 4, 5)

a.copy_instance_variables_from(b, [:@y])
# a is now: @x = 3, @y = 1, @z = 2
</ruby>

In the example +object+ and +self+ are of the same type, but they don't need to.

445 446
NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+.

447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471
h4. Silencing Warnings, Streams, and Exceptions

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

<ruby>
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
</ruby>

You can silence any stream while a block runs with +silence_stream+:

<ruby>
silence_stream(STDOUT) do
  # STDOUT is silent here
end
</ruby>

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

<ruby>
# If the user is locked the increment is lost, no big deal.
suppress(ActiveRecord::StaleObjectError) do
  current_user.increment! :visits
end
</ruby>

472 473
NOTE: Defined in +active_support/core_ext/kernel/reporting.rb+.

474 475 476 477 478 479 480 481 482 483 484 485 486 487
h4. +require_library_or_gem+

The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again.

If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised.

For example, that's the way the MySQL adapter loads the MySQL library:

<ruby>
require_library_or_gem('mysql')
</ruby>

NOTE: Defined in +active_support/core_ext/kernel/requires.rb+.

488 489
h3. Extensions to +Module+

490
h4. +alias_method_chain+
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537

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

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

<ruby>
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
</ruby>

That's the method +get+, +post+, etc., delegate the work to.

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

<ruby>
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
</ruby>

The method +alias_method_chain+ provides a shortcut for that pattern:

<ruby>
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
</ruby>

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 specialised in validations.

538 539
NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.

540 541
h4. Attributes

542 543 544 545 546 547 548 549 550 551 552 553
h5. +alias_attribute+

Model attributes have a reader, a writer, and a predicate. You can aliase 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):

<ruby>
class User < ActiveRecord::Base
  # let me refer to the email column as "login",
  # much meaningful for authentication code
  alias_attribute :login, :email
end
</ruby>

554 555
NOTE: Defined in +active_support/core_ext/module/aliasing.rb+.

556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
h5. +attr_accessor_with_default+

The method +attr_accessor_with_default+ serves the same purpose as the Ruby macro +attr_accessor+ but allows you to set a default value for the attribute:

<ruby>
class Url
  attr_accessor_with_default :port, 80
end

Url.new.port # => 80
</ruby>

The default value can be also specified with a block, which is called in the context of the corresponding object:

<ruby>
class User
  attr_accessor :name, :surname
  attr_accessor_with_default(:full_name) {
	[name, surname].compact.join(" ")
  }
end

u = User.new
u.name = 'Xavier'
u.surname = 'Noria'
u.full_name # => "Xavier Noria"
</ruby>

The result is not cached, the block is invoked in each call to the reader.

You can overwrite the default with the writer:

<ruby>
url = Url.new
url.host # => 80
url.host = 8080
url.host # => 8080
</ruby>

The default value is returned as long as the attribute is unset. The reader does not rely on the value of the attribute to know whether it has to return the default. It rather monitors the writer: if there's any assignment the value is no longer considered to be unset.

Active Resource uses this macro to set a default value for the +:primary_key+ attribute:

<ruby>
attr_accessor_with_default :primary_key, 'id'
</ruby>

NOTE: Defined in +active_support/core_ext/module/attr_accessor_with_default.rb+.

605 606 607 608
h5. Internal Attributes

When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.

609
Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
610

611
The macro +attr_internal+ is a synonym for +attr_internal_accessor+:
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642

<ruby>
# library
class ThirdPartyLibrary::Crawler
  attr_internal :log_level
end

# client code
class MyCrawler < ThirdPartyLibrary::Crawler
  attr_accessor :log_level
end
</ruby>

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

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

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

<ruby>
module ActionView
  class Base
    attr_internal :captures
    attr_internal :request, :layout
    attr_internal :controller, :template
  end
end
</ruby>

NOTE: Defined in +active_support/core_ext/module/attr_internal.rb+.

643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
h5. Module Attributes

The macros +mattr_reader+, +mattr_writer+, and +mattr_accessor+ are analogous to the +cattr_*+ macros defined for class. Check "Class Attributes":#class-attributes.

For example, the dependencies mechanism uses them:

<ruby>
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
</ruby>

NOTE: Defined in +active_support/core_ext/module/attribute_accessors.rb+.

670
h4. Method Delegation
671

672 673
The class method +delegate+ offers an easy way to forward methods.

674
For example, if +User+ has some details like the age factored out to +Profile+, it could be handy to still be able to access such attributes directly, <tt>user.age</tt>, instead of having to explicit the chain <tt>user.profile.age</tt>.
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725

That can be accomplished by hand:

<ruby>
class User
  has_one :profile

  def age
    profile.age
  end
end
</ruby>

But with +delegate+ you can make that shorter and the intention even more obvious:

<ruby>
class User
  has_one :profile

  delegate :age, to => :profile
end
</ruby>

The macro accepts more than one method:

<ruby>
class User
  has_one :profile

  delegate :age, :avatar, :twitter_username, to => :profile
end
</ruby>

Methods can be delegated to objects returned by methods, as in the examples above, but also to instance variables, class variables, and constants. Just pass their names as symbols or strings, including the at signs in the last cases.

For example, +ActionView::Base+ delegates +erb_trim_mode=+:

<ruby>
module ActionView
  class Base
    delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB'
  end
end
</ruby>

In fact, you can delegate to any expression passed as a string. It will be evaluated in the context of the receiver. Controllers for example delegate alerts and notices to the current flash:

<ruby>
delegate :alert, :notice, :to => "request.flash"
</ruby>

726
If the target is +nil+ calling any delegated method will raise an exception even if +nil+ responds to such method. You can override this behavior setting the option +:allow_nil+ to true, in which case the forwarded call will simply return +nil+.
727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749

If the target is a method, the name of delegated methods can also be prefixed. If the +:prefix+ option is set to (exactly) the +true+ object, the value of the +:to+ option is prefixed:

<ruby>
class Invoice
  belongs_to :customer

  # defines a method called customer_name
  delegate :name, :to => :customer, :prefix => true
end
</ruby>

And a custom prefix can be set as well, in that case it does not matter wheter the target is a method or not:

<ruby>
class Account
  belongs_to :user

  # defines a method called admin_email
  delegate :email, :to => :user, :prefix => 'admin'
end
</ruby>

750
NOTE: Defined in +active_support/core_ext/module/delegation.rb+.
751

752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768
h4. Method Removal

h5. +remove_possible_method+

The method +remove_possible_method+ is like the standard +remove_method+, except it silently returns on failure:

<ruby>
class A; end

A.class_eval do
  remove_method(:nonexistent)          # raises NameError
  remove_possible_method(:nonexistent) # no problem, continue
end
</ruby>

This may come in handy if you need to define a method that may already exist, since redefining a method issues a warning "method redefined; discarding old redefined_method_name".

769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
h5. +redefine_method(method_name, &block)+

The method first removes method with given name (using +remove_possible_method+) and then defines new one.

<ruby>
class A; end

A.class_eval do
  redefine_method(:foobar) do |foo|
    #do something here
  end
  
  #Code above does the same as this:
  
  method_name = :foobar
  remove_possible_method(method_name)
  define_method(method_name) do |foo|
    #do something here
  end
end
</ruby>

791 792
NOTE: Defined in +active_support/core_ext/module/remove_method.rb+.

793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840
h4. Parents

h5. +parent+

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

<ruby>
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.parent # => X::Y
M.parent       # => X::Y
</ruby>

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

WARNING: Note that in that case +parent_name+ returns +nil+.

NOTE: Defined in +active_support/core_ext/module/introspection.rb+.

h5. +parent_name+

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

<ruby>
module X
  module Y
    module Z
    end
  end
end
M = X::Y::Z

X::Y::Z.parent_name # => "X::Y"
M.parent_name       # => "X::Y"
</ruby>

For top-level or anonymous modules +parent_name+ returns +nil+.

WARNING: Note that in that case +parent+ returns +Object+.

NOTE: Defined in +active_support/core_ext/module/introspection.rb+.

841
h5(#module-parents). +parents+
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

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

<ruby>
module X
  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]
</ruby>

NOTE: Defined in +active_support/core_ext/module/introspection.rb+.

860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
h4. Constants

The method +local_constants+ returns the names of the constants that have been defined in the receiver module:

<ruby>
module X
  X1 = 1
  X2 = 2
  module Y
    Y1 = :y1
    X1 = :overrides_X1_above
  end
end

X.local_constants    # => ["X2", "X1", "Y"], assumes Ruby 1.8
X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
</ruby>

The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method +local_constant_names+ returns always strings.

WARNING: This method is exact if running under Ruby 1.9. In previous versions it may miss some constants if their value in some ancestor stores the exact same object than in the receiver.

NOTE: Defined in +active_support/core_ext/module/introspection.rb+.

884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
h4. Synchronization

The +synchronize+ macro declares a method to be synchronized:

<ruby>
class Counter
  @@mutex = Mutex.new
  attr_reader :value

  def initialize
    @value = 0
  end

  def incr
    @value += 1 # non-atomic
  end
  synchronize :incr, :with => '@@mutex'
end
</ruby>

The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block. 

NOTE: Defined in +active_support/core_ext/module/synchronization.rb+.

908
h4. Reachable
909

910
A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945

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

<ruby>
module M
end

M.reachable? # => true
</ruby>

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

<ruby>
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
</ruby>

NOTE: Defined in +active_support/core_ext/module/reachable.rb+.

946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
h4. Anonymous

A module may or may not have a name:

<ruby>
module M
end
M.name # => "M"

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

Module.new.name # => "" in 1.8, nil in 1.9
</ruby>

You can check whether a module has a name with the predicate +anonymous?+:

<ruby>
module M
end
M.anonymous? # => false

Module.new.anonymous? # => true
</ruby>

Note that being unreachable does not imply being anonymous:

<ruby>
module M
end

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

m.reachable? # => false
m.anonymous? # => false
</ruby>

though an anonymous module is unreachable by definition.

NOTE: Defined in +active_support/core_ext/module/anonymous.rb+.

987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
h4. Delegation

The +delegate+ macro declares that some instance method has to be forwarded to some object.

Let's imagine that users in some application have login information in the +User+ model but name and other data in a separate +Profile+ model:

<ruby>
class User < ActiveRecord::Base
  has_one :profile
end
</ruby>

With that configuration you get a user's name via his profile, +user.profile.name+, but you could write a shortcut so that client code can read it directly:

<ruby>
class User < ActiveRecord::Base
  has_one :profile

  def name
    profile.name
  end
end
</ruby>

That is what +delegate+ does for you:

<ruby>
class User < ActiveRecord::Base
  has_one :profile

  delegate :name, :to => :profile
end
</ruby>

When interpolated into a string, the +:to+ option should become an expression that evaluates to the object the method is delegated to:

<ruby>
delegate :logger, :to => :Rails
delegate :table_name, :to => 'self.class'
</ruby>

WARNING: If the +:prefix+ option is +true+ this is less generic, see below.

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

<ruby>
class User < ActiveRecord::Base
  has_one :profile

  delegate :name, :to => :profile, :allow_nil => true
end
</ruby>

With +:allow_nil+ the call +user.name+ returns +nil+ if the user has no profile instead of raising an exception.

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

<ruby>
class Account < ActiveRecord::Base
  has_one :address

  delegate :street, :to => :address, :prefix => true
end
</ruby>

The previous example generates +Account#address_street+ rather than +Account#street+.

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

A custom prefix may also be configured:

<ruby>
class User < ActiveRecord::Base
  has_one :attachment
  
  delegate :size, :to => :attachment, :prefix => :avatar
</ruby>

In the previous example the macro generates +User#avatar_size+ rather than +User#size+.

NOTE: Defined in +active_support/core_ext/module/delegation.rb+

1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
h4. Method Names

The builtin methods +instance_methods+ and +methods+ return method names as strings or symbols depending on the Ruby version. Active Support defines +instance_method_names+ and +method_names+ to be equivalent to them, respectively, but always getting strings back.

For example, +ActionView::Helpers::FormBuilder+ knows this array difference is going to work no matter the Ruby version:

<ruby>
self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
</ruby>

NOTE: Defined in +active_support/core_ext/module/method_names.rb+

1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
h4. Redefining Methods

There are cases where you need to define a method with +define_method+, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.

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

<ruby>
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
</ruby>

NOTE: Defined in +active_support/core_ext/module/remove_method.rb+

1102 1103
h3. Extensions to +Class+

1104 1105
h4. Class Attributes

1106 1107 1108
h5. +class_attribute+

The method +class_attribute+ declares one or more inheritable class attributes that can be overridden at any level down the hierarchy:
1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131

<ruby>
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
</ruby>

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
For example +ActionMailer::Base+ defines:

<ruby>
class_attribute :default_params
self.default_params = {
  :mime_version => "1.0",
  :charset      => "UTF-8",
  :content_type => "text/plain",
  :parts_order  => [ "text/plain", "text/enriched", "text/html" ]
}.freeze
</ruby>

They can be also accessed and overridden at the instance level:

<ruby>
A.x = 1

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

a1.x # => 1, comes from A
a2.x # => 2, overridden in a2
</ruby>

The generation of the writer instance method can be prevented by setting the option +:instance_writer+ to false, as in
1158 1159

<ruby>
1160 1161 1162 1163 1164 1165
module AcitveRecord
  class Base
    class_attribute :table_name_prefix, :instance_writer => false
    self.table_name_prefix = ""
  end
end
1166 1167
</ruby>

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

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

NOTE: Defined in +active_support/core_ext/class/attribute.rb+
1173

1174 1175
h5. +cattr_reader+, +cattr_writer+, and +cattr_accessor+

1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it:

<ruby>
class MysqlAdapter < AbstractAdapter
  # Generates class methods to access @@emulate_booleans.
  cattr_accessor :emulate_booleans
  self.emulate_booleans = true
end
</ruby>

1186
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
1187 1188

<ruby>
1189
module ActionView
1190
  class Base
1191 1192
    cattr_accessor :field_error_proc
    @@field_error_proc = Proc.new{ ... }
1193 1194 1195 1196
  end
end
</ruby>

1197
we can access +field_error_proc+ in views. The generation of the writer instance method can be prevented by setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

<ruby>
module ActiveRecord
  class Base
    # No pluralize_table_names= instance writer is generated.
    cattr_accessor :pluralize_table_names, :instance_writer => false
  end
end
</ruby>

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

1210 1211
NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+.

1212 1213
h4. Class Inheritable Attributes

1214
Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accessors for class-level data which is inherited but not shared with children:
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

<ruby>
module ActionController
  class Base
    # FIXME: REVISE/SIMPLIFY THIS COMMENT.
    # The value of allow_forgery_protection is inherited,
    # but its value in a particular class does not affect
    # the value in the rest of the controllers hierarchy.
    class_inheritable_accessor :allow_forgery_protection
  end
end
</ruby>

They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with +dup+ as long as the value is duplicable.

There are some variants specialised in arrays and hashes:

<ruby>
class_inheritable_array
class_inheritable_hash
</ruby>

Those writers take any inherited array or hash into account and extend them rather than overwrite them.

As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+):

<ruby>
module ActiveRecord
  class Base
    class_inheritable_accessor :default_scoping, :instance_writer => false
  end
end
</ruby>

Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point. 

1251 1252
NOTE: Defined in +active_support/core_ext/class/inheritable_attributes.rb+.

X
Xavier Noria 已提交
1253
h4. Subclasses & Descendants
1254

X
Xavier Noria 已提交
1255
h5. +subclasses+
1256

X
Xavier Noria 已提交
1257
The +subclasses+ method returns the subclasses of the receiver:
1258 1259 1260

<ruby>
class C; end
X
Xavier Noria 已提交
1261
C.subclasses # => []
1262

1263
class B < C; end
X
Xavier Noria 已提交
1264
C.subclasses # => [B]
1265

1266
class A < B; end
X
Xavier Noria 已提交
1267
C.subclasses # => [B]
1268

1269
class D < C; end
X
Xavier Noria 已提交
1270
C.subclasses # => [B, D]
1271 1272
</ruby>

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

X
Xavier Noria 已提交
1275 1276 1277 1278 1279 1280 1281
WARNING: This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.

NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.

h5. +descendants+

The +descendants+ method returns all classes that are <tt>&lt;</tt> than its receiver: 
1282 1283 1284

<ruby>
class C; end
X
Xavier Noria 已提交
1285
C.descendants # => []
1286 1287

class B < C; end
X
Xavier Noria 已提交
1288
C.descendants # => [B]
1289 1290

class A < B; end
X
Xavier Noria 已提交
1291
C.descendants # => [B, A]
1292 1293

class D < C; end
X
Xavier Noria 已提交
1294
C.descendants # => [B, A, D]
1295
</ruby>
1296

X
Xavier Noria 已提交
1297
The order in which these classes are returned is unspecified.
1298 1299 1300

NOTE: Defined in +active_support/core_ext/class/subclasses.rb+.

1301 1302
h3. Extensions to +String+

1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
h4. Output Safety

Inserting data into HTML templates needs extra care. For example you can't just interpolate +@review.title+ verbatim into an HTML page. On one hand 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;". On the other hand, 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.

Active Support has the concept of <i>(html) safe</i> strings since Rails 3. 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.

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

<ruby>
"".html_safe? # => false
</ruby>

You can obtain a safe string from a given one with the +html_safe+ method:

<ruby>
s = "".html_safe
s.html_safe? # => true
</ruby>

1322
It is important to understand that +html_safe+ performs no escaping whatsoever, it is just an assertion:
1323 1324 1325 1326 1327 1328 1329

<ruby>
s = "<script>...</script>".html_safe
s.html_safe? # => true
s            # => "<script>...</script>"
</ruby>

1330
It is your responsibility to ensure calling +html_safe+ on a particular string is fine.
1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365

NOTE: For performance reasons safe strings are implemented in a way that cannot offer an in-place +html_safe!+ variant.

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

<ruby>
"".html_safe + "<" # => "&lt;"
</ruby>

Safe arguments are directly appended:

<ruby>
"".html_safe + "<".html_safe # => "<"
</ruby>

These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:

<erb>
<%= @review.title %> <%# fine in Rails 3, escaped if needed %>
</erb>

To insert something verbatim use the +raw+ helper rather than calling +html_safe+:

<erb>
<%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
</erb>

The +raw+ helper calls +html_safe+ for you:

<ruby>
def raw(stringish)
  stringish.to_s.html_safe
end
</ruby>

1366 1367
NOTE: Defined in +active_support/core_ext/string/output_safety.rb+.

1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
h4. +squish+

The method +String#squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:

<ruby>
" \n  foo\n\r \t bar \n".squish # => "foo bar"
</ruby>

There's also the destructive version +String#squish!+.

1378 1379
NOTE: Defined in +active_support/core_ext/string/filters.rb+.

1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
h4. +truncate+

The method +truncate+ returns a copy of its receiver truncated after a given +length+:

<ruby>
"Oh dear! Oh dear! I shall be late!".truncate(20)
# => "Oh dear! Oh dear!..."
</ruby>

Ellipsis can be customized with the +:omission+ option:

<ruby>
"Oh dear! Oh dear! I shall be late!".truncate(20, :omission => '&hellip;')
# => "Oh dear! Oh &hellip;"
</ruby>

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

Pass a +:separator+ to truncate the string at a natural break:

<ruby>
"Oh dear! Oh dear! I shall be late!".truncate(18)
# => "Oh dear! Oh dea..." 
"Oh dear! Oh dear! I shall be late!".truncate(18, :separator => ' ')
# => "Oh dear! Oh..."
</ruby>

In the above example "dear" gets cut first, but then +:separator+ prevents it.

WARNING: The option +:separator+ can't be a regexp.

NOTE: Defined in +active_support/core_ext/string/filters.rb+.

1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
h4. Key-based Interpolation

In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:

<ruby>
"Total is %<total>.02f" % {:total => 43.1}  # => Total is 43.10
"I say %{foo}" % {:foo => "wadus"}          # => "I say wadus"
"I say %{woo}" % {:foo => "wadus"}          # => KeyError
</ruby>

Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.

1425 1426
NOTE: Defined in +active_support/core_ext/string/interpolation.rb+.

1427
h4. +starts_with?+ and +ends_width?+
1428

1429
Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:
1430 1431 1432 1433 1434 1435

<ruby>
"foo".starts_with?("f") # => true
"foo".ends_with?("o")   # => true
</ruby>

1436 1437
NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+.

1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
h4. Access

h5. +at(position)+

Returns the character of the string at position +position+:

<ruby>
"hello".at(0)  # => "h"
"hello".at(4)  # => "o"
"hello".at(-1) # => "o"
"hello".at(10) # => ERROR if < 1.9, nil in 1.9
</ruby>

1451 1452
NOTE: Defined in +active_support/core_ext/string/access.rb+.

1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
h5. +from(position)+

Returns the substring of the string starting at position +position+:

<ruby>
"hello".from(0)  # => "hello"
"hello".from(2)  # => "llo"
"hello".from(-2) # => "lo"
"hello".from(10) # => "" if < 1.9, nil in 1.9
</ruby>

1464 1465
NOTE: Defined in +active_support/core_ext/string/access.rb+.

1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
h5. +to(position)+

Returns the substring of the string up to position +position+:

<ruby>
"hello".to(0)  # => "h"
"hello".to(2)  # => "hel"
"hello".to(-2) # => "hell"
"hello".to(10) # => "hello"
</ruby>

1477 1478
NOTE: Defined in +active_support/core_ext/string/access.rb+.

1479 1480 1481 1482
h5. +first(limit = 1)+

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

1483 1484
NOTE: Defined in +active_support/core_ext/string/access.rb+.

1485 1486 1487 1488
h5. +last(limit = 1)+

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

1489 1490
NOTE: Defined in +active_support/core_ext/string/access.rb+.

1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
h4. Inflections

h5. +pluralize+

The method +pluralize+ returns the plural of its receiver:

<ruby>
"table".pluralize     # => "tables"
"ruby".pluralize      # => "rubies"
"equipment".pluralize # => "equipment"
</ruby>

1503
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.
1504

1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515
Active Record uses this method to compute the default table name that corresponds to a model:

<ruby>
# active_record/base.rb
def undecorated_table_name(class_name = base_class.name)
  table_name = class_name.to_s.demodulize.underscore
  table_name = table_name.pluralize if pluralize_table_names
  table_name
end
</ruby>

1516 1517
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540
h5. +singularize+

The inverse of +pluralize+:

<ruby>
"tables".singularize    # => "table"
"rubies".singularize    # => "ruby"
"equipment".singularize # => "equipment"
</ruby>

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

<ruby>
# active_record/reflection.rb
def derive_class_name
  class_name = name.to_s.camelize
  class_name = class_name.singularize if collection?
  class_name
end
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578
h5. +camelize+

The method +camelize+ returns its receiver in camel case:

<ruby>
"product".camelize    # => "Product"
"admin_user".camelize # => "AdminUser"
</ruby>

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:

<ruby>
"backoffice/session".camelize # => "Backoffice::Session"
</ruby>

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

<ruby>
# action_controller/metal/session_management.rb
def session_store=(store)
  if store == :active_record_store
    self.session_store = ActiveRecord::SessionStore
  else
    @@session_store = store.is_a?(Symbol) ?
      ActionDispatch::Session.const_get(store.to_s.camelize) :
      store
  end
end
</ruby>

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

<ruby>
"visual_effect".camelize(:lower) # => "visualEffect"
</ruby>

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

1579 1580
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: <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.

1581 1582 1583 1584 1585 1586
+camelize+ is aliased to +camelcase+.

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

h5. +underscore+

1587
The method +underscore+ goes the other way around, from camel case to paths:
1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619

<ruby>
"Product".underscore   # => "product"
"AdminUser".underscore # => "admin_user"
</ruby>

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

<ruby>
"Backoffice::Session".underscore # => "backoffice/session"
</ruby>

and understands strings that start with lowercase:

<ruby>
"visualEffect".underscore # => "visual_effect"
</ruby>

+underscore+ accepts no argument though.

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

<ruby>
# 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
</ruby>

1620 1621
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, <tt>"SSLError".underscore.camelize</tt> gives back <tt>"SslError"</tt>.

1622 1623
NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
h5. +titleize+

The method +titleize+ capitalizes the words in the receiver:

<ruby>
"alice in wonderland".titleize # => "Alice In Wonderland"
"fermat's enigma".titleize     # => "Fermat's Enigma"
</ruby>

+titleize+ is aliased to +titlecase+.

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
h5. +dasherize+

The method +dasherize+ replaces the underscores in the receiver with dashes:

<ruby>
"name".dasherize         # => "name"
"contact_data".dasherize # => "contact-data"
</ruby>

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

<ruby>
# active_model/serializers/xml.rb
def reformat_name(name)
  name = name.camelize if camelize?
  dasherize? ? name.dasherize : name
end
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682
h5. +demodulize+

Given a string with a qualified constant reference expression, +demodulize+ returns the very constant name, that is, the rightmost part of it:

<ruby>
"Product".demodulize                        # => "Product"
"Backoffice::UsersController".demodulize    # => "UsersController"
"Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
</ruby>

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

<ruby>
# 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
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
h5. +parameterize+

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

<ruby>
"John Smith".parameterize # => "john-smith"
"Kurt Gödel".parameterize # => "kurt-godel"
</ruby>

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

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1696 1697 1698 1699 1700 1701 1702
h5. +tableize+

The method +tableize+ is +underscore+ followed by +pluralize+.

<ruby>
"Person".tableize      # => "people"
"Invoice".tableize     # => "invoices"
1703
"InvoiceLine".tableize # => "invoice_lines"
1704 1705 1706 1707 1708 1709
</ruby>

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 de class name and checks a few options that may affect the returned string.

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729
h5. +classify+

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

<ruby>
"people".classify        # => "Person"
"invoices".classify      # => "Invoice"
"invoice_lines".classify # => "InvoiceLine"
</ruby>

The method understands qualified table names:

<ruby>
"highrise_production.companies".classify # => "Company"
</ruby>

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

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
h5. +constantize+

The method +constantize+ resolves the constant reference expression in its receiver:

<ruby>
"Fixnum".constantize # => Fixnum

module M
  X = 1
end
"M::X".constantize # => 1
</ruby>

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

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

<ruby>
X = :in_Object
module M
  X = :in_M

  X                 # => :in_M
  "::X".constantize # => :in_Object
  "X".constantize   # => :in_Object (!)
end
</ruby>

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

Mailer test cases obtain the mailer being tested from the name of the test class using +constantize+:

<ruby>
# action_mailer/test_case.rb
def determine_default_mailer(name)
  name.sub(/Test$/, '').constantize
rescue NameError => e
  raise NonInferrableMailerError.new(name)
end
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801
h5. +humanize+

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

<ruby>
"name".humanize           # => "Name"
"author_id".humanize      # => "Author"
"comments_count".humanize # => "Comments count"
</ruby>

The helper method +full_messages+ uses +humanize+ as a fallback to include attribute names:

<ruby>
def full_messages
  full_messages = []

  each do |attribute, messages|
    ...
    attr_name = attribute.to_s.gsub('.', '_').humanize
    attr_name = @base.class.human_attribute_name(attribute, :default => attr_name)
    ...
  end

  full_messages
end
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826
h5. +foreign_key+

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

<ruby>
"User".foreign_key           # => "user_id"
"InvoiceLine".foreign_key    # => "invoice_line_id"
"Admin::Session".foreign_key # => "session_id"
</ruby>

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

<ruby>
"User".foreign_key(false) # => "userid"
</ruby>

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

<ruby>
# active_record/associations.rb
foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
</ruby>

NOTE: Defined in +active_support/core_ext/string/inflections.rb+.

1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
h4. Conversions

h5. +constantize+

The method +constantize+ expects the receiver to contain the name of a constant, and tries to get you the object stored in there, assuming it is defined:

<ruby>
"ActiveRecord::Base".constantize # => ActiveRecord::Base
</ruby>

The name is assumed to be top-level, no matter whether it starts with "::" or not. No lexical context is taken into account:

<ruby>
C = 1
module M
  C = 2
  "C".constantize # => 1, same as "::C".constantize
end
</ruby>

NOTE: Defined in +active_support/core_ext/string/conversions.rb+.

h5. +ord+

Ruby 1.9 defines +ord+ to be the codepoint of the first character of the receiver. Active Support backports +ord+ for single-byte encondings like ASCII or ISO-8859-1 in Ruby 1.8:

<ruby>
"a".ord # => 97
"à".ord # => 224, in ISO-8859-1
</ruby>

In Ruby 1.8 +ord+ doesn't work in general in UTF8 strings, use the multibyte support in Active Support for that:

<ruby>
"a".mb_chars.ord # => 97
"à".mb_chars.ord # => 224, in UTF8
</ruby>

Note that the 224 is different in both examples. In ISO-8859-1 "à" is represented as a single byte, 224. Its single-character representattion in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call +ord+ on the UTF8 string "à" the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.

INFO: +ord+ is equivalent to +getbyte(0)+.

NOTE: Defined in +active_support/core_ext/string/conversions.rb+.

h5. +getbyte+

Active Support backports +getbyte+ from Ruby 1.9:

<ruby>
"foo".getbyte(0)  # => 102, same as "foo".ord
"foo".getbyte(1)  # => 111
"foo".getbyte(9)  # => nil
"foo".getbyte(-1) # => 111
</ruby>

INFO: +getbyte+ is equivalent to +[]+.

NOTE: Defined in +active_support/core_ext/string/conversions.rb+.

h5. +to_date+, +to_time+, +to_datetime+

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

<ruby>
"2010-07-27".to_date              # => Tue, 27 Jul 2010
"2010-07-27 23:37:00".to_time     # => Tue Jul 27 23:37:00 UTC 2010
"2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000 
</ruby>

1896
+to_time+ receives an optional argument +:utc+ or +:local+, to indicate which time zone you want the time in:
1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910

<ruby>
"2010-07-27 23:42:00".to_time(:utc)   # => Tue Jul 27 23:42:00 UTC 2010
"2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
</ruby>

Default is +:utc+.

Please refer to the documentation of +Date._parse+ for further details.

INFO: The three of them return +nil+ for blank receivers.

NOTE: Defined in +active_support/core_ext/string/conversions.rb+.

1911 1912
h3. Extensions to +Numeric+

1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938
h4. Bytes

All numbers respond to these methods:

<ruby>
bytes
kilobytes
megabytes
gigabytes
terabytes
petabytes
exabytes
</ruby>

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

<ruby>
2.kilobytes   # => 2048
3.megabytes   # => 3145728
3.5.gigabytes # => 3758096384
-4.exabytes   # => -4611686018427387904
</ruby>

Singular forms are aliased so you are able to say:

<ruby>
X
Xavier Noria 已提交
1939
1.megabyte # => 1048576
1940
</ruby>
1941

1942 1943
NOTE: Defined in +active_support/core_ext/numeric/bytes.rb+.

1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
h3. Extensions to +Integer+

h4. +multiple_of?+

The method +multiple_of?+ tests whether an integer is multiple of the argument:

<ruby>
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false
</ruby>

1955 1956
NOTE: Defined in +active_support/core_ext/integer/multiple.rb+.

1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
h4. +ordinalize+

The method +ordinalize+ returns the ordinal string corresponding to the receiver integer:

<ruby>
1.ordinalize    # => "1st"
2.ordinalize    # => "2nd"
53.ordinalize   # => "53rd"
2009.ordinalize # => "2009th"
</ruby>

1968 1969
NOTE: Defined in +active_support/core_ext/integer/inflections.rb+.

1970 1971
h3. Extensions to +Float+

X
Xavier Noria 已提交
1972 1973
h4. +round+

1974
The built-in method +Float#round+ rounds a float to the nearest integer. Active Support adds an optional parameter to let you specify a precision:
X
Xavier Noria 已提交
1975 1976 1977 1978 1979 1980

<ruby>
Math::E.round(4) # => 2.7183
</ruby>

NOTE: Defined in +active_support/core_ext/float/rounding.rb+.
1981 1982 1983 1984 1985 1986 1987 1988 1989

h3. Extensions to +BigDecimal+

...

h3. Extensions to +Enumerable+

h4. +group_by+

1990
Active Support redefines +group_by+ in Ruby 1.8.7 so that it returns an ordered hash as in 1.9:
1991 1992 1993 1994 1995 1996 1997

<ruby>
entries_by_surname_initial = address_book.group_by do |entry|
  entry.surname.at(0).upcase
end
</ruby>

1998
Distinct block return values are added to the hash as they come, so that's the resulting order.
1999

2000 2001
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
h4. +sum+

The method +sum+ adds the elements of an enumerable:

<ruby>
[1, 2, 3].sum # => 6
(1..100).sum  # => 5050
</ruby>

Addition only assumes the elements respond to <tt>+</tt>:

<ruby>
[[1, 2], [2, 3], [3, 4]].sum    # => [1, 2, 2, 3, 3, 4]
%w(foo bar baz).sum             # => "foobarbaz"
{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
</ruby>

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

<ruby>
[].sum    # => 0
[].sum(1) # => 1
</ruby>

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

<ruby>
(1..5).sum {|n| n * 2 } # => 30
[2, 4, 6, 8, 10].sum    # => 30
</ruby>

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

<ruby>
[].sum(1) {|n| n**3} # => 1
</ruby>

The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:

<ruby>
def observed_subclasses
  observed_classes.sum([]) { |klass| klass.send(:subclasses) }
end
</ruby>

2047 2048
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072
h4. +each_with_object+

The +inject+ method offers iteration with an accumulator:

<ruby>
[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
</ruby>

The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:

<ruby>
[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
</ruby>

See that spurious "+; h+"?

Active Support backports +each_with_object+ from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way:

<ruby>
[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
</ruby>

WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+.

2073 2074
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
h4. +index_by+

The method +index_by+ generates a hash with the elements of an enumerable indexed by some key.

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

<ruby>
invoices.index_by(&:number)
# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
</ruby>

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.

2088 2089
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
h4. +many?+

The method +many?+ is shorthand for +collection.size > 1+:

<erb>
<% if pages.many? %>
  <%= pagination_links %>
<% end %>
</erb>

If an optional block is given +many?+ only takes into account those elements that return true:

<ruby>
@see_more = videos.many? {|video| video.category == params[:category]}
</ruby>

2106 2107
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2108 2109 2110 2111 2112 2113 2114 2115
h4. +exclude?+

The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+:

<ruby>
to_visit << node if visited.exclude?(node)
</ruby>

2116 2117
NOTE: Defined in +active_support/core_ext/enumerable.rb+.

2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133
h3. Extensions to +Array+

h4. Accessing

Active Support augments the API of arrays to ease certain ways of accessing them. For example, +to+ returns the subarray of elements up to the one at the passed index:

<ruby>
%w(a b c d).to(2) # => %w(a b c)
[].to(7)          # => []
</ruby>

Similarly, +from+ returns the tail from the element at the passed index on:

<ruby>
%w(a b c d).from(2)  # => %w(c d)
%w(a b c d).from(10) # => nil
X
Xavier Noria 已提交
2134
[].from(0)           # => []
2135 2136
</ruby>

2137
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.
2138

2139 2140 2141 2142 2143 2144
NOTE: Defined in +active_support/core_ext/array/access.rb+.

h4. Random Access

Active Support backports +sample+ from Ruby 1.9:

2145
<ruby>
2146 2147 2148 2149 2150
shape_type = [Circle, Square, Triangle].sample
# => Square, for example

shape_types = [Circle, Square, Triangle].sample(2)
# => [Triangle, Circle], for example
2151 2152
</ruby>

2153
NOTE: Defined in +active_support/core_ext/array/random_access.rb+.
2154

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180
h4. Options Extraction

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

<ruby>
User.exists?(:email => params[:email])
</ruby>

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.

If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role.

In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash.

Let's see for example the definition of the +caches_action+ controller macro:

<ruby>
def caches_action(*actions)
  return unless cache_configured?
  options = actions.extract_options!
  ...
end
</ruby>

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.

2181 2182
NOTE: Defined in +active_support/core_ext/array/extract_options.rb+.

2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210
h4. Conversions

h5. +to_sentence+

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

<ruby>
%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"
</ruby>

This method accepts three options:

* <tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".
* <tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
* <tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".

The defaults for these options can be localised, their keys are:

|_. Option                      |_. I18n key                                 |
| <tt>:two_words_connector</tt> | <tt>support.array.two_words_connector</tt> |
| <tt>:words_connector</tt>     | <tt>support.array.words_connector</tt>     |
| <tt>:last_word_connector</tt> | <tt>support.array.last_word_connector</tt> |

Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.

2211 2212
NOTE: Defined in +active_support/core_ext/array/conversions.rb+.

2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226
h5. +to_formatted_s+

The method +to_formatted_s+ acts like +to_s+ by default.

If the array contains items that respond to +id+, however, it may be passed the symbol <tt>:db</tt> as argument. That's typically used with collections of ARs, though technically any object in Ruby 1.8 responds to +id+ indeed. Returned strings are:

<ruby>
[].to_formatted_s(:db)            # => "null"
[user].to_formatted_s(:db)        # => "8456"
invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
</ruby>

Integers in the example above are supposed to come from the respective calls to +id+.

2227 2228
NOTE: Defined in +active_support/core_ext/array/conversions.rb+.

2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327
h5. +to_xml+

The method +to_xml+ returns a string containing an XML representation of its receiver:

<ruby>
Contributor.all(:limit => 2, :order => 'rank ASC').to_xml
# =>
# <?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>
</ruby>

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

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

If there's any element that does not belong to the type of the first one the root node becomes "records":

<ruby>
[Contributor.first, Commit.first].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <records type="array">
#   <record>
#     <id type="integer">4583</id>
#     <name>Aaron Batalion</name>
#     <rank type="integer">53</rank>
#     <url-id>aaron-batalion</url-id>
#   </record>
#   <record>
#     <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>
#   </record>
# </records>
</ruby>

If the receiver is an array of hashes the root element is by default also "records":

<ruby>
[{:a => 1, :b => 2}, {:c => 3}].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <records type="array">
#   <record>
#     <b type="integer">2</b>
#     <a type="integer">1</a>
#   </record>
#   <record>
#     <c type="integer">3</c>
#   </record>
# </records>
</ruby>

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 <tt>:root</tt> option to ensure a consistent root element.

The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "record". The option <tt>:children</tt> allows you to set these node names.

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

<ruby>
Contributor.all(:limit => 2, :order => 'rank ASC').to_xml(:skip_types => true)
# =>
# <?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>
</ruby>

2328 2329
NOTE: Defined in +active_support/core_ext/array/conversions.rb+.

2330 2331
h4. Wrapping

2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346
The method +Array.wrap+ wraps its argument in an array unless it is already an array (or array-like).

Specifically:

* If the argument is +nil+ an empty list is returned.
* Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
* Otherwise, returns an array with the argument as its single element.

<ruby>
Array.wrap(nil)       # => []
Array.wrap([1, 2, 3]) # => [1, 2, 3]
Array.wrap(0)         # => [0]
</ruby>

This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:
2347 2348 2349 2350 2351

* If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> moves on to try +to_a+ if the returned value is +nil+, but <tt>Arraw.wrap</tt> returns such a +nil+ right away.
* If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> 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.

2352
The last point is particularly worth comparing for some enumerables:
2353 2354 2355 2356 2357 2358 2359 2360 2361

<ruby>
Array.wrap(:foo => :bar) # => [{:foo => :bar}]
Array(:foo => :bar)      # => [[:foo, :bar]]

Array.wrap("foo\nbar")   # => ["foo\nbar"]
Array("foo\nbar")        # => ["foo\n", "bar"], in Ruby 1.8
</ruby>

2362 2363 2364 2365 2366 2367 2368 2369 2370 2371
There's also a related idiom that uses the splat operator:

<ruby>
[*object]
</ruby>

which returns +[nil]+ for +nil+, and calls to <tt>Array(object)</tt> otherwise

Thus, in this case the behavior is different for +nil+, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of +object+s.

2372 2373
NOTE: Defined in +active_support/core_ext/array/wrap.rb+.

2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409
h4. Grouping

h5. +in_groups_of(number, fill_with = nil)+

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

<ruby>
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
</ruby>

or yields them in turn if a block is passed:

<ruby>
<% sample.in_groups_of(3) do |a, b, c| %>
  <tr>
    <td><%=h a %></td>
    <td><%=h b %></td>
    <td><%=h c %></td>
  </tr>
<% end %>
</ruby>

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

<ruby>
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
</ruby>

And you can tell the method not to fill the last group passing +false+:

<ruby>
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
</ruby>

As a consequence +false+ can't be a used as a padding value.

2410 2411
NOTE: Defined in +active_support/core_ext/array/grouping.rb+.

2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447
h5. +in_groups(number, fill_with = nil)+

The method +in_groups+ splits an array into a certain number of groups. The method returns and array with the groups:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3)
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
</ruby>

or yields them in turn if a block is passed:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
["1", "2", "3"]
["4", "5", nil]
["6", "7", nil]
</ruby>

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

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

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3, "0")
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
</ruby>

And you can tell the method not to fill the smaller groups passing +false+:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3, false)
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
</ruby>

As a consequence +false+ can't be a used as a padding value.

2448 2449
NOTE: Defined in +active_support/core_ext/array/grouping.rb+.

2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467
h5. +split(value = nil)+

The method +split+ divides an array by a separator and returns the resulting chunks.

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

<ruby>
(-5..5).to_a.split { |i| i.multiple_of?(4) }
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
</ruby>

Otherwise, the value received as argument, which defaults to +nil+, is the separator:

<ruby>
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
# => [[0], [-5], [], ["foo", "bar"]]
</ruby>

2468 2469 2470
TIP: Observe in the previous example that consecutive separators result in empty arrays.

NOTE: Defined in +active_support/core_ext/array/grouping.rb+.
2471 2472 2473

h3. Extensions to +Hash+

2474
h4(#hash-conversions). Conversions
2475

2476
h5(#hash-to-xml). +to_xml+
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519

The method +to_xml+ returns a string containing an XML representation of its receiver:

<ruby>
{"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>
</ruby>

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

* If +value+ is a hash there's a recursive call with +key+ as <tt>:root</tt>.

* If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>, and +key+ singularized as <tt>:children</tt>.

* 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 <tt>:root</tt>, and +key+ singularized as second argument. Its return value becomes a new node.

* If +value+ responds to +to_xml+ the method is invoked with +key+ as <tt>:root</tt>.

* 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 <tt>:skip_types</tt> exists and is true, an attribute "type" is added as well according to the following mapping:
<ruby>
XML_TYPE_NAMES = {
  "Symbol"     => "symbol",
  "Fixnum"     => "integer",
  "Bignum"     => "integer",
  "BigDecimal" => "decimal",
  "Float"      => "float",
  "TrueClass"  => "boolean",
  "FalseClass" => "boolean",
  "Date"       => "date",
  "DateTime"   => "datetime",
  "Time"       => "datetime"
}
</ruby>

By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.

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

2520 2521
NOTE: Defined in +active_support/core_ext/hash/conversions.rb+.

2522 2523
h4. Merging

2524
Ruby has a built-in method +Hash#merge+ that merges two hashes:
2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554

<ruby>
{:a => 1, :b => 1}.merge(:a => 0, :c => 2)
# => {:a => 0, :b => 1, :c => 2}
</ruby>

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

h5. +reverse_merge+ and +reverse_merge!+

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

<ruby>
options = {:length => 30, :omission => "..."}.merge(options)
</ruby>

Active Support defines +reverse_merge+ in case you prefer this alternative notation:

<ruby>
options = options.reverse_merge(:length => 30, :omission => "...")
</ruby>

And a bang version +reverse_merge!+ that performs the merge in place:

<ruby>
options.reverse_merge!(:length => 30, :omission => "...")
</ruby>

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

2555 2556
NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.

2557 2558 2559 2560 2561 2562
h5. +reverse_update+

The method +reverse_update+ is an alias for +reverse_merge!+, explained above.

WARNING. Note that +reverse_update+ has no bang.

2563 2564
NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+.

2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577
h5. +deep_merge+ and +deep_merge!+

As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.

Active Support defines +Hash#deep_merge+. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:

<ruby>
{:a => {:b => 1}}.deep_merge(:a => {:c => 2})
# => {:a => {:b => 1, :c => 2}}
</ruby>

The method +deep_merge!+ performs a deep merge in place.

2578 2579
NOTE: Defined in +active_support/core_ext/hash/deep_merge.rb+.

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615
h4. Diffing

The method +diff+ returns a hash that represents a diff of the receiver and the argument with the following logic:

* Pairs +key+, +value+ that exist in both hashes do not belong to the diff hash.

* If both hashes have +key+, but with different values, the pair in the receiver wins.

* The rest is just merged.

<ruby>
{:a => 1}.diff(:a => 1)
# => {}, first rule

{:a => 1}.diff(:a => 2)
# => {:a => 1}, second rule

{:a => 1}.diff(:b => 2)
# => {:a => 1, :b => 2}, third rule

{:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4)
# => {:a => 1, :b => 2, :d => 4}, all rules

{}.diff({})        # => {}
{:a => 1}.diff({}) # => {:a => 1}
{}.diff(:a => 1)   # => {:a => 1}
</ruby>

An important property of this diff hash is that you can retrieve the original hash by applying +diff+ twice:

<ruby>
hash.diff(hash2).diff(hash2) == hash
</ruby>

Diffing hashes may be useful for error messages related to expected option hashes for example.

2616 2617
NOTE: Defined in +active_support/core_ext/hash/diff.rb+.

2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643
h4. Working with Keys

h5. +except+ and +except!+

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

<ruby>
{:a => 1, :b => 2}.except(:a) # => {:b => 2}
</ruby>

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

<ruby>
{:a => 1}.with_indifferent_access.except(:a)  # => {}
{:a => 1}.with_indifferent_access.except("a") # => {}
</ruby>

The method +except+ may come in handy for example when you want to protect some parameter that can't be globally protected with +attr_protected+:

<ruby>
params[:account] = params[:account].except(:plan_id) unless admin?
@account.update_attributes(params[:account])
</ruby>

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

2644 2645
NOTE: Defined in +active_support/core_ext/hash/except.rb+.

2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675
h5. +stringify_keys+ and +stringify_keys!+

The method +stringify_keys+ returns a hash that has a stringified version of the keys in the receiver. It does so by sending +to_s+ to them:

<ruby>
{nil => nil, 1 => 1, :a => :a}.stringify_keys
# => {"" => nil, "a" => :a, "1" => 1}
</ruby>

The result in case of collision is undefined:

<ruby>
{"a" => 1, :a => 2}.stringify_keys
# => {"a" => 2}, in my test, can't rely on this result though
</ruby>

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

<ruby>
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
  options = options.stringify_keys
  options["type"] = "checkbox"
  ...
end
</ruby>

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

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

2676 2677
NOTE: Defined in +active_support/core_ext/hash/keys.rb+.

2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
h5. +symbolize_keys+ and +symbolize_keys!+

The method +symbolize_keys+ returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending +to_sym+ to them:

<ruby>
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
# => {1 => 1, nil => nil, :a => "a"}
</ruby>

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

The result in case of collision is undefined:

<ruby>
{"a" => 1, :a => 2}.symbolize_keys
# => {:a => 2}, in my test, can't rely on this result though
</ruby>

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

<ruby>
def rewrite_path(options)
  options = options.symbolize_keys
  options.update(options[:params].symbolize_keys) if options[:params]
  ...
end
</ruby>

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

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

2710 2711
NOTE: Defined in +active_support/core_ext/hash/keys.rb+.

2712 2713 2714 2715
h5. +to_options+ and +to_options!+

The methods +to_options+ and +to_options!+ are respectively aliases of +symbolize_keys+ and +symbolize_keys!+.

2716 2717
NOTE: Defined in +active_support/core_ext/hash/keys.rb+.

2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748
h5. +assert_valid_keys+

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

<ruby>
{:a => 1}.assert_valid_keys(:a)  # passes
{:a => 1}.assert_valid_keys("a") # ArgumentError
</ruby>

Active Record does not accept unknown options when building associations for example. It implements that control via +assert_valid_keys+:

<ruby>
mattr_accessor :valid_keys_for_has_many_association
@@valid_keys_for_has_many_association = [
  :class_name, :table_name, :foreign_key, :primary_key,
  :dependent,
  :select, :conditions, :include, :order, :group, :having, :limit, :offset,
  :as, :through, :source, :source_type,
  :uniq,
  :finder_sql, :counter_sql,
  :before_add, :after_add, :before_remove, :after_remove,
  :extend, :readonly,
  :validate, :inverse_of
]

def create_has_many_reflection(association_id, options, &extension)
  options.assert_valid_keys(valid_keys_for_has_many_association)
  ...
end
</ruby>

2749 2750
NOTE: Defined in +active_support/core_ext/hash/keys.rb+.

2751 2752
h4. Slicing

2753
Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779

<ruby>
{:a => 1, :b => 2, :c => 3}.slice(:a, :c)
# => {:c => 3, :a => 1}

{:a => 1, :b => 2, :c => 3}.slice(:b, :X)
# => {:b => 2} # non-existing keys are ignored
</ruby>

If the receiver responds to +convert_key+ keys are normalized:

<ruby>
{:a => 1, :b => 2}.with_indifferent_access.slice("a")
# => {:a => 1}
</ruby>

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

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

<ruby>
hash = {:a => 1, :b => 2}
rest = hash.slice!(:a) # => {:b => 2}
hash                   # => {:a => 1}
</ruby>

2780 2781
NOTE: Defined in +active_support/core_ext/hash/slice.rb+.

2782 2783 2784 2785 2786 2787 2788 2789
h4. Indifferent Access

The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:

<ruby>
{:a => 1}.with_indifferent_access["a"] # => 1
</ruby>

2790 2791
NOTE: Defined in +active_support/core_ext/hash/indifferent_access.rb+.

2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
h3. Extensions to +Regexp+

h4. +multiline?+

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

<ruby>
%r{.}.multiline?  # => false
%r{.}m.multiline? # => true

Regexp.new('.').multiline?                    # => false
Regexp.new('.', Regexp::MULTILINE).multiline? # => true
</ruby>

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.

<ruby>
def assign_route_options(segments, defaults, requirements)
  ...
  if requirement.multiline?
    raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
  end
  ...
end
</ruby>

2818 2819
NOTE: Defined in +active_support/core_ext/regexp.rb+.

2820 2821
h3. Extensions to +Range+

2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
h4. +to_s+

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

<ruby>
(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'"
</ruby>

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.

2836 2837
NOTE: Defined in +active_support/core_ext/range/conversions.rb+.

2838 2839 2840 2841 2842 2843 2844 2845 2846
h4. +step+

Active Support extends the method +Range#step+ so that it can be invoked without a block:

<ruby>
(1..10).step(2) # => [1, 3, 5, 7, 9]
</ruby>

As the example shows, in that case the method returns and array with the corresponding elements.
2847

2848 2849
NOTE: Defined in +active_support/core_ext/range/blockless_step.rb+.

2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866
h4. +include?+

The method +Range#include?+ says whether some value falls between the ends of a given instance:

<ruby>
(2..3).include?(Math::E) # => true
</ruby>

Active Support extends this method 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:

<ruby>
(1..10).include?(3..7)  # => true
(1..10).include?(0..7)  # => false
(1..10).include?(3..11) # => false
(1...9).include?(3..9)  # => false
</ruby>

2867
WARNING: The original +Range#include?+ is still the one aliased to +Range#===+.
2868

2869 2870
NOTE: Defined in +active_support/core_ext/range/include_range.rb+.

2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
h4. +overlaps?+

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

<ruby>
(1..10).overlaps?(7..11)  # => true
(1..10).overlaps?(0..7)   # => true
(1..10).overlaps?(11..27) # => false
</ruby>

2881 2882
NOTE: Defined in +active_support/core_ext/range/overlaps.rb+.

2883 2884
h3. Extensions to +Proc+

X
Xavier Noria 已提交
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925
h4. +bind+

As you surely know Ruby has an +UnboundMethod+ class whose instances are methods that belong to the limbo of methods without a self. The method +Module#instance_method+ returns an unbound method for example:

<ruby>
Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
</ruby>

An unbound method is not callable as is, you need to bind it first to an object with +bind+:

<ruby>
clear = Hash.instance_method(:clear)
clear.bind({:a => 1}).call # => {}
</ruby>

Active Support defines +Proc#bind+ with an analogous purpose:

<ruby>
Proc.new { size }.bind([]).call # => 0
</ruby>

As you see that's callable and bound to the argument, the return value is indeed a +Method+.

NOTE: To do so +Proc#bind+ actually creates a method under the hood. If you ever see a method with a weird name like +__bind_1256598120_237302+ in a stack trace you know now where it comes from.

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

<ruby>
def handler_for_rescue(exception)
  _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
    ...
  end

  case rescuer
  when Symbol
    method(rescuer)
  when Proc
    rescuer.bind(self)
  end
end
</ruby>
2926

2927 2928
NOTE: Defined in +active_support/core_ext/proc.rb+.

2929 2930
h3. Extensions to +Date+

2931 2932
h4. Calculations

2933
NOTE: All the following methods are defined in +active_support/core_ext/date/calculations.rb+.
2934

2935
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.
2936

2937 2938
h5. +Date.current+

2939
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+.
2940 2941 2942

h5. Named dates

2943
h6. +prev_year+, +next_year+
2944

2945
In Ruby 1.9 +prev_year+ and +next_year+ return a date with the same day/month in the last or next year:
2946 2947 2948

<ruby>
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
2949
d.prev_year              # => Fri, 08 May 2009
2950 2951 2952 2953 2954 2955 2956
d.next_year              # => Sun, 08 May 2011
</ruby>

If date is the 29th of February of a leap year, you obtain the 28th:

<ruby>
d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
2957
d.prev_year               # => Sun, 28 Feb 1999
2958 2959 2960
d.next_year               # => Wed, 28 Feb 2001
</ruby>

2961
Active Support defines these methods as well for Ruby 1.8.
2962

2963 2964 2965
h6. +prev_month+, +next_month+

In Ruby 1.9 +prev_month+ and +next_month+ return the date with the same day in the last or next month:
2966 2967 2968

<ruby>
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
2969
d.prev_month             # => Thu, 08 Apr 2010
2970 2971 2972 2973 2974 2975
d.next_month             # => Tue, 08 Jun 2010
</ruby>

If such a day does not exist, the last day of the corresponding month is returned:

<ruby>
2976 2977
Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
2978 2979 2980 2981
Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
</ruby>

2982 2983
Active Support defines these methods as well for Ruby 1.8.

2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041
h6. +beginning_of_week+, +end_of_week+

The methods +beginning_of_week+ and +end_of_week+ return the dates for the beginning and end of week, assuming weeks start on Monday:

<ruby>
d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
d.beginning_of_week      # => Mon, 03 May 2010
d.end_of_week            # => Sun, 09 May 2010
</ruby>

+beginning_of_week+ is aliased to +monday+ and +at_beginning_of_week+. +end_of_week+ is aliased to +sunday+ and +at_end_of_week+.

h6. +next_week+

+next_week+ receives a symbol with a day name in English (in lowercase, default is +:monday+) and it returns the date corresponding to that day in the next week:

<ruby>
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
</ruby>

h6. +beginning_of_month+, +end_of_month+

The methods +beginning_of_month+ and +end_of_month+ return the dates for the beginning and end of the month:

<ruby>
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
</ruby>

+beginning_of_month+ is aliased to +at_beginning_of_month+, and +end_of_month+ is aliased to +at_end_of_month+.

h6. +beginning_of_quarter+, +end_of_quarter+

The methods +beginning_of_quarter+ and +end_of_quarter+ return the dates for the beginning and end of the quarter of the receiver's calendar year:

<ruby>
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
</ruby>

+beginning_of_quarter+ is aliased to +at_beginning_of_quarter+, and +end_of_quarter+ is aliased to +at_end_of_quarter+.

h6. +beginning_of_year+, +end_of_year+

The methods +beginning_of_year+ and +end_of_year+ return the dates for the beginning and end of the year:

<ruby>
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
</ruby>

+beginning_of_year+ is aliased to +at_beginning_of_year+, and +end_of_year+ is aliased to +at_end_of_year+.

3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096
h5. Other Date Computations

h6. +years_ago+, +years_since+

The method +years_ago+ receives a number of years and returns the same date those many years ago:

<ruby>
date = Date.new(2010, 6, 7)
date.years_ago(10) # => Wed, 07 Jun 2000
</ruby>

+years_since+ moves forward in time:

<ruby>
date = Date.new(2010, 6, 7)
date.years_since(10) # => Sun, 07 Jun 2020
</ruby>

If such a day does not exist, the last day of the corresponding month is returned:

<ruby>
Date.new(2012, 2, 29).years_ago(3)     # => Sat, 28 Feb 2009
Date.new(2012, 2, 29).years_since(3)   # => Sat, 28 Feb 2015
</ruby>

h6. +months_ago+, +months_since+

The methods +months_ago+ and +months_since+ work analogously for months:

<ruby>
Date.new(2010, 4, 30).months_ago(2)   # => Sun, 28 Feb 2010
Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
</ruby>

If such a day does not exist, the last day of the corresponding month is returned:

<ruby>
Date.new(2010, 4, 30).months_ago(2)    # => Sun, 28 Feb 2010
Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
</ruby>

h6. +advance+

The most generic way to jump to other days is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, and returns a date advanced as much as the present keys indicate:

<ruby>
date = Date.new(2010, 6, 6)
date.advance(:years => 1, :weeks => 2)  # => Mon, 20 Jun 2011
date.advance(:months => 2, :days => -2) # => Wed, 04 Aug 2010
</ruby>

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.

3097
The method +advance+ advances first one month, and then one day, the result is:
3098 3099

<ruby>
3100 3101
Date.new(2010, 2, 28).advance(:months => 1, :days => 1)
# => Sun, 29 Mar 2010
3102 3103 3104 3105 3106 3107 3108 3109 3110
</ruby>

While if it did it the other way around the result would be different:

<ruby>
Date.new(2010, 2, 28).advance(:days => 1).advance(:months => 1)
# => Thu, 01 Apr 2010
</ruby>

3111
h5. Changing Components
3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126

The method +change+ allows you to get a new date which is the same as the receiver except for the given year, month, or day:

<ruby>
Date.new(2010, 12, 23).change(:year => 2011, :month => 11)
# => Wed, 23 Nov 2011
</ruby>

This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised:

<ruby>
Date.new(2010, 1, 31).change(:month => 2)
# => ArgumentError: invalid date
</ruby>

3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146
h5. Durations

Durations can be added and substracted to dates:

<ruby>
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
</ruby>

They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:

<ruby>
Date.new(1582, 10, 4) + 1.day
# => Fri, 15 Oct 1582
</ruby>

3147
h5. Timestamps
3148

3149
INFO: The following methods return a +Time+ object if possible, otherwise a +DateTime+. If set, they honor the user time zone.
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166

h6. +beginning_of_day+, +end_of_day+

The method +beginning_of_day+ returns a timestamp at the beginning of the day (00:00:00):

<ruby>
date = Date.new(2010, 6, 7)
date.beginning_of_day # => Sun Jun 07 00:00:00 +0200 2010
</ruby>

The method +end_of_day+ returns a timestamp at the end of the day (23:59:59):

<ruby>
date = Date.new(2010, 6, 7)
date.end_of_day # => Sun Jun 06 23:59:59 +0200 2010
</ruby>

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185
+beginning_of_day+ is aliased to +at_beginning_of_day+, +midnight+, +at_midnight+.

h6. +ago+, +since+

The method +ago+ receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:

<ruby>
date = Date.current # => Fri, 11 Jun 2010 
date.ago(1)         # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
</ruby>

Similarly, +since+ moves forward:

<ruby>
date = Date.current # => Fri, 11 Jun 2010 
date.since(1)       # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
</ruby>

h5. Other Time Computations
3186

3187
h4(#date-conversions). Conversions
3188 3189 3190

h3. Extensions to +DateTime+

3191 3192 3193 3194
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.

h4(#calculations-datetime). Calculations

3195 3196
NOTE: All the following methods are defined in +active_support/core_ext/date_time/calculations.rb+.

3197 3198 3199 3200 3201
The class +DateTime+ is a subclass of +Date+ so by loading +active_support/core_ext/date/calculations.rb+ you inherit these methods and their aliases, except that they will always return datetimes:

<ruby>
yesterday
tomorrow
3202 3203
beginning_of_week (monday, at_beginning_of_week)
end_on_week (at_end_of_week)
3204 3205 3206
next_week
months_ago
months_since
3207 3208
beginning_of_month (at_beginning_of_month)
end_of_month (at_end_of_month)
3209 3210
prev_month
next_month
3211 3212 3213 3214
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)
3215 3216 3217 3218 3219 3220 3221 3222 3223
years_ago
years_since
prev_year
next_year
</ruby>

The following methods are reimplemented so you do *not* need to load +active_support/core_ext/date/calculations.rb+ for these ones:

<ruby>
3224
beginning_of_day (midnight, at_midnight, at_beginning_of_day)
3225 3226
end_of_day
ago
3227
since (in)
3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269
</ruby>

On the other hand, +advance+ and +change+ are also defined and support more options, they are documented below.

h5. Named Datetimes

h6. +DateTime.current+

Active Support defines +DateTime.current+ to be like +Time.now.to_datetime+, except that it honors the user time zone, if defined. It also defines instance predicates +past?+, and +future?+ relative to +DateTime.current+.

h5. Other Extensions

h6. +seconds_since_midnight+

The method +seconds_since_midnight+ returns the number of seconds since midnight:

<ruby>
now = DateTime.current     # => Mon, 07 Jun 2010 20:26:36 +0000
now.seconds_since_midnight # => 73596
</ruby>

h6(#utc-datetime). +utc+

The method +utc+ gives you the same datetime in the receiver expressed in UTC.

<ruby>
now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
now.utc                # => Mon, 07 Jun 2010 23:27:52 +0000
</ruby>

This method is also aliased as +getutc+.

h6. +utc?+

The predicate +utc?+ says whether the receiver has UTC as its time zone:

<ruby>
now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
now.utc?           # => false
now.utc.utc?       # => true
</ruby>

3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300
h6(#datetime-advance). +advance+

The most generic way to jump to another datetime is +advance+. This method receives a hash with keys +:years+, +:months+, +:weeks+, +:days+, +:hours+, +:minutes+, and +:seconds+, and returns a datetime advanced as much as the present keys indicate.

<ruby>
d = DateTime.current
# => Thu, 05 Aug 2010 11:33:31 +0000
d.advance(:years => 1, :months => 1, :days => 1, :hours => 1, :minutes => 1, :seconds => 1)
# => Tue, 06 Sep 2011 12:34:32 +0000
</ruby>

This method first computes the destination date passing +:years+, +:months+, +:weeks+, and +:days+ to +Date#advance+ documented above. After that, it adjusts the time calling +since+ with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in +Date#advance+ applies, and we can extend it to show order relevance related to the time bits.

If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:

<ruby>
d = DateTime.new(2010, 2, 28, 23, 59, 59)
# => Sun, 28 Feb 2010 23:59:59 +0000
d.advance(:months => 1, :seconds => 1)
# => Mon, 29 Mar 2010 00:00:00 +0000
</ruby>

but if we computed them the other way around, the result would be different:

<ruby>
d.advance(:seconds => 1).advance(:months => 1)
# => Thu, 01 Apr 2010 00:00:00 +0000
</ruby>

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.

3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332
h5(#datetime-changing-components). Changing Components

The method +change+ allows you to get a new datetime which is the same as the receiver except for the given options, which may include +:year+, +:month+, +:day+, +:hour+, +:min+, +:sec+, +:offset+, +:start+:

<ruby>
now = DateTime.current
# => Tue, 08 Jun 2010 01:56:22 +0000
now.change(:year => 2011, :offset => Rational(-6, 24))
# => Wed, 08 Jun 2011 01:56:22 -0600
</ruby>

If hours are zeroed, then minutes and seconds are too (unless they have given values):

<ruby>
now.change(:hour => 0)
# => Tue, 08 Jun 2010 00:00:00 +0000
</ruby>

Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):

<ruby>
now.change(:min => 0)
# => Tue, 08 Jun 2010 01:00:00 +0000
</ruby>

This method is not tolerant to non-existing dates, if the change is invalid +ArgumentError+ is raised:

<ruby>
DateTime.current.change(:month => 2, :day => 30)
# => ArgumentError: invalid date
</ruby>

3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351
h5. Durations

Durations can be added and substracted to datetimes:

<ruby>
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
</ruby>

They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:

<ruby>
DateTime.new(1582, 10, 4, 23) + 1.hour
# => Fri, 15 Oct 1582 00:00:00 +0000
</ruby>
3352 3353 3354

h3. Extensions to +Time+

3355 3356
h4(#time-calculations). Calculations

3357
NOTE: All the following methods are defined in +active_support/core_ext/time/calculations.rb+.
3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398

Active Support adds to +Time+ many of the methods available for +DateTime+:

<ruby>
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
beginning_of_week (monday, at_beginning_of_week)
end_on_week (at_end_of_week)
next_week
months_ago
months_since
beginning_of_month (at_beginning_of_month)
end_of_month (at_end_of_month)
prev_month
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
prev_year
next_year
</ruby>

They are analogous. Please refer to their documentation above and take into account the following differences:

* +change+ accepts an additional +:usec+ option.
* +Time+ understands DST, so you get correct DST calculations as in

<ruby>
3399 3400 3401
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>

3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444
# In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
t = Time.local_time(2010, 3, 28, 1, 59, 59)
# => Sun Mar 28 01:59:59 +0100 2010
t.advance(:seconds => 1)
# => Sun Mar 28 03:00:00 +0200 2010
</ruby>

* If +since+ or +ago+ jump to a time that can't be expressed with +Time+ a +DateTime+ object is returned instead.

h4. Time Constructors

Active Support defines +Time.current+ to be +Time.zone.now+ if there's a user time zone defined, with fallback to +Time.now+:

<ruby>
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
Time.current
# => Fri, 06 Aug 2010 17:11:58 CEST +02:00
</ruby>

Analogously to +DateTime+, the predicates +past?+, and +future?+ are relative to +Time.current+.

Use the +local_time+ class method to create time objects honoring the user time zone:

<ruby>
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
Time.local_time(2010, 8, 15)
# => Sun Aug 15 00:00:00 +0200 2010
</ruby>

The +utc_time+ class method returns a time in UTC:

<ruby>
Time.zone_default
# => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
Time.utc_time(2010, 8, 15)
# => Sun Aug 15 00:00:00 UTC 2010
</ruby>

Both +local_time+ and +utc_time+ accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.

If the time to be constructed lies beyond the range supported by +Time+ in the runtime platform, usecs are discarded and a +DateTime+ object is returned instead.
3445

3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465
h5. Durations

Durations can be added and substracted to time objects:

<ruby>
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
</ruby>

They translate to calls to +since+ or +advance+. For example here we get the correct jump in the calendar reform:

<ruby>
Time.utc_time(1582, 10, 3) + 5.days
# => Mon Oct 18 00:00:00 UTC 1582
</ruby>

3466 3467
h3. Extensions to +Process+

3468 3469 3470
h4. +daemon+

Ruby 1.9 provides +Process.daemon+, and Active Support defines it for previous versions. It accepts the same two arguments, whether it should chdir to the root directory (default, true), and whether it should inherit the standard file descriptors from the parent (default, false).
3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487

h3. Extensions to +File+

h4. +atomic_write+

With the class method +File.atomic_write+ you can write to a file in a way that will prevent any reader from seeing half-written content.

The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done +atomic_write+ closes the file handle and completes its job.

For example, Action Pack uses this method to write asset cache files like +all.css+:

<ruby>
File.atomic_write(joined_asset_path) do |cache|
  cache.write(join_asset_file_contents(asset_paths))
end
</ruby>

3488
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.
3489 3490 3491 3492 3493

WARNING. Note you can't append with +atomic_write+.

The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.

3494 3495
NOTE: Defined in +active_support/core_ext/file/atomic.rb+.

3496 3497 3498 3499 3500 3501
h3. Extensions to +NameError+

Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument.

The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.

3502
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.
3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516

For example, when an action of +PostsController+ is called Rails tries optimistically to use +PostsHelper+. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that +posts_helper.rb+ raises a +NameError+ due to an actual unknown constant. That should be reraised. The method +missing_name?+ provides a way to distinguish both cases:

<ruby>
def default_helper_module!
  module_name = name.sub(/Controller$/, '')
  module_path = module_name.underscore
  helper module_path
rescue MissingSourceFile => e
  raise e unless e.is_missing? "#{module_path}_helper"
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
</ruby>
3517 3518 3519

NOTE: Defined in +active_support/core_ext/name_error.rb+.

3520 3521
h3. Extensions to +LoadError+

3522
Active Support adds +is_missing?+ to +LoadError+, and also assigns that class to the constant +MissingSourceFile+ for backwards compatibility.
3523

3524
Given a path name +is_missing?+ tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
3525

3526
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:
3527 3528 3529 3530 3531 3532 3533

<ruby>
def default_helper_module!
  module_name = name.sub(/Controller$/, '')
  module_path = module_name.underscore
  helper module_path
rescue MissingSourceFile => e
3534
  raise e unless e.is_missing? "helpers/#{module_path}_helper"
3535 3536 3537 3538 3539
rescue NameError => e
  raise e unless e.missing_name? "#{module_name}Helper"
end
</ruby>

3540 3541
NOTE: Defined in +active_support/core_ext/load_error.rb+.

3542 3543 3544 3545 3546
h3. Changelog

"Lighthouse ticket":https://rails.lighthouseapp.com/projects/16213/tickets/67

* April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn