1 How to Load Core Extensions

1.1 Stand-Alone Active Support

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

Thus, after a simple require like:

require 'active_support'

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

1.1.1 Cherry-picking a Definition

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

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

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

1.1.2 Loading Grouped Core Extensions

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

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

require 'active_support'
require 'active_support/core_ext/object'

1.1.3 Loading All Core Extensions

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

require 'active_support'
require 'active_support/core_ext'

1.1.4 Loading All Active Support

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

require 'active_support/all'

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

1.2 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.

2 Extensions to All Objects

2.1 blank? and present?

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

nil and false,

strings composed only of whitespace (see note below),

empty arrays and hashes, and

any other object that responds to empty? and is empty.

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

Note that numbers are not mentioned. In particular, 0 and 0.0 are not blank.

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

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

Defined in active_support/core_ext/object/duplicable.rb.

2.4 deep_dup

The deep_dup method returns deep copy of a given object. Normally, when you dup an object that contains other objects, Ruby does not dup them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:

As you can see, after duplicating the Array instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since dup does not make deep copy, the string inside the array is still the same object.

If you need a deep copy of an object, you should use deep_dup. Here is an example:

2.5 try

When you want to call a method on an object only if it is not nil, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use try. try is like Object#send except that it returns nil if sent to nil.

2.7 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

def acts_like_string?
end

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

some_klass.acts_like?(:string)

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

Defined in active_support/core_ext/object/acts_like.rb.

2.8 to_param

All objects in Rails respond to the method to_param, which is meant to return something that represents them as values in a query string, or as URL fragments.

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
"#{id}-#{name.parameterize}"
end
end

we get:

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

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].

Defined in active_support/core_ext/object/to_param.rb.

2.9 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

class User
def to_param
"#{id}-#{name.parameterize}"
end
end

we get:

current_user.to_query('user') # => "user=357-john-smith"

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

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 "&":

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

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:

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

Defined in active_support/core_ext/object/with_options.rb.

2.11 JSON support

Active Support provides a better implementation of to_json than the json gem ordinarily provides for Ruby objects. This is because some classes, like Hash, OrderedHash and Process::Status need special handling in order to provide a proper JSON representation.

Defined in active_support/core_ext/object/json.rb.

2.12 Instance Variables

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

2.12.1 instance_values

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

2.13 Silencing Warnings and Exceptions

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

silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }

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

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

Defined in active_support/core_ext/kernel/reporting.rb.

2.14 in?

The predicate in? tests if an object is included in another object. An ArgumentError exception will be raised if the argument passed does not respond to include?.

3 Extensions to Module

3.1 alias_method_chain

Using plain Ruby you can wrap methods with other methods, that's called alias chaining.

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

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

Defined in active_support/core_ext/module/aliasing.rb.

3.2 Attributes

3.2.1 alias_attribute

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

class User < ActiveRecord::Base
# You can refer to the email column as "login".
# This can be meaningful for authentication code.
alias_attribute :login, :email
end

Defined in active_support/core_ext/module/aliasing.rb.

3.2.2 Internal Attributes

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

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

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:

3.2.3 Module Attributes

The macros mattr_reader, mattr_writer, and mattr_accessor are the same as the cattr_* macros defined for class. In fact, the cattr_* macros are just aliases for the mattr_* macros. Check Class Attributes.

These methods are analogous to their built-in counterparts. In particular,
qualified_constant_defined? accepts an optional second argument to be
able to say whether you want the predicate to look in the ancestors.
This flag is taken into account for each constant in the expression while
walking down the path.

As the last example implies, the second argument defaults to true,
as in const_defined?.

For coherence with the built-in methods only relative paths are accepted.
Absolute qualified constant names like ::Math::PI raise NameError.

Defined in active_support/core_ext/module/qualified_const.rb.

3.5 Reachable

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

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

module M
end
M.reachable? # => true

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

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

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

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:

delegate :name, to: :profile, allow_nil: true

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

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

delegate :street, to: :address, prefix: true

The previous example generates address_street rather than street.

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:

delegate :size, to: :attachment, prefix: :avatar

In the previous example the macro generates avatar_size rather than size.

Defined in active_support/core_ext/module/delegation.rb

3.8 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.

Defined in active_support/core_ext/module/remove_method.rb

4 Extensions to Class

4.1 Class Attributes

4.1.1 class_attribute

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

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

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

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

Defined in active_support/core_ext/class/attribute.rb

4.1.2 cattr_reader, cattr_writer, and cattr_accessor

The macros cattr_reader, cattr_writer, and cattr_accessor are analogous to their attr_* counterparts but for classes. They initialize a class variable to nil unless it already exists, and generate the corresponding class methods to access it:

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

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

5 Extensions to String

5.1 Output Safety

5.1.1 Motivation

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

5.1.2 Safe Strings

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

Strings are considered to be unsafe by default:

"".html_safe? # => false

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

s = "".html_safe
s.html_safe? # => true

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

5.9 indent

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

5.11 Inflections

5.11.1 pluralize

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

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

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

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

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

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

5.11.10 tableize

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

Defined in active_support/core_ext/string/inflections.rb.

5.11.11 classify

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

10.2.2 append

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

User.exists?(email: params[:email])

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 * in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.

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

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

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.

Defined in active_support/core_ext/array/extract_options.rb.

10.4 Conversions

10.4.1 to_sentence

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

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 "objects":

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 "object". 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:

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.

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:

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.

Defined in active_support/core_ext/hash/conversions.rb.

11.2 Merging

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

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

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

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

options = {length: 30, omission: "..."}.merge(options)

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

options = options.reverse_merge(length: 30, omission: "...")

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

options.reverse_merge!(length: 30, omission: "...")

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

Defined in active_support/core_ext/hash/reverse_merge.rb.

11.2.2 reverse_update

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

Note that reverse_update has no bang.

Defined in active_support/core_ext/hash/reverse_merge.rb.

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

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

The method deep_merge! performs a deep merge in place.

Defined in active_support/core_ext/hash/deep_merge.rb.

11.3 Deep duplicating

The method Hash.deep_dup duplicates itself and all keys and values
inside recursively with Active Support method Object#deep_dup. It works like Enumerator#each_with_object with sending deep_dup method to each pair inside.

14 Extensions to Proc

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

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

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

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

Active Support defines Proc#bind with an analogous purpose:

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

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

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:

15 Extensions to Date

15.1 Calculations

All the following methods are defined in active_support/core_ext/date/calculations.rb.

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.

15.1.1 Date.current

Active Support defines Date.current to be today in the current time zone. That's like Date.today, except that it honors the user time zone, if defined. It also defines Date.yesterday and Date.tomorrow, and the instance predicates past?, today?, and future?, all of them relative to Date.current.

When making Date comparisons using methods which honor the user time zone, make sure to use Date.current and not Date.today. There are cases where the user time zone might be in the future compared to the system time zone, which Date.today uses by default. This means Date.today may equal Date.yesterday.

15.1.2 Named dates

15.1.2.1 prev_year, next_year

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

15.1.2.4 beginning_of_week, end_of_week

The methods beginning_of_week and end_of_week return the dates for the
beginning and end of the week, respectively. Weeks are assumed to start on
Monday, but that can be changed passing an argument, setting thread local
Date.beginning_of_week or config.beginning_of_week.

15.1.2.6 prev_week, next_week

The method next_week receives a symbol with a day name in English (default is the thread local Date.beginning_of_week, or config.beginning_of_week, or :monday) and it returns the date corresponding to that day.

To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.

The method advance advances first one month, and then one day, the result is:

beginning_of_hour, end_of_hour, beginning_of_minute and end_of_minute are implemented for Time and DateTime but notDate as it does not make sense to request the beginning or end of an hour or minute on a Date instance.

15.1.6.4 ago, since

The method ago receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:

On the other hand, advance and change are also defined and support more options, they are documented below.

The following methods are only implemented in active_support/core_ext/date_time/calculations.rb as they only make sense when used with a DateTime instance:

beginning_of_hour (at_beginning_of_hour)
end_of_hour

16.1.1 Named Datetimes

16.1.1.1 DateTime.current

Active Support defines DateTime.current to be like Time.now.to_datetime, except that it honors the user time zone, if defined. It also defines DateTime.yesterday and DateTime.tomorrow, and the instance predicates past?, and future? relative to DateTime.current.

16.1.2 Other Extensions

16.1.2.1 seconds_since_midnight

The method seconds_since_midnight returns the number of seconds since midnight:

16.1.2.3 utc?

16.1.2.4 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.

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:

If since or ago jump to a time that can't be expressed with Time a DateTime object is returned instead.

17.1.1 Time.current

Active Support defines Time.current to be today in the current time zone. That's like Time.now, except that it honors the user time zone, if defined. It also defines the instance predicates past?, today?, and future?, all of them relative to Time.current.

When making Time comparisons using methods which honor the user time zone, make sure to use Time.current instead of Time.now. There are cases where the user time zone might be in the future compared to the system time zone, which Time.now uses by default. This means Time.now.to_date may equal Date.yesterday.

17.1.2 all_day, all_week, all_month, all_quarter and all_year

The method all_day returns a range representing the whole day of the current time.

File.atomic_write(joined_asset_path) do |cache|
cache.write(join_asset_file_contents(asset_paths))
end

To accomplish this atomic_write creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists atomic_write overwrites it and keeps owners and permissions. However there are a few cases where atomic_write cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is accessible to the processes that need it.

Due to the chmod operation atomic_write performs, if the target file has an ACL set on it this ACL will be recalculated/modified.

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.

Defined in active_support/core_ext/file/atomic.rb.

19 Extensions to Marshal

19.1 load

Active Support adds constant autoloading support to load.

For example, the file cache store deserializes this way:

File.open(file_name) { |f| Marshal.load(f) }

If the cached data refers to a constant that is unknown at that point, the autoloading mechanism is triggered and if it succeeds the deserialization is retried transparently.

If the argument is an IO it needs to respond to rewind to be able to retry. Regular files respond to rewind.

Defined in active_support/core_ext/marshal.rb.

20 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.

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

For example, when an action of ArticlesController is called Rails tries optimistically to use ArticlesHelper. 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 articles_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:

21 Extensions to LoadError

Active Support adds is_missing? to LoadError.

Given a path name is_missing? tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).

For example, when an action of ArticlesController is called Rails tries to load articles_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:

Feedback

You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Make sure to check
Edge Guides first to verify
if the issues are already fixed or not on the master branch.
Check the Ruby on Rails Guides Guidelines
for style and conventions.

If for whatever reason you spot something to fix but cannot patch it yourself, please
open an issue.