Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Tree: f56b814671
Fetching contributors…

Cannot retrieve contributors at this time

1311 lines (920 sloc) 41.4 KB

Active Support Overview

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.

By referring to this guide you will learn:

  • The extensions to the Ruby core modules and classes provided by Rails.
  • The rest of fundamental libraries available in Rails.


Extensions to All Objects

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:

def charset
charset = String(headers[“Content-Type”] || headers[“type”]).split(“;”)1
charset.blank? ? nil : charset.strip.split(“=”)1

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:

def instantiate_observers
return if @observers.blank?

  1. end

The method present? is equivalent to !blank?:

assert response.body.present? # same as !response.body.blank?


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

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

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

true.dup # => TypeError: can’t dup TrueClass

Some numbers which are not singletons are not duplicable either:

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

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

"".duplicable? # => true
false.duplicable? # => false

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.


The method returning yields its argument to a block and returns it. You tipically use it with a mutable object that gets modified in the block:

def html_options_for_form(url_for_options, options, *parameters_for_url)
returning options.stringify_keys do |html_options|
html_options[“enctype”] = “multipart/form-data” if html_options.delete(“multipart”)
html_options[“action”] = url_for(url_for_options, *parameters_for_url)

See also Object#tap.


Object#tap exists in Ruby 1.8.7 and 1.9, and it is defined by Active Support for previous versions. This method yields its receiver to a block and returns it.

For example, the following class method from ActionDispatch::TestResponse creates, initializes, and returns a new test response using tap:

def self.from_response(response)
new.tap do |resp|
resp.status = response.status
resp.headers = response.headers
resp.body = response.body

See also Object#returning.


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:

def log_info(sql, name, ms)
if @logger && @logger.debug?
name = ‘s (.1fms)’ % [name || ‘SQL’, ms]
@logger.debug(format_log_entry(name, sql.squeeze(’ ’)))

You can shorten that using Object#try. This method is a synonim for Object#send except that it returns nil if sent to nil. The previous example could then be rewritten as:

def log_info(sql, name, ms)
if @logger.try(:debug?)
name = ‘s (.1fms)’ % [name || ‘SQL’, ms]
@logger.debug(format_log_entry(name, sql.squeeze(’ ’)))


The method metaclass returns the singleton class on any object:

String.metaclass # => # # => #<Class:#>

class_eval(*args, &block)

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

class Proc
def bind(object)
block, time = self,
object.class_eval do
method_name = “__bind_#{time.to_i}_#{time.usec}”
define_method(method_name, &block)
method = instance_method(method_name)


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

def acts_like_string?

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


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


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 a URL fragments.

By default to_param just calls to_s:

7.to_param # => “7”

The return value of to_param should not be escaped:

“Tom & Jerry”.to_param # => “Tom & Jerry”

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 “/”:

[0, true, String].to_param # => “0/true/String”

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

class User
def to_param

we get:

user_path(@user) # => “/users/357-john-smith”

WARNING. Controllers need to be aware of any redifinition of to_param because when a request like that comes in “357-john-smith” is the value of params[:id].


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

class User
def to_param

we get:

current_user.to_query(‘user’) # => user=357-john-smith

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


  1. => “company%5Bname%5D=Johnson+%26+Johnson”

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

Arrays return the result of applying to_query to each element with key[] as key, and join the result with “&”:

[3.4, -45.6].to_query(‘sample’)

  1. => “sample%5B%5D=3.4&sample%5B%5D=-45.6”

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

{:c => 3, :b => 2, :a => 1}.to_query # => “a=1&b=2&c=3”

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

{:id => 89, :name => “John Smith”}.to_query(‘user’)

  1. => “user%5Bid%5D=89&user%5Bname%5D=John+Smith”


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:

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

this way:

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

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:

I18n.with_options :locale => user.locale, :scope => “newsletter” do |i18n|
subject i18n.t :subject
body i18n.t :body, :user_name =>

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.

Instance Variables

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


The method instance_variable_defined? exists in Ruby 1.8.6 and later, and it is defined for previous versions anyway:

class C
def initialize
@a = 1

def m @b = 2 end


c =

c.instance_variable_defined?(“@a”) # => true
c.instance_variable_defined?(:@a) # => true
c.instance_variable_defined?(“a”) # => NameError: `a’ is not allowed as an instance variable name

c.instance_variable_defined?(“@b”) # => false
c.instance_variable_defined?(“@b”) # => true


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:

class C
def initialize(x, y)
@x, @y = x, y
end, 1).instance_variable_names # => [“@y”, “@x”]

WARNING: The order in which the names are returned is unespecified, and it indeed depends on the version of the interpreter.


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:

class C
def initialize(x, y)
@x, @y = x, y
end, 1).instance_values # => {"x" => 0, “y” => 1}

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.

class C
def initialize(x, y, z)
@x, @y, @z = x, y, z

def protected_instance_variables %w(@z) end


a =, 1, 2)
b =, 4, 5)

a.copy_instance_variables_from(b, [:@y])

  1. a is now: @x = 3, @y = 1, @z = 2

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

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:

silence_warnings { Object.const_set “RAILS_DEFAULT_LOGGER”, logger }

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

silence_stream(STDOUT) do

  1. STDOUT is silent here

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:

  1. If the user is locked the increment is lost, no big deal.
    suppress(ActiveRecord::StaleObjectError) do
    current_user.increment! :visits

Extensions to Module



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:

ActionController::TestCase.class_eval do

  1. save a reference to the original process method
    alias_method :original_process, :process
  1. now redefine process and delegate to original_process
    def process(action, params=nil, session=nil, flash=nil, http_method=‘GET’)
    params = Hash[* {|k, v| [k, v.to_s]}.flatten]
    original_process(action, params, session, flash, http_method)

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:

ActionController::TestCase.class_eval do
def process_with_stringified_params(…)
params = Hash[* {|k, v| [k, v.to_s]}.flatten]
process_without_stringified_params(action, params, session, flash, http_method)
alias_method :process_without_stringified_params, :process
alias_method :process, :process_with_stringified_params

The method alias_method_chain provides a shortcut for that pattern:

ActionController::TestCase.class_eval do
def process_with_stringified_params(…)
params = Hash[* {|k, v| [k, v.to_s]}.flatten]
process_without_stringified_params(action, params, session, flash, http_method)
alias_method_chain :process, :stringified_params

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.


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):

class User < ActiveRecord::Base

  1. let me refer to the email column as “login”,
  2. much meaningful for authentication code
    alias_attribute :login, :email

Extensions to Class

Class Attribute Accessors

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:

class MysqlAdapter < AbstractAdapter

  1. Generates class methods to access @@emulate_booleans.
    cattr_accessor :emulate_booleans
    self.emulate_booleans = true

Instance methods are created as well for convenience. For example given

module ActionController
class Base
cattr_accessor :logger

we can access logger in actions. The generation of the writer instance method can be prevented setting :instance_writer to false (not any false value, but exactly false):

module ActiveRecord
class Base

  1. No pluralize_table_names= instance writer is generated.
    cattr_accessor :pluralize_table_names, :instance_writer => false

Class Inheritable Attributes

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 accesors for class-level data which is inherited but not shared with children:

module ActionController
class Base

  2. The value of allow_forgery_protection is inherited,
  3. but its value in a particular class does not affect
  4. the value in the rest of the controllers hierarchy.
    class_inheritable_accessor :allow_forgery_protection

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:


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):

module ActiveRecord
class Base
class_inheritable_accessor :default_scoping, :instance_writer => false

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.

There’s a related macro called superclass_delegating_accessor, however, that does not copy the value when the base class is subclassed. Instead, it delegates reading to the superclass as long as the attribute is not set via its own writer. For example, ActionMailer::Base defines delivery_method this way:

module ActionMailer
class Base
superclass_delegating_accessor :delivery_method
self.delivery_method = :smtp

If for whatever reason an application loads the definition of a mailer class and after that sets ActionMailer::Base.delivery_method, the mailer class will still see the new value. In addition, the mailer class is able to change the delivery_method without affecting the value in the parent using its own inherited class attribute writer.


The subclasses method returns the names of all subclasses of a given class as an array of strings. That comprises not only direct subclasses, but all descendants down the hierarchy:

class C; end
C.subclasses # => []

Integer.subclasses # => [“Bignum”, “Fixnum”]

module M
class A; end
class B1 < A; end
class B2 < A; end

module N
class C < M::B1; end

M::A.subclasses # => [“N::C”, “M::B2”, “M::B1”]

The order in which these class names are returned is unspecified.

See also Object#subclasses_of in Extensions to All Objects FIX THIS LINK.

Class Removal

Roughly speaking, the remove_class method removes the class objects passed as arguments:

Class.remove_class(Hash, Dir) # => [Hash, Dir]
Hash # => NameError: uninitialized constant Hash
Dir # => NameError: uninitialized constant Dir

More specifically, remove_class attempts to remove constants with the same name as the passed class objects from their parent modules. So technically this method does not guarantee the class objects themselves are not still valid and alive somewhere after the method call:

module M
class A; end
class B < A; end

A2 = M::A

M::A.object_id # => 13053950

M::B.superclass.object_id # => 13053950 (same object as before) # => “M::A” (name is hard-coded in object)

WARNING: Removing fundamental classes like String can result in really funky behaviour.

The method remove_subclasses provides a shortcut for removing all descendants of a given class, where “removing” has the meaning explained above:

class A; end
class B1 < A; end
class B2 < A; end
class C < A; end

A.subclasses # => [“C”, “B2”, “B1”]
A.subclasses # => []
C # => NameError: uninitialized constant C

See also Object#remove_subclasses_of in Extensions to All Objects FIX THIS LINK.

Extensions to Symbol


The method to_proc turns a symbol into a Proc object so that for example

emails = {|u|}

can be written as

emails =

TIP: If the method that receives the Proc yields more than one value to it the rest are considered to be arguments of the method call.

Symbols from Ruby 1.8.7 on respond to to_proc, and Active Support defines it for previous versions.

Extensions to String


Ruby 1.9 introduces String#bytesize to obtain the length of a string in bytes. Ruby 1.8.7 defines this method as an alias for String#size for forward compatibility, and Active Support does so for previous versions.


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

" \n foo\n\r \t bar \n".squish # => “foo bar”

There’s also the destructive version String#squish!.

Key-based Interpolation

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

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

Active Support adds that functionality to % in previous versions of Ruby.

start_with? and end_width?

Ruby 1.8.7 and up define the predicates String#start_with? and String#end_with?:

“foo”.start_with?(“f”) # => true
“foo”.start_with?(“g”) # => false
“foo”.start_with?("") # => true

“foo”.end_with?(“o”) # => true
“foo”.end_with?(“p”) # => false
“foo”.end_with?("") # => true

If strings do not respond to those methods Active Support emulates them, and also defines their 3rd person aliases:

“foo”.starts_with?(“f”) # => true
“foo”.ends_with?(“o”) # => true

in case you feel more comfortable spelling them that way.

WARNING. Active Support invokes to_s on the argument, but Ruby does not. Since Active Support defines these methods only if strings do not respond to them, this corner of their behaviour depends on the interpreter that runs a given Rails application. You change the interpreter, and start_with?(1) may change its return value. In consequence, it’s more portable not to rely on that and pass always strings.


Ruby 1.8.7 and up define the iterator String#each_char that understands UTF8 and yields strings with a single character each, so they have length 1 but may be multibyte. Active Support defines that method for previous versions of Ruby:

“\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E”.each_char {|c| print c} # => 日本語

Extensions to Numeric

Extensions to Integer


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

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

WARNING: Due the way it is implemented the argument must be nonzero, otherwise ZeroDivisionError is raised.

even? and odd?

Integers in Ruby 1.8.7 and above respond to even? and odd?, Active Support defines them for older versions:

-1.even? # => false
-1.odd? # => true
0.even? # => true
0.odd? # => false
2.even? # => true
2.odd? # => false


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

1.ordinalize # => “1st”
2.ordinalize # => “2nd”
53.ordinalize # => “53rd”
2009.ordinalize # => “2009th”

Extensions to Float

Extensions to BigDecimal

Extensions to Enumerable

Extensions to Array


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:

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

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

%w(a b c d).from(2) # => %w(c d)
%w(a b c d).from(10) # => nil
[].from(0) # => nil

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

You can pick a random element with rand:

shape_type = [Circle, Square, Triangle].rand



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

%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”

This method accepts three options:

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

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

Option I18n key
:two_words_connector support.array.two_words_connector
:words_connector support.array.words_connector
:last_word_connector support.array.last_word_connector

Options :connector and :skip_last_comma are deprecated.


The method to_formatted_s acts like to_s by default.

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

[].to_formatted_s(:db) # => “null”
[user].to_formatted_s(:db) # => “8456”
invoice.lines.to_formatted_s(:db) # => “23,567,556,12”

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


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

Contributor.all(:limit => 2, :order => ‘rank ASC’).to_xml

  1. =>
  2. <?xml version=“1.0” encoding=“UTF-8”?>
  3. 4356
  4. Jeremy Kemper
  5. 1
  6. jeremy-kemper
  7. 4404
  8. David Heinemeier Hansson
  9. 2
  10. david-heinemeier-hansson

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

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

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

[Contributor.first, Commit.first].to_xml

  1. =>
  2. <?xml version=“1.0” encoding=“UTF-8”?>
  3. 4583
  4. Aaron Batalion
  5. 53
  6. aaron-batalion
  7. Joshua Peek
  8. 2009-09-02T16:44:36Z
  9. origin/master
  10. 2009-09-02T16:44:36Z
  11. Joshua Peek
  12. 190316
  13. false
  14. Kill AMo observing wrap_with_notifications since ARes was only using it
  15. 723a47bfb3708f968821bc969a9a3fc873a3ed58

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

[{:a => 1, :b => 2}, {:c => 3}].to_xml

  1. =>
  2. <?xml version=“1.0” encoding=“UTF-8”?>
  3. 2
  4. 1
  5. 3

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

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 :children allows you to set these node names.

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

Contributor.all(:limit => 2, :order => ‘rank ASC’).to_xml(:skip_types => true)

  1. =>
  2. <?xml version=“1.0” encoding=“UTF-8”?>
  3. 4356
  4. Jeremy Kemper
  5. 1
  6. jeremy-kemper
  7. 4404
  8. David Heinemeier Hansson
  9. 2
  10. david-heinemeier-hansson


The class method Array.wrap behaves like the function Array() except that it does not try to call to_a on its argument. That changes the behaviour for enumerables:

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


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:

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

or yields them in turn if a block is passed:

<% sample.in_groups_of(3) do |a, b, c| >

<=h a >
<=h b >
<=h c %>

<% end %>

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

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

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

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

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

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:

%w(1 2 3 4 5 6 7).in_groups(3)

  1. => [[“1”, “2”, “3”], [“4”, “5”, nil], [“6”, “7”, nil]]

or yields them in turn if a block is passed:

%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
[“1”, “2”, “3”]
[“4”, “5”, nil]
[“6”, “7”, nil]

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

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

%w(1 2 3 4 5 6 7).in_groups(3, “0”)

  1. => [[“1”, “2”, “3”], [“4”, “5”, “0”], [“6”, “7”, “0”]]

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

%w(1 2 3 4 5 6 7).in_groups(3, false)

  1. => [[“1”, “2”, “3”], [“4”, “5”], [“6”, “7”]]

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

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:

(-5..5).to_a.split { |i| i.multiple_of?(4) }

  1. => [[-5], [-3, -2, -1], [1, 2, 3], 5]

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

[0, 1, -5, 1, 1, “foo”, “bar”].split(1)

  1. => [0, [-5], [], [“foo”, “bar”]]

NOTE: Observe in the previous example that consecutive separators result in empty arrays.

Extensions to Hash



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

{"foo" => 1, “bar” => 2}.to_xml

  1. =>
  2. <?xml version=“1.0” encoding=“UTF-8”?>
  3. 1
  4. 2

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

  • If value is a hash there’s a recursive call with key as :root.
  • If value is an array there’s a recursive call with key as :root, and key singularized as :children.
  • If value is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the options hash as first argument with key as :root, and key singularized as second argument. Its return value becomes a new node.
  • If value responds to to_xml the method is invoked with key as :root.
  • Otherwise, a node with key as tag is created with a string representation of value as text node. If value is nil an attribute “nil” set to “true” is added. Unless the option :skip_types exists and is true, an attribute “type” is added as well according to the following mapping:

    “Symbol” => “symbol”,
    “Fixnum” => “integer”,
    “Bignum” => “integer”,
    “BigDecimal” => “decimal”,
    “Float” => “float”,
    “TrueClass” => “boolean”,
    “FalseClass” => “boolean”,
    “Date” => “date”,
    “DateTime” => “datetime”,
    “Time” => “datetime”

By default the root node is “hash”, but that’s configurable via the :root option.

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

Deep Merging

Ruby has a builtin method Hash#merge that merges two hashes:

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

  1. => {:a => 0, :b => 1, :c => 2}

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:

{:a => {:b => 1}}.deep_merge(:a => {:c => 2})

  1. => {:a => {:b => 1, :c => 2}}

The method deep_merge! performs a deep merge in place.


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.

{:a => 1}.diff(:a => 1)

  1. => {}, first rule

{:a => 1}.diff(:a => 2)

  1. => {:a => 1}, second rule

{:a => 1}.diff(:b => 2)

  1. => {:a => 1, :b => 2}, third rule

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

  1. => {:a => 1, :b => 2, :d => 4}, all rules

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

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

hash1.diff(hash2).diff(hash2) == hash1

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

Removing Keys

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

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

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

{:a => 1}.with_indifferent_access.except(:a) # => {}
{:a => 1}.with_indifferent_access.except(“a”) # => {}

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

params[:account] = params[:account].except(:plan_id) unless admin?

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

Extensions to Range

Extensions to Proc

Extensions to Date

Extensions to DateTime

Extensions to Time

Extensions to Process

Extensions to Pathname

Extensions to File


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:

File.atomic_write(joined_asset_path) do |cache|

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. If the target file exists atomic_write overwrites it and keeps owners and permissions.

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.

Extensions to Exception

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.

TIP: A symbol can represent a fully-qualified constant name as in :“ActiveRecord::Base”, so the behaviour for symbols is defined for convenience, not because it has to be that way technically.

For example, when an action of PostsController is called Rails tries optimistically to use PostsHelper. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that posts_helper.rb raises a NameError due to an actual unknown constant. That should be reraised. The method missing_name? provides a way to distinguish both cases:

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”

Extensions to LoadError

Rails hijacks to return a MissingSourceFile exception:

$ ruby e ‘require “nonexistent”’
…: no such file to load -
nonexistent (LoadError)

$ script/runner ‘require “nonexistent”’
…: no such file to load — nonexistent (MissingSourceFile)

The class MissingSourceFile is a subclass of LoadError, so any code that rescues LoadError as usual still works as expected. Point is these exception objects respond to is_missing?, which given a path name tests whether the exception was raised due to that particular file (except perhaps for the “.rb” extension).

For example, when an action of PostsController is called Rails tries to load posts_helper.rb, but that file may not exist. That’s fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist, but it 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:

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”

Extensions to CGI

Extensions to Benchmark


Lighthouse ticket

Jump to Line
Something went wrong with that request. Please try again.