Active Support is a Rails library containing utility classes and extensions to Ruby’s built-in libraries. It usually doesn’t get much attention on its own—you might even call its modules the supporting cast members of the Rails ensemble.
However, Active Support’s low profile doesn’t diminish its importance in day-to-day Rails programming. To ensure that this book is useful as an offline programming companion, here is a complete, enhanced version of the Rails Active Support API reference, supplemented in most cases with realistic example usages and commentary. As your reviewing the material in this appendix, note that many of the methods featured here are used primarily by other Rails libraries and are not particularly useful to application developers.
Section headings reflect the name of the Class or Module where the API method is located and are organized in alphabetical order for easy lookup. Sub-sections appear according to the name of the Ruby file in which they exist within Active Support’s lib
directory. Finally, the sub-sub-sections are the API methods themselves.
Array
The following methods provide additional functionality for accessing array elements.
active_support/core_ext/array/access
from(position)
Returns the tail of the array starting from the position
specified. Note that the position is zero-indexed.
> %w(foo bar baz quux).from(2)
=> ["baz", "quux"]
to(position)
Returns the beginning elements of the array up to position
specified. Note that the position is zero-indexed.
> %w(foo bar baz quux).to(2)
=> ["foo", "bar", "baz"]
second
Equivalent to calling self[1]
.
> %w(foo bar baz quux).second
=> "bar"
third
Equivalent to self[2]
.
fourth
Equivalent to self[3]
.
fifth
Equivalent to self[4]
.
forty_two
Equivalent to calling self[41]
—a humorous addition to the API by David.
active_support/core_ext/array/conversions
The following methods are used for converting Ruby arrays into other formats.
to_formatted_s(format = :default)
Two formats are supported, :default
and :db
. The :default
format delegates to the normal to_s
method for an array, which simply concatenates the contents into one mashed-up string.
> %w(foo bar baz quux).to_s
=> "foobarbazquux"
The much more interesting :db
option returns "null"
if the array is empty, or concatenates the id
fields of its member elements into a comma-delimited string with code like this:
collect { |element| element.id }.join(",")
In other words, the :db
formatting is meant to work with ActiveRecord objects (or other types of objects that properly respond to id
).
to_s
The to_s
method of Array
is aliased to to_formatted_s
.
to_sentence(options = {})
Converts the array to a comma-separated sentence in which the last element is joined by a connector word.
>> %w(alcohol tobacco firearms).to_sentence
=> "alcohol, tobacco, and firearms"
The following options are available for to_sentence:
:connector
The word used to join the last element in arrays with two or more elements (default: “and”).
:skip_last_comma
Set this option to true
to return “a, b and c” instead of “a, b, and c.”
to_xml(options = {}) |xml| ...
As covered in Chapter 15, XML and Active Resource, the to_xml
method on Array
can be used to create an XML collection by iteratively calling to_xml
on its members, and wrapping the entire thing in an enclosing element. All of the array elements must respond to to_xml
.
>> ["riding","high"].to_xml
RuntimeError: Not all elements respond to to_xml
The following example yields the Builder
object to an optional block so that arbitrary markup can be inserted at the bottom of the generated XML, as the last child of the enclosing element.
{:foo => "foo", :bar => 42}.to_xml do |xml|
xml.did_it "again"
end
The options for to_xml
are:
:builder
Defaults to a new instance of Builder::XmlMarkup
. Specify explicitly if you’re calling to_xml
on this array as part of a larger XML construction routine.
:children
Sets the name to use for element tags explicitly. Defaults to singularized version of the :root
name by default.
:dasherize
Whether or not to turn underscores to dashes in tag names (defaults to true
).
:indent
Indent level to use for generated XML (defaults to two spaces).
:root
The tag name to use for the enclosing element. If no :root
is supplied and all members of the array are of the same class, the dashed, pluralized form of the first element’s class name is used as a default. Otherwise the default :root
is records
.
:skip_instruct
Whether or not to generate an XML instruction tag by calling instruct!
on Builder
.
:skip_types
Whether or not to include a type="array"
attribute on the enclosing element.
active_support/core_ext/array/extract_options
Active Support provides a method for extracting Rails-style options from a variable-length set of argument parameters.
extract_options!
Extracts options from a variable set of arguments. It’s a bang method because it removes and returns the last element in the array if it’s a hash; otherwise, it returns a blank hash and the source array is unmodified.
active_support/core_ext/array/grouping
Methods used for splitting array elements into logical groupings.
in_groups(number, fill_with = nil) |group| ...
The in_groups
method splits an array into a number
of equally sized groups. If a fill_with
parameter is provided, its value is used to pad the groups into equal sizes.
In the special case that you don’t want equally sized groups (in other words, no padding) then pass false
as the value of fill_with
.
in_groups_of(number, fill_with = nil) {|group| ...}
Related to its sibling in_groups
, the in_groups_of
method splits an array into groups of the specified number
size, padding any remaining slots. The fill_with
parameter is used for padding and defaults to nil
. If a block is provided, it is called with each group; otherwise, a two-dimensional array is returned.
>> %w(1 2 3 4 5 6 7).in_groups_of(3)
=> [[1, 2, 3], [4, 5, 6], [7, nil, nil]
>> %w(1 2 3).in_groups_of(2, ' ') {|group| puts group }
=> [[1, 2],[3, " "]]
Passing false
to the fill_with
parameter inhibits the fill behavior.
>> %w(1 2 3).in_groups_of(2, false) {|group| puts group }
=> [[1, 2][3]]
The in_groups_of
method is particularly useful for batch-processing model objects and generating table rows in view templates.
split(value = nil, &block)
Divides an array into one or more subarrays based on a delimiting value:
[1, 2, 3, 4, 5].split(3) #=> [[1, 2], [4, 5]]
or the result of an optional block:
(1..8).to_a.split { |i|i%3==0}#=> [[1, 2], [4, 5], [7, 8]]
active_support/core_ext/array/random_access
A convenience method for accessing a random element of an array.
sample
Returns a random element from the array.
Efficiently grabbing a random record from the database is covered under the heading, Random Ordering in Chapter 5, Working with Active Record.
active_support/core_ext/array/uniq_by
Two convenience methods used for deriving unique elements of an array.
uniq_by
Returns an unique array based on the criteria given as a proc. Can be used when you need to enhance or decorate Ruby’s default uniq
behavior.
uniq_by!
Same behavior as uniq_by
but modifies the array in place.
active_support/core_ext/array/wrap
This is a convenience method added to the Array
class.
Array.wrap(object)
Wraps the object
in an Array
unless it’s an Array
. Converts the object to an Array using to_ary
if it implements that. It differs with Array()
in that it does not call to_a
on the argument:
active_support/core_ext/object/blank
blank?
Alias for empty?
active_support/core_ext/object/to_param
to_param
Calls to_param
on all of its elements and joins the result with slashes. This is used by the url_for
method in Action Pack.
ActiveSupport::BacktraceCleaner
active_support/backtrace_cleaner
Many backtraces include too much information that’s not relevant for the context. This makes it hard to find the signal in the backtrace and adds debugging time. With a custom BacktraceCleaner
, you can setup filters and silencers for your particular context, so only the relevant lines are included.
If you want to change the setting of Rails’s built-in BacktraceCleaner
, to show as much as possible, you can call BacktraceCleaner.remove_silencers!
in your console, specs or an application initializer. Also, if you need to reconfigure an existing BacktraceCleaner so that it does not filter or modify the paths of any lines of the backtrace, you can call BacktraceCleaner#remove_filters!
These two methods will give you a completely untouched backtrace.
Inspired by the Quiet Backtrace gem by Thoughtbot.
ActiveSupport::Base64
Base64 provides utility methods for encoding and de-coding binary data using a base 64 representation. A base 64 representation of binary data consists entirely of printable US-ASCII characters. The Base64 module is included in Ruby 1.8, but has been removed in Ruby 1.9. Active Support will use Ruby’s built-in Base64 library if it’s available.
active_support/base64
Base64.encode64(data)
Encodes a string to its base 64 representation. Each 60 characters of output is separated by a newline character.
Base64.encode64s(data)
Encodes the value as base64 without the newline breaks. This makes the base64 encoding readily usable as URL parameters or memcache keys without further processing.
Base64.decode64(data)
Decodes a base 64 encoded string to its original representation.
ActiveSupport::BasicObject
A class with no predefined methods that behaves similarly to Builder’s BlankSlate. Used for proxy classes and can come in handy when implementing domain-specific languages in your application code.
active_support/basic_object
The implementation of BasicObject
is an interesting and common Ruby idiom, so it’s reproduced here for your reference.
ActiveSupport::Benchmarkable
Benchmarkable
allows you to measure the execution time of a block in a template and records the result to the log.
active_support/benchmarkable
benchmark(message = "Benchmarking", options = {})
Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation. For example, let’s say you thought your file processing method was taking too long; you could wrap it in a benchmark block.
That would add an entry like “Process data files (345.2ms)” to the log, which can then be used to compare timings when optimizing your code.
You may give an optional logger level as the :level option. Valid options are :debug
, :info
, :warn
, and :error
. The default level is :info
.
Finally, you can pass true as the third argument to silence all log activity inside the block. This is great for boiling down a noisy block to just a single statement:
BigDecimal
active_support/core_ext/big_decimal/conversions
to_yaml
Emits the number without any scientific notation and without losing precision. Note that reconstituting YAML floats to native floats may lose precision.
active_support/json/encoding
A BigDecimal would be naturally represented as a JSON number. Most libraries, however, parse non-integer JSON numbers directly as floats. Clients using those libraries would get in general a wrong number and no way to recover other than manually inspecting the string with the JSON code itself.
That’s why a JSON string is returned. The JSON literal is not numeric, but if the other end knows by contract that the data is supposed to be a BigDecimal, it still has the chance to post-process the string and get the real value.
as_json
Returns self.to_s
.
ActiveSupport::BufferedLogger
The BufferedLogger
class is Rails’s built-in logger facility.
active_support/buffered_logger
The following levels are recognized by the logger, in order of increasing severity:
add(severity, msg)
The logger class uses meta-programming to wrap the add
method in convenience methods named after the severity levels.
auto_flushing=(period)
Sets the auto-flush period. Set to true
to flush after every log message, to an integer to flush every N messages, or to false
, nil
, or zero
to never auto-flush. If you turn auto-flushing off, be sure to regularly flush
the log yourself. Otherwise you will quickly eat up all available memory.
close
Flushes the logger and closes the log (if supported), then sets its internal log reference to nil
.
flush
Writes log messages buffered in memory to the log’s IO stream (generally your application’s log file.) Only needed when you turn auto-flushing off.
initialize(log, level = DEBUG)
You can change where the log is written by replacing the default logger in application.rb
.
Rails.logger = ActiveSupport::BufferedLogger.new("mylogger.txt")
It won’t work as expected in an initializer script, because the core frameworks are already loaded and have logger instances before the initializers.
The initializer
code is versatile and understands filenames, paths or any other type of IO
object, including $stdout
, which allows you to do the following cool hack in your console:
silence(temporary_level = ERROR)
Silences log items below the temporary_level
severity for the duration of the block. Assuming that you’re in a context, such as models or controllers, that have a logger
method, you can use the silence
method as follows:
logger.silence do
really_chatty_operation
end
In other contexts, grab a reference to the logger via the Rails.logger
method.
ActiveSupport::Cache::Store
This is an abstract cache store class. There are multiple cache store implementations, each having its own additional features. MemCacheStore
is currently the most popular cache store for large production websites.
Some implementations may not support all methods beyond the basic cache methods of fetch
, write
, read
, exist?
, and delete
.
ActiveSupport::Cache::Store
can store any serializable Ruby object.
Keys are always translated into strings and are case-sensitive.
>> cache.read("city") == cache.read(:city)
=> true
When an object is specified as a key, its cache_key
method will be called if it is defined. Otherwise, the to_param
method will be called.
Hashes and Arrays can also be used as keys. The elements will be delimited by slashes and hash elements will be sorted by key so they are consistent.
Nil values can be cached.
If your cache is on a shared infrastructure, you can define a namespace for your cache entries. If a namespace is defined, it will be prefixed on to every key. The namespace can be either a static value or a Proc. If it is a Proc, it will be invoked when each key is evaluated so that you can use application logic to invalidate keys.
All caches support auto expiring content after a specified number of seconds. To set the cache entry time to live, you can either specify :expires_in
as an option to the constructor to have it affect all entries or to the fetch
or write
methods for just one entry.
Caches can also store values in a compressed format to save space and reduce time spent sending data. Since there is some overhead, values must be large enough to warrant compression. To turn on compression either pass :compress => true
in the initializer or to fetch
or write
. To specify the threshold at which to compress values, set :compress_threshold
. The default threshold is 32K.
cleanup(options = nil)
Cleanup the cache by removing expired entries. Not all cache implementations may support this method. Options are passed to the underlying cache implementation.
clear(options = nil)
Clear the entire cache. Not all cache implementations may support this method. You should be careful with this method since it could affect other processes if you are using a shared cache. Options are passed to the underlying cache implementation.
decrement(name, amount = 1, options = nil)
Decrement an integer value in the cache. Options are passed to the underlying cache implementation.
delete(name, options = nil)
Delete an entry in the cache. Returns true
if there was an entry to delete. Options are passed to the underlying cache implementation.
delete_matched(matcher, options = nil)
Delete all entries whose keys match a pattern. Options are passed to the underlying cache implementation.
exist?(name, options = nil)
Return true
if the cache contains an entry with this name. Options are passed to the underlying cache implementation.
fetch(name, options = nil)
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned.
If there is no such data in the cache (a cache miss occurred), then nil
will be returned. However, if a block has been passed, then that block will be run in the event of a cache miss. The return value of the block will be written to the cache under the given cache key, and that return value will be returned.
You may also specify additional options via the options argument. Setting :force => true will force a cache miss:
cache.write("today", "Monday")
cache.fetch("today", :force => true) # => nil
Setting :compress
will store a large cache entry set by the call in a compressed format.
Setting :expires_in
will set an expiration time on the cache entry if it is set by call.
Setting :race_condition_ttl
will invoke logic on entries set with an :expires_in option
. If an entry is found in the cache that is expired and it has been expired for less than the number of seconds specified by this option and a block was passed to the method call, then the expiration future time of the entry in the cache will be updated to that many seconds in the and the block will be evaluated and written to the cache.
This is very useful in situations in which a cache entry is used very frequently under heavy load. The first process to find an expired cache entry will then become responsible for regenerating that entry while other processes continue to use the slightly out of date entry. This can prevent race conditions where too many processes are trying to regenerate the entry all at once. If the process regenerating the entry errors out, the entry will be regenerated after the specified number of seconds.
Other options will be handled by the specific cache store implementation. Internally, fetch calls read_entry
, and calls write_entry
on a cache miss. Options will be passed to the read and write calls.
For example, MemCacheStore’s write method supports the :raw
option, which tells the memcached server to store all values as strings. We can use this option with fetch
too:
increment(name, amount = 1, options = nil)
Increment an integer value in the cache. Options are passed to the underlying cache implementation.
options
Get the default options set when the cache was created.
read(name, options = nil)
Fetches data from the cache, using the given key. If there is data in the cache with the given key, then that data is returned. Otherwise, nil
is returned. Options are passed to the underlying cache implementation.
read_multi(*names)
Read multiple values at once from the cache. Options can be passed in the last argument. Some cache implementation may optimize this method.
Returns a hash mapping the names provided to the values found.
write(name, value, options = nil)
Writes the given value to the cache, with the given key.
You may also specify additional options via the options
argument. The specific cache store implementation will decide what to do with options.
ActiveSupport::Callbacks
Callbacks are hooks into the lifecycle of an object that allow you to trigger logic before or after an alteration of the object state. Mixing in this module allows you to define callbacks in your class.
For instance, assume you have the following code in your application:
Running the following code using
config = ConfigStorage.new
config.save
would output
saving...
- running save callbacks
saved
Note that callback defined on parent classes are inherited.
active_support/callbacks
The following methods are used to configure custom callbacks on your classes and are what Rails itself uses to create things such as before_filter
in Action Pack and before_save
in Active Record. Note that this is rather advanced functionality which you typically won’t need in your day-to-day Rails programming.
define_callbacks(*callbacks)
Defines callbacks types for your custom class.
module MyOwnORM
class Base
define_callbacks :validate
end
end
The following options determine the operation of the callback:
:terminator
Indicates when a before filter is considered to be halted.
define_callbacks :validate, :terminator => "result == false"
In the example above, if any before validate callbacks return false
, other callbacks are not executed. Defaults to false
.
:rescuable
By default, after filters are not executed if the given block or a before_filter
raises an error. Supply :rescuable => true
to change this behavior.
:scope
Specifies which methods should be executed when a class is given as callback.
before_filter MyFilter
Assuming the callback has been defined with a :kind
scope
define_callbacks :filters, :scope => [ :kind ]
then the method called will correspond to the type of the filter in the given class, which in this case, is before
.
The :scope
option can be supplied with multiple components, like this:
define_callbacks :validate, :scope => [ :kind, :name ]
A method named "#{kind}_#{name}"
will be invoked in the given class. So before_validate
will be called in the class below:
before_validate MyValidation
The :scope
option defaults to :kind
.
set_callback(name, *filter_list, &block)
Sets callbacks for a previously defined callback.
set_callback :save, :before, :before_method
set_callback :save, :after, :after_method, :if => :condition
set_callback :save, :around, lambda { |r| stuff; yield; stuff }
skip_callback(name, *filter_list, &block)
Skips a previously defined callback for a given type.
When creating or skipping callbacks, you can specify conditions that are always the same for a given key. For instance, ActionPack converts :only and :except conditions into per-key conditions.
before_filter :authenticate, :except => "index"
becomes
dispatch_callback :before, :authenticate, :per_key => {:unless => proc{|c| c.action_name == "index"}}
Per-Key conditions are evaluated only once per use of a given key. In the case of the above example, you would do:
run_callbacks(:dispatch, action_name) { ... dispatch stuff ... }
In that case, each action_name
would get its own compiled callback method that took into consideration the per_key
conditions. Introduction of this technique resulted in a large speed improvement for Action Pack.
Class
Rails extends Ruby’s Class
object with a number class methods that then become available on all other classes in the runtime, regardless of type.
active_support/core_ext/class/attribute
The following method allows for creation of attributes on Ruby classes.
class_attribute(*attrs)
Declares one or more class-level attributes whose value is inheritable and overwritable by subclasses and instances, like so:
This behavior matches normal Ruby method inheritance: Think of writing an attribute on a subclass as overriding the parent’s reader method. Instances may overwrite the class value in the same way. (Note that the following code samples create anonymous classes to illustrate usage in a more concise fashion.)
To opt out of the instance writer method, pass :instance_writer => false.klass = Class.new { class_attribute :setting, :instance_writer => false }
>> klass.new.setting
=> NoMethodError
The class_attribute
method also works with singleton classes, as can be seen in the following example.
klass = Class.new { class_attribute :setting }
>> klass.singleton_class.setting = "foo"
=> "foo"
For convenience, a query method is defined as well, which allows you to see if an attribute has been set on a particular class instance.
active_support/core_ext/class/attribute_accessors
This extends the class object with class and instance accessors for class attributes, just like the native attr*
accessors for instance attributes.
cattr_accessor(*syms)
Creates both reader and writer methods for supplied method names syms
.
cattr_reader(*syms)
Creates class and instance reader methods for supplied method names syms
.
cattr_writer(*syms)
Creates class and instance writer methods for supplied method names syms
.
active_support/core_ext/class/attribute_accessors
This extends the class object with class and instance accessors for class attributes, just like the native attr*
accessors for instance attributes.
active_support/core_ext/class/delegating_attributes
This is primarily for internal use by Rails.
superclass_delegating_accessors(name, options = {})
Generates class methods name
, name=
, and name?
. These methods dispatch to the private _name
, and _name=
methods, making them overridable by subclasses.
If an instances should be able to access the attribute then pass :instance_reader => true
in the options to generate a name
method accessible to instances.
active_support/core_ext/class/inheritable_attributes
This allows attributes to be shared within an inheritance hierarchy, but where each descendant gets a copy of their parents’ attributes, instead of just a pointer to the same. This means that the child can add elements to, for example, an array without those additions being shared with either their parent, siblings, or children, unlike the regular class-level attributes that are shared across the entire hierarchy.
The copies of inheritable parent attributes are added to subclasses when they are created, via the inherited
hook. All reader methods accept :instance_reader => true
option. All writer methods accept :instance_writer => true
option. Accessor methods accept both options.
Like many other obscure corners of Active Support, these methods are primarily for internal use by Rails itself and some of them are no longer used internally by Rails 3. They are included here primarily for completeness and on the off chance that they could be useful in advanced application code or in libraries that depend on Active Support.
class_inheritable_accessor(*syms)
Creates class inheritable attribute accessor(s).
class FormBuilder
class_inheritable_accessor :field_helpers
...
class_inheritable_array(*syms)
Creates class inheritable attribute(s) initialized to an empty array.
class_inheritable_hash(*syms)
Creates class inheritable attribute(s) initialized to an empty hash.
inheritable_attributes
Returns array of any class inheritable attributes that have been defined on a particular class instance.
reset_inheritable_attributes
Clears class inheritable attributes that have been defined on a particular class instance.
active_support/core_ext/class/subclasses
Provides methods that introspect the inheritance hierarchy of a class. Used extensively in Active Record.
subclasses
Returns an array with the names of the subclasses of self
as strings.
Integer.subclasses # => ["Bignum", "Fixnum"]
descendents
Returns an array of all class objects found that are subclasses of self
.
ActiveSupport::Concern
active_support/concern
The Concern
module is only 29 lines of Ruby code, but it helps drive some of the most elegant code improvements in Rails 3. Using it, you can make your code more modular and have less dependency problems than ever before.
You use Concern
to define common behavior that you want to mix into other application classes, or into Rails itself in the case of plugins.
A Concern
module has three elements: the included
block, ClassMethods
module, and InstanceMethods
module.
To use your custom Concern
module, just mix it into a class.
class Widget
include Foo
end
The included
block will be triggered at inclusion time. Methods in ClassMethods
will get added to Widget
as class methods. Methods in InstanceMethods
will get added to Widget
as instance methods.
See ActiveSupport::Configurable
for a good example of how Concern
is used internally by Rails.
ActiveSupport::Configurable
This Configurable
module is used internally by Rails to add configuration settings to AbstractController::Base
. You can use it yourself to add configuration to your classes.
active_support/configurable
The implementation of Configurable
is done as a Concern
that is mixed into other classes.
config_accessor(*names)
Creates configuration properties accessible via class and instance contexts. The names
parameter expects one or more symbols corresponding to property names.
Date
Active Support provides a wide array of extensions to Ruby’s built-in date and time classes to simplify conversion and calculation tasks in simple-to-understand language.
active_support/core_ext/date/acts_like
Duck-types as a Date-like class. See Object#acts_like?
for more explanation.
class Date
def acts_like_date?
true
end
end
active_support/core_ext/date/calculations
The following methods enable the use of calculations with Date
objects.
+(other) / -(other)
Rails extends the existing + and -
operator so that a since
calculation is performed when the other
argument is an instance of ActiveSupport::Duration
(the type of object returned by methods such as 10.minutes
and 9.months
).
>> Date.today + 1.day == Date.today.tomorrow
=> true
advance(options)
Provides precise Date
calculations for years, months, and days. The options
parameter takes a hash with any of these keys: :months
, :days
, :years
.
>> Date.new(2006, 2, 28) == Date.new(2005, 2, 28).advance(:years => 1)
=> true
ago(seconds)
Converts Date
to a Time
(or DateTime
if necessary) with the time portion set to the beginning of the day (0:00) and then subtracts the specified number of seconds.
>> Time.local(2005, 2, 20, 23, 59, 15) == Date.new(2005, 2, 21).ago(45)
=> true
at_beginning_of_day/at_midnight / beginning_of_day / midnight
Converts Date
to a Time
(or DateTime
if necessary) with the time portion set to the beginning of the day (0:00).
>> Time.local(2005,2,21,0,0,0) == Date.new(2005,2,21).beginning_of_day
=> true
at_beginning_of_month / beginning_of_month
Returns a new DateTime
representing the start of the month (1st of the month). Objects will have their time set to 0:00.
>> Date.new(2005, 2, 1) == Date.new(2005,2,21).beginning_of_month
=> true
at_beginning_of_quarter / beginning_of_quarter
Returns a new Date
/DateTime
representing the start of the calendar-based quarter (1st of January, April, July, and October). DateTime
objects will have their time set to 0:00.
>> Date.new(2005, 4, 1) == Date.new(2005, 6, 30).beginning_of_quarter
=> true
at_beginning_of_week / beginning_of_week monday
Returns a new Date
(or DateTime
) representing the beginning of the week. (Calculation is Monday-based.)
>> Date.new(2005, 1, 31) == Date.new(2005, 2, 4).beginning_of_week
=> true
at_beginning_of_year / beginning_of_year
Returns a new Date
/DateTime
representing the start of the calendar year (1st of January). DateTime
objects will have their time set to 0:00.
>> Date.new(2005, 1, 1) == Date.new(2005, 2, 22).beginning_of_year
=> true
at_end_of_month / end_of_month
Returns a new Date
/DateTime
representing the last day of the calendar month. DateTime
objects will have their time set to 23:59:59.
>> Date.new(2005, 3, 31) == Date.new(2005,3,20).end_of_month
=> true
change(options)
Returns a new Date
where one or more of the elements have been changed according to the options parameter.
The valid options are :year
, :month
, and :day
.
Date.current
This is the preferred way to get the current date when your Rails application is timezone-aware. Returns Time.zone.today
when config.time_zone
is set, otherwise just returns Date.today
.
end_of_day
Converts Date
to a Time
(or DateTime
if necessary) with the time portion set to the end of the day (23:59:59).
>> Time.local(2005,2,21,23,59,59) == Date.new(2005, 2, 21).end_of_day
=> true
in(seconds)since(seconds)
Converts Date
to a Time
(or DateTime
if necessary) with the time portion set to the beginning of the day (0:00) and then adds the specified number of seconds.
>> Time.local(2005, 2, 21, 0, 0, 45) == Date.new(2005, 2, 21).since(45)
=> true
last_month
Syntax sugar for months_ago(1)
.
last_year
Syntax sugar for years_ago(1)
.
months_ago(months)
Returns a new Date
(or DateTime
) representing the time a number of specified months ago.
>> Date.new(2005, 1, 1) == Date.new(2005, 3, 1).months_ago(2)
=> true
months_since(months)
Returns a new Date
(or DateTime
) representing the time a number of specified months into the past or the future. Supply a negative number of months to go back to the past.
>> Date.today.months_ago(1) == Date.today.months_since(-1)
=> true
next_month
Syntax sugar for months_since(1)
.
next_week(day = :monday)
Returns a new Date
(or DateTime
) representing the start of the given day in the following calendar week. Default day of the week may be overridden with a symbolized day name.
>> Date.new(2005, 3, 4) == Date.new(2005, 2, 22).next_week(:friday)
=> true
next_year
Syntax sugar for years_since(1)
.
Date.tomorrow
Convenience method that returns a new Date
(or DateTime
) representing the time one day in the future.
>> Date.new(2007, 3, 2) == Date.new(2007, 2, 28).tomorrow.tomorrow
=> true
years_ago(years)
Returns a new Date
(or DateTime
) representing the time a number of specified years ago.
>> Date.new(2000, 6, 5) == Date.new(2007, 6, 5).years_ago(7)
=> true
years_since(years)
Returns a new Date
(or DateTime
) representing the time a number of specified years into the future.
>> Date.new(2007, 6, 5) == Date.new(2006, 6, 5).years_since(1)
=> true
Date.yesterday
Convenience method that returns a new Date
(or DateTime
) representing the time one day ago.
>> Date.new(2007, 2, 21) == Date.new(2007, 2, 22).yesterday
=> true
active_support/core_ext/date/ conversions
The following methods facilitate the conversion of date data into various formats.
readable_inspect
Overrides the default inspect method with a human readable one.
>> Date.current
=> Wed, 02 Jun 2010
to_date
Used in order to keep Time
, Date
, and DateTime
objects interchangeable in conversions.
to_datetime
Converts a Date
object into a Ruby DateTime
object. The time is set to beginning of day.
to_formatted_s(format = :default)
Converts a Date
object into its string representation, according to the predefined formats in the DATE_FORMATS
constant. (Aliased as to_s
. Original to_s
is aliased as to_default_s
.)
The following hash of formats dictates the behavior of the to_s
method.
to_time(timezone = :local)
Converts a Date
object into a Ruby Time
object; time is set to beginning of day. The time zone can be :local
or :utc
.
>> Time.local(2005, 2, 21) == Date.new(2005, 2, 21).to_time
=> true
If the Date
object is a UTC time, Z is used as TZD. Otherwise [+-]hh:mm
is used to indicate the hours offset.
xmlschema
Returns a string that represents the time as defined by XML Schema (also known as iso8601):
CCYY-MM-DDThh:mm:ssTZD
active_support/core_ext/date/freeze
Date
memoizes some instance methods using metaprogramming to wrap the methods with one that caches the result in an instance variable.
If a Date
instance is frozen but the memoized method hasn’t been called, the first call will result in a frozen object error since the memo instance variable is uninitialized. The code in freeze.rb
works around the issue by eagerly memoizing before freezing.
Ruby 1.9 uses a preinitialized instance variable so it’s unaffected.
active_support/json/encoding
as_json
Returns self
as a JSON string. The ActiveSupport.use_standard_json_time_format
configuration setting determines whether the date string is delimited with dashes or not.
>> Date.today.as_json
=> "2010-06-03"
DateTime
The following methods extend Ruby’s built-in DateTime
class.
active_support/core_ext/date_time/acts_like
Duck-types as a DateTime-like class. See Object#acts_like?
for more explanation.
active_support/core_ext/date_time/calculations
The following methods permit easier use of DateTime
objects in date and time calculations.
<=> compare_with_coercion
Layers additional behavior on DateTime
so that Time
and ActiveSupport::TimeWithZone
instances can be compared with DateTime
instances.
at_beginning_of_day at_midnight beginning_of_day midnight
Convenience methods that all represent the start of a day (00:00). Implemented simply as change(:hour => 0)
.
advance(options)
Uses Date
to provide precise Time
calculations for years, months, and days. The options
parameter takes a hash with any of the keys :months
, :days
, and :years
.
ago(seconds)
Returns a new DateTime
representing the time a number of seconds ago. The opposite of since
.
change(options)
Returns a new DateTime
where one or more of the elements have been changed according to the options
parameter. The valid date options are :year
, :month
, :day
. The valid time options are :hour
, :min
, :sec
, :offset
, and :start
.
Date.current
Timezone-aware implementation of Time.now
returns a DateTime
instance.
end_of_day
Convenience method that represents the end of a day (23:59:59). Implemented simply as change(:hour => 23, :min => 59, :sec => 59)
.
future?
Tells whether the DateTime
is in the future.
Date.local_offset
DateTime
objects aren’t aware of DST rules, so use a consistent non-DST offset when creating a DateTime
with an offset in the local zone.
past?
Tells whether the DateTime
is in the past.
seconds_since_midnight
Returns how many seconds have passed since midnight.
since(seconds)
Returns a new DateTime
representing the time a number of seconds since the instance time. The opposite of ago
.
utc
Returns a new DateTime
with the offset
set to 0
to represent UTC time.
utc?
Convenience method returns true
if the offset
is set to 0
.
utc_offset
Returns the offset value in seconds.
active_support/core_ext/date_time/conversions
The following methods permit conversion of DateTime
objects (and some of their attributes) into other types of data.
Date.civil_from_format(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0)
Creates a datetime from the parameters provided. The utc_or_local
parameter recognizes :local
causing it to use the value of the local_offset
.
formatted_offset(colon = true, alternate_utc_string = nil)
Returns the utc_offset
as an HH:MM
formatted string.
datetime = DateTime.civil(2000, 1, 1, 0, 0, 0, Rational(-6, 24))
>> datetime.formatted_offset
=> "-06:00"
The options provide for tweaking the output of the method by doing things like ommitting the colon character.
>> datetime.formatted_offset(false)
=> "-0600"
readable_inspect
Overrides the default inspect method with a human-readable one that looks like this:
Mon, 21 Feb 2005 14:30:00 +0000
to_date
Converts self
to a Ruby Date
object, discarding time data.
to_datetime
Returns self
to be able to keep Time
, Date
, and DateTime
classes interchangeable on conversions.
to_f
Converts self to a floating-point number of seconds since the Unix epoch. Note the limitations of this methods with dates prior to 1970.
to_formatted_s(format=:default)
See the options on to_formatted_s
of the Time
class. The primary difference is the appending of the time information.
>> datetime.to_formatted_s(:db)
=> "2007-12-04 00:00:00"
to_i
Converts self to an integer number of seconds since the Unix epoch. Note the limitations of this methods with dates prior to 1970.
to_time
Attempts to convert self
to a Ruby Time
object. Returns self
if out of range of Ruby Time
class. If self.offset
is 0, will attempt to cast as a UTC time; otherwise, will attempt to cast in local timezone.
xmlschema
Converts datetime to an appropriate format for use in XML. The implementation is reproduced here for reference purposes:
strftime("%Y-%m-%dT%H:%M:%S%Z")
active_support/core_ext/date_time/zones
The following method allows conversion of a DateTime
into a different time zone.
in_time_zone(zone = ::Time.zone)
Returns the simultaneous time in Time.zone
>> Time.zone = 'Hawaii'
>> DateTime.new(2000).in_time_zone
=> Fri, 31 Dec 1999 14:00:00 HST -10:00
This method is similar to Time#localtime
, except that it uses the Time.zone
argument as the local zone instead of the operating system’s time zone. You can also pass it a string that identifies a TimeZone as an argument, and the conversion will be based on that zone instead. Allowable string parameters are operating-system dependent.
>> DateTime.new(2000).in_time_zone('Alaska')
=> Fri, 31 Dec 1999 15:00:00 AKST -09:00
active_support/json/encoding
as_json
Returns self
as a JSON string. The ActiveSupport.use_standard_json_time_format
configuration setting determines whether the output is formatted using :xmlschema
or the following pattern:
strftime('%Y/%m/%d %H:%M:%S %z')
ActiveSupport::Dependencies
This module contains the logic for Rails’ automatic classloading mechanism, which is what makes it possible to reference any constant in the Rails varied loadpaths without ever needing to issue a require
directive.
This module extends itself, a cool hack that you can use with modules that you want to use elsewhere in your codebase in a functional manner:
module Dependencies
extend self
...
As a result, you can call methods directly on the module constant, à la Java static class methods, like this:
>> ActiveSupport::Dependencies.search_for_file('person.rb')
=> "/Users/obie/work/tr3w_time_and_expenses/app/models/person.rb"
You shouldn’t need to use this module in day-to-day Rails coding—it’s mostly for internal use by Rails and plugins. On occasion, it might also be useful to understand the workings of this module when debugging tricky class-loading problems.
active_support/dependencies/autoload
Several of these attributes are set based on Configuration
settings declared in your various environment files, as described in Chapter 1, Rails Environments and Configuration.
autoloaded_constants
An array of qualified constant names that have been loaded. Adding a name to this array will cause it to be unloaded the next time. Dependencies
are cleared.
clear
Clears the list of currently loaded classes and removes unloadable constants.
constant_watch_stack
An internal stack used to record which constants are loaded by any block.
explicitly_unloadable_constants
An array of constant names that need to be unloaded on every request. Used to allow arbitrary constants to be marked for unloading.
history
The Set
of all files ever loaded.
load_once_paths
The Set
of directories from which automatically loaded constants are loaded only once. Usually consists of your plugin lib
directories. All directories in this set must also be present in load_paths
.
load_paths
The Set
of directories from which Rails may automatically load files. Files under these directories will be reloaded on each request in development mode, unless the directory also appears in load_once_paths
.
loaded
The Set
of all files currently loaded.
log_activity
Set this option to true
to enable logging of const_missing
and file loads. (Defaults to false
.)
mechanism
A setting that determines whether files are loaded (default) or required. This attribute determines whether Rails reloads classes per request, as in development mode.
>> ActiveSupport::Dependencies.mechanism
=> :load
warnings_on_first_load
A setting that determines whether Ruby warnings should be activated on the first load of dependent files. Defaults to true
.
associate_with(file_name)
Invokes depend_on
with swallow_load_errors
set to true
. Wrapped by the require_association
method of Object
.
autoload_module!(into, const_name, qualified_name, path_suffix)
Attempts to autoload the provided module name by searching for a directory matching the expected path suffix
. If found, the module is created and assigned to into
’s constants with the name +const_name+
. Provided that the directory was loaded from a reloadable base path, it is added to the set of constants that are to be unloaded.
autoloadable_module?(path_suffix)
Checks whether the provided path_suffix
corresponds to an autoloadable module. Instead of returning a Boolean, the autoload base for this module is returned.
autoloaded?(constant)
Determines if the specified constant
has been automatically loaded.
depend_on(file_name, swallow_load_errors = false)
Searches for the file_name
specified and uses require_or_load
to establish a new dependency. The swallow_load_errors
argument specifies whether LoadError
should be suppressed. Wrapped by the require_dependency
method of Object
.
load?
Returns true
if mechanism
is set to :load
.
load_file(path, const_paths = loadable_constants_for_path(path))
Loads the file at the specified path
. The const_paths
is a set of fully qualified constant names to load. When the file is loading, Dependencies
will watch for the addition of these constants. Each one that is defined will be marked as autoloaded, and will be removed when Dependencies.clear
is next called.
If the second parameter is left off, Dependencies
will construct a set of names that the file at path
may define. See loadable_constants_for_path
for more details.
load_once_path?(path)
Returns true
if the specified path
appears in the load_once_path
list.
load_missing_constant(mod, const_name)
Loads the constant named const_name
, which is missing from mod
. If it is not possible to load the constant from mod
, try its parent module by calling const_missing
on it.
loadable_constants_for_path(path, bases = load_paths)
Returns an array of constants, based on a specified filesystem path
to a Ruby file, which would cause Dependencies
to attempt to load the file.
mark_for_unload(constant)
Marks the specified constant
for unloading. The constant will be unloaded on each request, not just the next one.
new_constants_in(*descs, &block)
Runs the provided block and detects the new constants that were loaded during its execution. Constants may only be regarded as new once. If the block calls new_constants_in
again, the constants defined within the inner call will not be reported in this one.
If the provided block does not run to completion, and instead raises an exception, any new constants are regarded as being only partially defined and will be removed immediately.
qualified_const_defined?(path)
Returns true
if the provided constant path is defined?
qualified_name_for(parent_module, constant_name)
Returns a qualified path for the specified parent_module
and constant_name
.
remove_unloadable_constants!
Removes the constants that have been autoloaded, and those that have been marked for unloading.
require_or_load(file_name, const_path = nil)
Implements the main classloading mechanism. Wrapped by the require_or_load
method of Object
.
search_for_file(path_suffix)
Searches for a file in load_paths
matching the provided path_suffix
.
will_unload?(constant)
Returns true
if the specified constant is queued for unloading on the next request.
ActiveSupport::Deprecation
The deprecate method provides Rails core and application developers with a formal mechanism to be able to explicitly state what methods are deprecated. (Deprecation means to mark for future deletion.) Rails will helpfully log a warning message when deprecated methods are called.
Deprecation.deprecate_methods(target_module, *method_names)
Pass the module and name(s) of the methods as symbols to deprecate.
Deprecation.silence(&block)
Silence deprecation warnings within the block.
ActiveSupport::Duration
Provides accurate date and time measurements using the advance
method of Date
and Time
. It mainly supports the methods on Numeric
, such as in this example:
1.month.ago # equivalent to Time.now.advance(:months => -1)
active_support/duration
+ (other)
Adds another Duration
or a Numeric
to this Duration
. Numeric
values are treated as seconds.
>> 2.hours + 2
=> 7202 seconds
- (other)
Subtracts another Duration
or a Numeric
to this Duration
. Numeric
values are treated as seconds.
>> 2.hours - 2
=> 7198 seconds
ago(time = Time.now)
Calculates a new Time
or Date
that is as far in the past as this Duration
represents.
>> birth = 35.years.ago
=> Mon, 21 Apr 1975 00:48:43 UTC +00:00
from_now(time = Time.now)
Alias for since
, which reads a little bit more naturally when using the default Time.now
as the time
argument.
>> expiration = 1.year.from_now
=> Thu, 21 Apr 2011 00:51:48 UTC +00:00
inspect
Calculates the time resulting from a Duration
expression and formats it as a string appropriate for display in the console. (Remember that IRB and the Rails console automatically invoke inspect
on objects returned to them. You can use that trick with your own objects.)
>> 10.years.ago
=> Sun Aug 31 17:34:15 -0400 1997
since(time = Time.now)
Calculates a new Time
or Date
that is as far in the future as this Duration
represents.
>> expiration = 1.year.since(account.created_at)
until(time = Time.now)
Alias for ago
. Reads a little more naturally when specifying a time
argument instead of using the default value, Time.now
.
>> membership_duration = created_at.until(expires_at)
Enumerable
Extensions to Ruby’s built-in Enumerable
module, which gives arrays and other types of collections iteration abilities.
active_support/core_ext/enumerable
The following methods are added to all Enumerable
objects.
each_with_object(memo, &block)
Iterates over a collection, passing the current element and the memo
to the block. Handy for building up hashes or reducing collections down to one object. Examples:
>> %w(foo bar).each_with_object({}) { |str, hsh| hsh[str] = str.upcase }
=> {'foo' => 'FOO', 'bar' => 'BAR'}
Note: that you can’t use immutable objects (like numbers
, true
, false
, etc) as the memo
argument. You would think the following returns 120, but since the memo is never changed, it does not.
(1..5).each_with_object(1) }value, memo} memo *= value # => 1
group_by(&block)
Collects an enumerable into sets, grouped by the result of a block and ordered. Useful, for example, for grouping records by date like in the following example:
Rubys own group_by
method is used in versions 1.9 and above.
index_by
Converts an enumerable to a hash, based on a block that identifies the keys. The most common usage is with a single attribute name:
>> people.index_by(&:login)
=> { "nextangle" => <Person ...>, "chad" => <Person ...>}
Use full block syntax (instead of the to_proc
hack) to generate more complex keys:
>> people.index_by { |p| "#{p.first_name} #{p.last_name}" }
=> {"Chad Fowler" => <Person ...>, "David Hansson" => <Person ...>}
sum(default = 0, &block)
Calculates a sum from the elements of an enumerable, based on a block.
payments.sum(&:price)
Its easier to understand than Rubys clumsier inject method:
payments.inject { |sum, p| sum + p.price }
Use full block syntax (instead of the to_proc
hack) to do more complicated calculations:
payments.sum { |p| p.price * p.tax_rate }
Also, sum
can calculate results without the use of a block:
[5, 15, 10].sum # => 30
The default identity (a fancy way of saying, “the sum of an empty list”) is 0
. However, you can override it with anything you want by passing a default
argument:
[].sum(10) { |i| i.amount}#=>10
index_by
Converts an enumerable to a hash, based on a block that identifies the keys. The most common usage is with a single attribute name:
>> people.index_by(&:login)
=> { "nextangle" => <Person ...>, "chad" => <Person ...>}
Use full block syntax (instead of the to_proc
hack) to generate more complex keys:
>> people.index_by { |p| "#{p.first_name} #{p.last_name}" }
=> {"Chad Fowler" => <Person ...>, "David Hansson" => <Person ...>}
active_support/json/encoding
as_json
Returns self.to_a
.
ERB::Util
active_support/core_ext/string/output_safety
html_escape(s)
A utility method for escaping HTML tag characters. This method is also aliased as h
.
In your templates, use this method to escape any unsafe (often, anything user-submitted) content, like this:
=h @person.name
The method primarily escapes angle brackets and ampersands.
>> puts html_escape("is a > 0 & a < 10?")
=> is a > 0 & a < 10?
json_escape(s)
A utility method for escaping HTML entities in JSON strings. This method is also aliased as j
.
In your ERb templates, use this method to escape any HTML entities:
=j @person.to_json
The method primarily escapes angle brackets and ampersands.
puts json_escape("is a > 0 & a < 10?")
=> is a u003E 0 u0026 a u003C 10?
FalseClass
active_support/core_ext/object/blank
blank?
Returns true
.
active_support/json/encoding
as_json
Returns "false"
.
File
active_support/core_ext/file/atomic
Provides an atomic_write
method to Ruby’s File
class.
atomic_write(file_name, temp_dir = Dir.tmpdir)
Writes to a file atomically, by writing to a temp file first and then renaming to the target file_name
. Useful for situations where you need to absolutely prevent other processes or threads from seeing half-written files.
File.atomic_write("important.file") do |file|
file.write("hello")
end
If your temp
directory is not on the same filesystem as the file you’re trying to write, you can provide a different temporary directory with the temp_dir
argument.
File.atomic_write("/data/something.imporant", "/data/tmp") do |f|
file.write("hello")
end
active_support/core_ext/file/path
Ensures that to_path
is aliased to path
.
Float
active_support/core_ext/float/rounding
Provides an round
method to Ruby’s Float
class that accepts an optional precision
parameter.
round(precision = nil)
Rounds the float with the specified precision.
>> x = 1.337
>> x.round
=> 1
>> x.round(1)
=> 1.3
>> x.round(2)
=> 1.34
Hash
active_support/core_ext/hash/conversions
Contains code that adds the ability to convert hashes to and from xml.
Hash.from_xml(xml)
Parses arbitrary strings of XML markup into nested Ruby arrays and hashes. Works great for quick-and-dirty integration of REST-style web services.
Here’s a quick example in the console with some random XML content. The XML only has to be well-formed markup.
Now you can easily access the data from the XML:
>> h["people"]["person"].first["name"]["given"] => "Big"
to_xml(options={})
Collects the keys and values of a hash and composes a simple XML representation.
active_support/core_ext/hash/deep_merge
deep_merge(other_hash)
Returns a new hash with self
and other_hash
merged recursively.
deep_merge!(other_hash)
Modifies self
by merging in other_hash
recursively.
active_support/core_ext/hash/diff
diff(hash2)
A method for getting the difference between one hash and another. Returns the difference between a hash and the one passed in as a parameter.
A quick example in the console:
active_support/core_ext/hash/except
except(*keys)
Returns a hash that includes everything but the given keys
. This is useful for limiting a set of parameters to everything but a few known toggles.
person.update_attributes(params[:person].except(:admin))
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.
except!(*keys)
Replaces the hash without the given keys.
active_support/core_ext/hash/indifferent_access
with_indifferent_access
Returns an ActiveSupport::HashWithIndifferentAccess
out of its receiver.
>> {:a => 1}.with_indifferent_access["a"]
=> 1
active_support/core_ext/hash/keys
Provides methods that operate on the keys of a hash. The stringify
and symbolize
methods are used liberally throughout the Rails codebase, which is why it generally doesn’t matter if you pass option names as strings or symbols.
You can use assert_valid_keys
method in your own application code, which takes Rails-style option hashes.
assert_valid_keys(*valid_keys)
Raises an ArgumentError
if the hash contains any keys not specified in valid_keys
.
def my_method(some_value, options={})
options.assert_valid_keys(:my_conditions, :my_order, ...)
...
end
Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols as keys, this will fail.
stringify_keys
Returns a new copy of the hash with all keys converted to strings.
stringify_keys!
Destructively converts all keys in the hash to strings.
symbolize_keys and to_options
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
.
symbolize_keys! and to_options!
Destructively converts all keys in the hash to symbols.
active_support/core_ext/hash/reverse_merge
Allows for reverse merging where the keys in the calling hash take precedence over those in the other_hash
. This is particularly useful for initializing an incoming option hash with default values like this:
In the example, the default :size
and :velocity
are only set if the options passed in don’t already have those keys set.
reverse_merge(other_hash)
Returns a merged version of two hashes, using key values in the other_hash
as defaults, leaving the original hash unmodified.
reverse_merge!(other_hash) and reverse_update
Destructive versions of reverse_merge
; both modify the original hash in place.
active_support/core_ext/hash/slice
slice(*keys)
Slices a hash to include only the given keys. This is useful for limiting an options hash to valid keys before passing to a method:
If you have an array of keys you want to limit to, you should splat them:
valid_keys = [:mass, :velocity, :time]
search(options.slice(*valid_keys))
slice!(*keys)
Replaces the hash with only the given keys.
>> {:a => 1, :b => 2, :c => 3, :d => 4}.slice!(:a, :b)
=> {:c => 3, :d =>4}
active_support/core_ext/object/to_param
to_param(namespace = nil)
Converts a hash into a string suitable for use as a URL query string. An optional namespace
can be passed to enclose the param names (see example below).
active_support/core_ext/object/to_query
to_query
Collects the keys and values of a hash and composes a URL-style query string using ampersand and equal-sign characters.
>> {:foo => "hello", :bar => "goodbye"}.to_query
=> "bar=goodbye&foo=hello"
active_support/json/encoding
as_json
Returns self
as a string of JSON.
active_support/core_ext/object/blank
blank?
Alias for empty?
HashWithIndifferentAccess
A subclass of Hash
used internally by Rails.
active_support/hash_with_indifferent_access
As stated in the source file:
This class has dubious semantics and we only have it so that people can write
params[:key]
instead ofparams['key'].
ActiveSupport::Inflector::Inflections
The Inflections
class transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys.
The default inflections for pluralization, singularization, and uncountable words are kept in activesupport/lib/active_support/inflections.rb
and reproduced here for reference.
A singleton instance of Inflections
is yielded by Inflector.inflections
, which can then be used to specify additional inflection rules in an initializer.
New rules are added at the top. So in the example, the irregular rule for octopus will now be the first of the pluralization and singularization rules that are checked when an inflection happens. That way Rails can guarantee that your rules run before any of the rules that may already have been loaded.
active_support/inflector/inflections
This API reference lists the inflections methods themselves in the modules where they are actually used: Numeric
and String
. The Inflections
module contains methods used for modifying the rules used by the inflector.
clear(scope = :all))
Clears the loaded inflections within a given scope
. Give the scope
as a symbol of the inflection type: :plurals
, :singulars
, :uncountables
, or :humans
.
ActiveSupport::Inflector.inflections.clear
ActiveSupport::Inflector.inflections.clear(:plurals)
human(rule, replacement)
Specifies a humanized form of a string by a regular expression rule or by a string mapping. When using a regular expression based replacement, the normal humanize formatting is called after the replacement. When a string is used, the human form should be specified as desired (example: “The name”, not “the_name”)
ActiveSupport::Inflector.inflections do |inflect|
inflect.human /_cnt$/i, '1_count'
inflect.human "legacy_col_person_name", "Name"
end
inflections
Yields a singleton instance of ActiveSupport::Inflector::Inflections
so you can specify additional inflector rules.
ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable "rails"
end
irregular(singular, plural)
Specifies a new irregular that applies to both pluralization and singularization at the same time. The singular
and plural
arguments must be strings, not regular expressions. Simply pass the irregular word in singular and plural form.
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'octopus', 'octopi'
inflect.irregular 'person', 'people'
end
plural(rule, replacement)
Specifies a new pluralization rule and its replacement. The rule
can either be a string or a regular expression. The replacement
should always be a string and may include references to the matched data from the rule by using backslash-number syntax, like this:
ActiveSupport::Inflector.inflections do |inflect|
inflect.plural /^(ox)$/i, '1en'
end
singular(rule, replacement)
Specifies a new singularization rule and its replacement. The rule
can either be a string or a regular expression. The replacement
should always be a string and may include references to the matched data from the rule by using backslash-number syntax, like this:
uncountable(*words)
Adds uncountable words that should not be inflected to the list of inflection rules.
active_support/inflector/transliteration
transliterate(string, replacement = "?")
Replaces non-ASCII characters with an ASCII approximation, or if none exists, a replacement character which defaults to “?”.
transliterate("øørskbing")
# => "AEroskobing"
Default approximations are provided for Western/Latin characters, e.g, “ø”, “ñ”, “é”, “ß”, etc.
This method is I18n aware, so you can set up custom approximations for a locale. This can be useful, for example, to transliterate German’s “ü” and “ö” to “ue” and “oe”, or to add support for transliterating Russian to ASCII.
In order to make your custom transliterations available, you must set them as the <tt>i18n.transliterate.rule</tt> i18n key:
The value for <tt>i18n.transliterate.rule</tt> can be a simple Hash that maps characters to ASCII approximations as shown above, or, for more complex requirements, a Proc:
Now you can have different transliterations for each locale:
parameterize(string, sep = '-')
Replaces special characters in a string so that it may be used as part of a “pretty” URL. This method replaces accented characters with their ASCII equivalents and discards all other non-ASCII characters by turning them into the string specified as sep
. The method is smart enough to not double up separators. Leading and trailing separators are also removed.
Integer
Extensions to Ruby’s built-in Integer
class.
active_support/core_ext/integer/inflections
ordinalize
Turns an integer into an ordinal string used to denote the position in an ordered sequence such as 1st, 2nd, 3rd, 4th.
active_support/core_ext/integer/multiple
multiple_of?(number)
Returns true
if the integer is a multiple of number
.
9.multiple_of?3#=> true
ActiveSupport::JSON
Rails includes support for three JSON (JavaScript Object Notation) backends:
• JSONGem (json)
• Yajl (yajl-ruby)
• Yaml
The JSON
module adds JSON decoding and encoding support to Rails.
active_support/json/decoding
backend
Returns the selected JSON backend.
backend=(name)
Sets desired JSON backend.
decode(json)
Parses a JSON string or IO
object and converts it into an object graph.
with_backend(name, &block)
Use an alternate JSON backend within the supplied block
.
active_support/json/encoding
encode(value, options = nil)
Dumps object in JSON.
>> ActiveSupport::JSON.encode({:a => 1, :b => 2})
=> "{"a":1,"b":2}"
Kernel
Methods added to Ruby’s Kernel
class are available in all contexts.
active_support/core_ext/kernel/agnostics
'(command)
Makes backticks behave (somewhat more) similarly on all platforms. On win32 `nonexistent_command`
raises Errno::ENOENT
, but on Unix, the spawned shell prints a message to stderr and sets $?
.
active_support/core_ext/kernel/debugger
debugger
Starts a debugging session if ruby-debug
has been loaded. Use rails server --debugger
to start Rails with the debugger enabled.
active_support/core_ext/kernel/reporting
enable_warnings
Sets $VERBOSE
to true for the duration of the block provided and back to its original value afterward.
silence_stream(stream)
Silences any stream for the duration of the block provided.
silence_stream(STDOUT) do
puts 'This will never be seen'
end
puts 'But this will'
silence_warnings
Sets $VERBOSE
to false for the duration of the block provided and back to its original value afterward.
suppress(*exception_classes)
Amethod that should be named swallow. Suppresses raising of any exception classes specified inside of the block provided. Use with caution.
active_support/core_ext/kernel/requires
require_library_or_gem
Requires a library with fallback to RubyGems. Warnings during library loading are silenced to increase signal/noise for application warnings.
active_support/core_ext/kernel/singleton_class
class_eval
Forces class_eval
to behave like singleton_class.class_eval
.
singleton_class
Returns the object’s singleton class.
Logger
This section includes extensions to the built-in Ruby logger, accessible via the logger
property in various Rails contexts such as Active Record models and controller classes. Always accessible via Rails.logger
. Use of the logger is explained in Chapter 1.
To use the default log formatter as defined in the Ruby core, you need to set a formatter for the logger as in the following example:
logger.formatter = Formatter.new
You can then specify properties such as the datetime format, for example:
logger.datetime_format = "%Y-%m-%d"
active_support/core_ext/logger
around_debug(start_message, end_message) ...
Streamlines the all-too-common pattern of wrapping a few lines of code in comments that indicate the beginning and end of a routine, as follows:
The same code would be written with around_debug
like this:
around_error, around_fatal, and around_info
See as around_debug
except with a different log-level.
datetime_format
Gets the current logging datetime format. Returns nil
if the formatter does not support datetime formatting.
datetime_format=(datetime_format)
Sets the format string passed to strftime
to generate the log’s timestamp string.
formatter
Gets the current formatter. The Rails default formatter is a SimpleFormatter
, which only displays the log message.
silence(temporary_level = Logger::ERROR)
Silences the logger for the duration of a block provided.
ActiveSupport::MessageEncryptor
MessageEncryptor
is a simple way to encrypt values that get stored somewhere you don’t trust.
The cipher text and initialization vector are base64 encoded and returned to you.
This can be used in situations similar to the MessageVerifier
, but where you don’t want users to be able to determine the value of the payload.
active_support/message_encryptor
initialize(secret, cipher = 'aes-256-cbc')
Creates a new instance of MessageEncryptor
.
encrypt(value)
Encrypts value
.
decrypt(encrypted_messages)
Decrypts encrypted_message
.
ActiveSupport::MessageVerifier
MessageVerifier
makes it easy to generate and verify signed messages to prevent tampering.
This is useful for cases like remember-me tokens and auto-unsubscribe links where the session store isn’t suitable or available.
active_support/message_verifier
initialize(secret, digest = 'SHA1')
Creates a new MessageVerifier
with the supplied secret
string and digest
.
generate(value)
Generate a signed message.
cookies[:remember_me] = verifier.generate([user.id, 2.weeks.from_now])
verify(signed_message)
Verify a signed message.
Module
This section covers extensions to Ruby’s Module
class, available in all contexts.
active_support/core_ext/module/aliasing
alias_attribute(new_name, old_name)
This super-useful method allows you to easily make aliases for attributes, including their reader, writer, and query methods.
In the following example, the Content
class is serving as the base class for Email
using STI, but e-mails should have a subject, not a title:
As a result of the alias_attribute
, you can see in the following example that the title
and subject
attributes become interchangeable:
alias_method_chain(target, feature)
Encapsulates the following common pattern:
alias_method :foo_without_feature, :foo
alias_method :foo, :foo_with_feature
With alias_method_chain
, you simply do one line of code and both aliases are set up for you:
alias_method_chain :foo, :feature
Query and bang methods keep the same punctuation. The following syntax
alias_method_chain :foo?, :feature
is equivalent to
alias_method :foo_without_feature?, :foo?
alias_method :foo?, :foo_with_feature?
so you can safely chain foo
, foo?
, and foo!
.
active_support/core_ext/module/anonymous
anonymous?
Returns true
if self
does not have a name.
A module gets a name when it is first assigned to a constant. Either via the module
or class
keyword
or by an explicit assignment
active_support/core_ext/module/attr_accessor_with_default
attr_accessor_with_default (sym, default = nil, &block)
Declares an attribute accessor with an initial default return value.
To give attribute :age
the initial value 25
, you would write the following:
class Person
attr_accessor_with_default :age, 25
end
To give attribute :element_name
a dynamic default value, evaluated in scope of self, you would write
attr_accessor_with_default(:element_name) { name.underscore }
active_support/core_ext/module/attr_internal
attr_internal
Alias for attr_internal_accessor
.
attr_internal_accessor(*attrs)
Declares attributes backed by internal instance variables names (using an @_
naming convention). Basically just a mechanism to enhance controlled access to sensitive attributes.
For instance, Object
’s copy_instance_variables_from
will not copy internal instance variables.
attr_internal_reader(*attrs)
Declares an attribute reader backed by an internally named instance variable.
attr_internal_writer(*attrs)
Declares an attribute writer backed by an internally named instance variable.
active_support/core_ext/module/attribute_accessors
mattr_accessor(*syms)
Defines one or more module attribute reader and writer methods in the style of the native attr*
accessors for instance attributes.
mattr_reader(*syms)
Defines one or more module attribute reader methods.
mattr_writer(*syms)
Defines one or more module attribute writer methods.
active_support/core_ext/module/delegation
delegate(*methods)
Provides a delegate class method to easily expose contained objects’ methods as your own. Pass one or more methods (specified as symbols or strings) and the name of the target object via the :to
option (also a symbol or string). At least one method name and the :to
option are required.
Delegation is particularly useful with Active Record associations:
Multiple delegates to the same target are allowed:
Methods can be delegated to instance variables, class variables, or constants by providing them as a symbols:
Delegates can optionally be prefixed using the :prefix
option. If the value is true
, the delegate methods are prefixed with the name of the object being delegated to.
It is also possible to supply a custom prefix.
If the delegate object is nil
an exception is raised, and that happens no matter whether nil
responds to the delegated method. You can get a nil
instead with the :allow_nil
option.
active_support/core_ext/module/introspection
local_constants
Returns the constants that have been defined locally by this object and not in an ancestor. This method is exact if running under Ruby 1.9. In previous versions it may miss some constants if their definition in some ancestor is identical to their definition in the receiver.
local_constant_names
Returns the names of the constants defined locally rather than the constants themselves.
parent
Returns the module that contains this one; if this is a root module, such as ::MyModule, then Object
is returned.
>> ActiveRecord::Validations.parent
=> ActiveRecord
parent_name
Returns the name of the module containing this one.
>> ActiveRecord::Validations.parent_name
=> "ActiveRecord"
parents
Returns all the parents of this module according to its name, ordered from nested outwards. The receiver is not contained within the result.
active_support/core_ext/module/synchronization
synchronize(*methods)
Synchronizes access around a method, delegating synchronization to a particular mutex. A mutex (either a Mutex
, or any object that responds to synchronize
and yields to a block) must be provided together with a :with
option. The :with
option should be a symbol or string, and can represent a method, constant, or instance or class variable.
It is used internally by Rails in various places including database connection pooling, the buffered logger, and generation of asset timestamps.
active_support/dependencies
const_missing(class_id)
The const_missing
callback is invoked when Ruby can’t find a specified constant in the current scope, which is what makes Rails autoclassloading possible. See the Dependencies
module for more detail.
ActiveSupport::Multibyte::Chars
The chars
proxy enables you to work transparently with multibyte encodings in the Ruby String
class without having extensive knowledge about encoding.
active_support/multibyte/chars
A Chars
object accepts a string upon initialization and proxies String
methods in an encoding-safe manner. All the normal String
methods are proxied through the Chars
object, and can be accessed through the mb_chars
method. Methods that would normally return a String
object now return a Chars
object so that methods can be chained together safely.
>> "The Perfect String".mb_chars.downcase.strip.normalize
=> "the perfect string"
Chars
objects are perfectly interchangeable with String
objects as long as no explicit class checks are made. If certain methods do explicitly check the class, call to_s
before you pass Chars
objects to them, to go back to a normal String
object:
bad.explicit_checking_method("T".chars.downcase.to_s)
The default Chars
implementation assumes that the encoding of the string is UTF-8. If you want to handle different encodings, you can write your own multibyte string handler and configure it through ActiveSupport::Multibyte.proxy_class
Note that a few methods are defined on Chars
instead of the handler because they are defined on Object
or Kernel
and method_missing
(the method used for delegation) can’t catch them.
<=> (other)
Returns –1, 0, or +1 depending on whether the Chars
object is to be sorted before, equal to, or after the object on the right side of the operation. In other words, it works exactly as you would expect it to.
handler
Returns the proper handler for the contained string depending on $KCODE
and the encoding of the string. This method is used internally by Rails to always redirect messages to the proper classes depending on the context.
method_missing(m, *a, & b)
Tries to forward all undefined methods to the designated handler. When a method is not defined on the handler, it sends it to the contained string instead. Also responsible for making the bang (!
) methods destructive, since a handler doesn’t have access to change an enclosed string instance.
split(*args)
Works just like the normal String
’s split
method, with the exception that the items in the resulting list are Chars
instances instead of String
, which makes chaining calls easier.
tidy_bytes(force = false)
Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.
Passing true
will forcibly tidy all bytes, assuming that the string’s encoding is entirely CP1252 or ISO-8859-1.
active_support/multibyte/unicode
Contains methods handling Unicode strings.
Unicode.compose_codepoints(codepoints)
Composes decomposed characters to the composed form.
Unicode.decompose_codepoints(type, codepoints)
Decomposes composed characters to the decomposed form. The type
argument accepts :canonical
or :compatability
.
Unicode.g_pack(string)
Reverses operation of g_unpack
Unicode.g_unpack(string)
Unpacks the string at grapheme boundaries. Returns a list of character lists.
Unicode.in_char_class?(codepoint, classes)
Detects whether the codepoint is in a certain character class. Returns true
when it’s in the specified character class and false
otherwise. Valid character classes are: :cr
, :lf
, :l
, :v
, :lv
, :lvt
and :t
.
Primarily used by grapheme cluster support.1
Unicode.normalize(string, form = nil)
Returns the KC normalization of the string by default. NFKC is considered the best normalization form for passing strings to databases and validations. The form
specifies the form you want to normalize in and should be one of the following: :c
, :kc
, :d
, or :kd
. Default is form is stored in the ActiveSupport::Multibyte.default_normalization_form
attribute and is overridable in an initializer.
Unicode.reorder_characters(codepoints)
Re-orders codepoints so the string becomes canonical.
Unicode.u_unpack(string)
Unpacks the string at codepoints boundaries. Raises an EncodingError
when the encoding of the string isn’t valid UTF-8.
>> Unicode.u_unpack('Café')
=> [67, 97, 102, 233]
active_support/multibyte/utils
Contains methods for verifying the encoding of character strings.
Multibyte.verify(string)
Verifies the encoding of a string. Splits the string on character boundaries, which are determined based on $KCODE
.
>> ActiveSupport::Multibyte.verify("obie")
=> true
Multibyte.verify!(string)
Verifies the encoding of a string. Splits the string on character boundaries, which are determined based on $KCODE
. Raises an exception if it’s not valid.
NilClass
Remembers that everything in Ruby is an object, even nil
, which is a special reference to a singleton instance of the NilClass
.
active_support/core_ext/object/blank
blank?
Returns true
.
active_support/json/encoding
as_json
Returns "null"
.
active_support/whiny_nil
Besides blank?
, the extensions to nil
try to raise more descriptive error messages, to help Rails newbies. The aim is to ensure that when developers pass nil
to methods unintentionally, instead of NoMethodError
and the name of some method used by the framework, they’ll see a message explaining what type of object was expected. The behavior was named “whiny nil” as an inside joke.
Method missing magic is used to capture the method that was erroneously invoked on nil
. The method name is looked up in a hash containing method names indexed to Rails classes, so that a helpful suggestion can be attempted.
If you’ve done any amount of Rails programming, you’re probably familiar with the output of this error-helping process, as the description of a NoMethodError
:
You have a nil object when you didn’t expect it! You might have expected an instance of class_name. The error occurred while evaluating nil.method_name.
The whiny nil
behavior can be controlled in the individual environment configurations with the following line:
config.whiny_nils = true
Rails has it set to true
by default in development and test modes, and false
in production mode.
NilClass.add_whiner(klass)
Specifies that klass
should have whiny nil behavior. Active Support adds Array
by default.
id
Raises a message along the lines of: Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
.
ActiveSupport::Notifications
Notifications provides an instrumentation API for Ruby. To instrument an action in Ruby you just need to do:
You can consume those events and the information they provide by registering a log subscriber. For instance, let’s store all instrumented events in an array:
When subscribing to Notifications
, you can pass a pattern, to only consume events that match the pattern:
Notifications ships with a queue implementation that consumes and publish events to log subscribers in a thread. You can use any queue implementation you want.
Numeric
Extensions to Ruby’s Numeric
class.
active_support/core_ext/object/blank
blank?
Returns false
.
active_support/json/encoding
as_json
Returns self
.
encode_json
Returns self.to_s
.
active_support/numeric/bytes
Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes
.
The following constants are defined in bytes.rb
.
byte / bytes
Returns the value of self
. Enables the use of byte calculations and declarations, like 45.bytes
+ 2.6.megabytes
.
kilobyte / kilobytes
Returns self * 1024
.
megabyte / megabytes
Returns self * 1024.kilobytes
.
gigabyte / gigabytes
Returns self * 1024.megabytes
.
terabyte / terabytes
Returns self * 1024.gigabytes
.
petabyte / petabytes
Returns self * 1024.terabytes
.
exabyte / exabytes
Returns self * 1024.petabytes
.
active_support/numeric/time
Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years
.
These methods use Time#advance
for precise date calculations when using from_now
, ago
, etc. as well as adding or subtracting their results from a Time
object. For example:
While these methods provide precise calculation when used as in the examples above, care should be taken to note that this is not true if the result of ‘months’, ‘years’, etc is converted before use:
In such cases, Ruby’s core Date
and Time
should be used for precision date and time arithmetic.
ago and until
Appends to a numeric time value to express a moment in the past.
10.minutes.ago
day / days
A duration equivalent to self * 24.hours
.
fortnight / fortnights
A duration equivalent to self * 2.weeks
.
from_now(time = Time.now) / since(time = Time.now)
An amount of time in the future, from a specified time (which defaults to Time.now
).
hour / hours
A duration equivalent to self * 3600.seconds
.
minute / minutes
A duration equivalent to self * 60.seconds
.
month / months
A duration equivalent to self * 30.days
.
second / seconds
A duration in seconds equal to self
.
week / weeks
A duration equivalent to self * 7.days
.
year / years
A duration equivalent to self * 365.25.days
.
Object
Rails mixes quite a few methods into the Object
class, meaning they are available via every other object at runtime.
active_support/core_ext/object/acts_like
acts_like?(duck)
A duck-type assistant method. For example, Active Support extends Date
to define an acts_like_date?
method, and extends Time
to define acts_like_time?
. As a result, we can do “x.acts_like?(:time)” and “x.acts_like?(:date)” to do duck-type-safe comparisons, since classes that we want to act like Time simply need to define an acts_like_time?
method.
active_support/core_ext/object/blank
blank?
An object is blank if it’s false
, empty, or a whitespace string. For example, “”, “ ”, nil
, []
, and {}
are blank.
This simplifies:
if !address.nil? && !address.empty?
to
unless address.blank?
presence
Returns object if it’s present?
otherwise returns nil
. The expression object.presence
is equivalent to object.present? ? object : nil
present?
An object is present if it’s not blank.
This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:
becomes
region = params[:state].presence || params[:country].presence || 'US'
active_support/core_ext/object/duplicable
Most objects are cloneable, but not all. For example you can’t dup +nil+:
nil.dup # => TypeError: can't dup NilClass
Classes may signal their instances are not duplicable removing dup
and clone
or raising exceptions from them. So, to dup
an arbitrary object you normally use an optimistic approach and are ready to catch an exception, say:
arbitrary_object.dup rescue object
Rails dups objects in a few critical spots where they are not that arbitrary. That rescue
is very expensive (like 40 times slower than a predicate), and it is often triggered.
That’s why we hardcode the following cases and check duplicable?
instead of using the rescue idiom.
duplicable?
Is it possible to safely duplicate this object? Returns false
for nil
, false
, true
, symbols
, numbers
, class and module objects, true
otherwise.
active_support/core_ext/object/instance_variables
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
, then protected variables are also ignored.
In both cases, strings and symbols are understood, and they have to include the at sign.
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.
instance_variable_names
Returns an array of instance variable names including “@”. They are strings both in Ruby 1.8 and 1.9.
active_support/core_ext/object/to_param
to_param
Alias of to_s
.
active_support/core_ext/object/with_options
with_options(options)
An elegant way to refactor out common options.
active_support/dependencies
load(file, *extras)
Rails overrides Ruby’s built-in load
method to tie it into the Dependencies
subsystem.
require(file, *extras)
Rails overrides Ruby’s built-in require
method to tie it into the Dependencies
subsystem.
require_association(file_name)
Used internally by Rails. Invokes Dependencies.associate_with (file_name)
.
require_dependency(file_name)
Used internally by Rails. Invokes Dependencies.depend_on(file_name)
.
require_or_load(file_name)
Used internally by Rails. Invokes Dependencies.require_or_load(file_name)
.
unloadable(const_desc)
Marks the specified constant as unloadable. Unloadable constants are removed each time dependencies are cleared.
Note that marking a constant for unloading need only be done once. Setup or init scripts may list each unloadable constant that will need unloading; constants marked in this way will be removed on every subsequent Dependencies.clear
, as opposed to the first clear only.
The provided constant descriptor const_desc
may be a (nonanonymous) module or class, or a qualified constant name as a string or symbol.
Returns true
if the constant was not previously marked for unloading, false
otherwise.
active_support/json/encoding
to_json(options = nil)
Dumps object in JSON (JavaScript Object Notation).
ActiveSupport::OrderedHash
active_support/ordered_hash
This is a hash implementation for Ruby 1.8.x that preserves the ordering of its elements, in contrast to normal Ruby hashes. (Ruby 1.9 hashes are ordered natively!) It’s namespaced to prevent conflicts with other implementations, but you can assign it to a top-level namespace if you don’t want to constantly use the fully qualified name:
ActiveSupport::OrderedOptions
active_support/ordered_options
A subclass of OrderedHash
that adds a method-missing implementation so that hash elements can be accessed and modified using normal attribute semantics, dot-notation:
ActiveSupport::Railtie
active_support/railtie
Contains Active Support’s initialization routine for itself and the I18n subsystem.
If you’re depending on Active Support outside of Rails, you should be aware of what happens in this Railtie in case you end up needing to replicate it in your own code.
Range
Extensions to Ruby’s Range
class.
active_support/core_ext/range/blockless_step
step
Ruby’s native Range#step
(on most platforms) raises a LocalJumpError
if you omit a block. Rails patches step
to make it return an array if it’s called without a block.
active_support/core_ext/range/conversions
to_formatted_s(format = :default)
Generates a formatted string representation of the range.
active_support/core_ext/range/include_range
include?(value)
Extends the default Range#include?
to support range comparisons.
The native include?
behavior is untouched.
active_support/core_ext/range/include_range
overlaps?(other)
Compares two ranges and sees if they overlap each other
Regexp
active_support/core_ext/enumerable
sum(identity = 0)
Optimizes range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
active_support/json/encoding
as_json
Returns self.to_s
.
ActiveSupport::Rescuable
The Rescuable
module is a Concern
that adds support for easier exception handling. Used within Rails primarily in controller actions, but potentially very useful in your own libraries too.
active_support/rescuable
rescue_from(*klasses, &block)
The rescue_from
method receives a series of exception classes or class names, and a trailing :with
option with the name of a method or a Proc
object to be called to handle them. Alternatively a block can be given.
Handlers that take one argument will be called with the exception, so that the exception can be inspected when dealing with it.
Handlers are inherited. They are searched from right to left, from bottom to top, and up the hierarchy. The handler of the first class for which exception.is_a?(klass)
returns true
is the one invoked, if any.
Here’s some example code taken from Action Controller.
ActiveSupport::SecureRandom
A secure random number generator interface.
This library is an interface for secure random number generator which is suitable for generating session key in HTTP cookies, etc.
It supports following secure random number generators.
• openssl
• /dev/urandom
• Win32
Note: This module is based on the SecureRandom library from Ruby 1.9, revision 18786, August 23 2008. It’s 100 percent interface-compatible with Ruby 1.9’s SecureRandom library.
active_support/secure_random
Note that all of the methods in this module will raise NotImplementedError
if a secure random number generator is not available.
SecureRandom.base64(n = 16)
This method generates a random base64 string. The argument n
specifies the length of the random length. The length of the result string is about 4/3 of n
.
SecureRandom.hex(n = 16)
This method generates a random hex string. The argument n
specifies the length of the random length. The length of the result string is twice of n
.
SecureRandom.random_number(n = 0)
This method generates a random number. If an positive integer is given as n, then random_number
returns an integer.
0 <= SecureRandom.random_number(n) < n
If 0 is given or an argument is not supplied then random_number
returns a float.
0.0 <= SecureRandom.random_number() < 1.0
SecureRandom.random_bytes(n = 16)
This method generates a random binary string. The argument n
specifies the length of the result string.
String
Extensions to Ruby’s String
class.
active_support/json/encoding
as_json
Returns self
.
encode_json
Returns JSON escaped version of self
.
active_support/core_ext/object/blank
blank?
Returns true
if the string consists of only whitespace.
active_support/core_ext/string/access
at(position)
Returns the character at position,
treating the string as an array (where 0 is the first character). Returns nil
if the position exceeds the length of the string.
blank?
Returns the result of empty?
(stripping whitespace, if needed).
first(number)
Returns the first number
of characters in a string.
"hello".first # => "h"
"hello".first(2) # => "he"
"hello".first(10) # => "hello"
from(position)
Returns the remaining characters of a string from the position,
treating the string as an array (where 0 is the first character). Returns nil
if the position exceeds the length of the string.
"hello".at(0) # => "hello"
"hello".at(2) # => "llo"
"hello".at(10) # => nil
last(number)
Returns the last number
of characters in a string.
"hello".last # => "o"
"hello".last(2) # => "lo"
"hello".last(10) # => "hello"
to(position)
Returns the beginning of the string up to the position
treating the string as an array (where 0 is the first character). Doesn’t produce an error when the position
exceeds the length of the string.
"hello".at(0) # => "h"
"hello".at(2) # => "hel"
"hello".at(10) # => "hello"
active_support/core_ext/string/acts_like
Duck-types as a String
-like class. See Object#acts_like?
for more explanation.
active_support/core_ext/string/conversions
ord
Returns the codepoint of the first character of the string, assuming a single-byte character encoding:
"a".ord # => 97
"à".ord # => 224, in ISO-8859-1
This method is defined in Ruby 1.8 for Ruby 1.9 forward compatibility on these character encodings. It is forward compatible with Ruby 1.9 on UTF8 strings:
>> "a".mb_chars.ord
=> 97
>> "à".mb_chars.ord
=> 224 # in UTF8
Note that the 224 is different in both examples. In ISO-8859-1 “à” is represented as a single byte, 224. In UTF8 it is represented with 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.
to_date
Uses Date.parse
to turn a string into a Date
.
to_datetime
Uses Date.parse
to turn a string into a DateTime
.
to_time(form = :utc)
Uses Date.parse
to turn a string into a Time
either using either :utc
(default) or :local
.
active_support/core_ext/string/encoding
encoding_aware?
Returns true
if Encoding
is defined and String
responds to :encode
.
active_support/core_ext/string/exclude
exclude?(other)
The inverse of include?
. Returns true
if self
does not include the other
string.
active_support/core_ext/string/filters
squish
Returns the string, first removing all whitespace on both ends of the string, and then changing remaining consecutive whitespace groups into one space each.
squish!
Performs a destructive squish. See squish
.
truncate(length, options = {})
Truncates a given text
after a given length
if text
is longer than length
. The last characters will be replaced with the :omission
(which defaults to “...”) for a total length not exceeding :length
.
Pass a :separator
to truncate text
at a natural break.
active_support/core_ext/string/inflections
String inflections define new methods on the String
class to transform names for different purposes.
For instance, you can figure out the name of a database from the name of a class:
>> "ScaleScore".tableize
=> "scale_scores"
If you get frustrated by the limitations of Rails inflections, try the most excellent Linguistics library by Michael Granger at http://www.deveiate.org/projects/ Linguistics. It doesn’t do all of the same inflections as Rails, but the ones that it does do, it does better. (See titleize
for an example.)
camelize(first_letter = :upper)
By default, camelize
converts strings to UpperCamelCase. If the argument to camelize
is set to :lower
, then camelize
produces lowerCamelCase. Also converts “/” to “::”, which is useful for converting paths to namespaces.
classify
Creates a class name from a table name; used by Active Record to turn table names to model classes. Note that the classify
method returns a string and not a Class
. (To convert to an actual class, follow classify
with constantize
.)
>> "egg_and_hams".classify
=> "EggAndHam"
>> "post".classify
=> "Post"
constantize
The constantize
method tries to find a declared constant with the name specified in the string. It raises a NameError
if a matching constant is not located.
>> "Module".constantize
=> Module
>> "Class".constantize
=> Class
dasherize
Replaces underscores with dashes in the string.
>> "puni_puni"
=> "puni-puni"
demodulize
Removes the module prefixes from a fully qualified module or class name.
foreign_key(separate_class_name_and_id_with_underscore = true)
Creates a foreign key name from a class name.
"Message".foreign_key #=> "message_id"
"Message".foreign_key(false) #=> "messageid"
"Admin::Post".foreign_key #=> "post_id"
humanize
Capitalizes the first word of a string, turns underscores into spaces, and strips _id
. Similar to the titleize
method in that it is intended for creating pretty output.
"employee_salary" #=> "Employee salary"
"author_id" #=> "Author"
parameterize(sep = '-')
Replaces special characters in a string with sep
string so that it may be used as part of a pretty URL.
pluralize
Returns the plural form of the word in the string.
"post".pluralize #=> "posts"
"octopus".pluralize #=> "octopi"
"sheep".pluralize #=> "sheep"
"words".pluralize #=> "words"
"the blue mailman".pluralize #=> "the blue mailmen"
"CamelOctopus".pluralize #=> "CamelOctopi"
singularize
The reverse of pluralize
; returns the singular form of a word in a string.
"posts".singularize #=> "post"
"octopi".singularize #=> "octopus"
"sheep".singluarize #=> "sheep"
"word".singluarize #=> "word"
"the blue mailmen".singularize #=> "the blue mailman"
"CamelOctopi".singularize #=> "CamelOctopus"
tableize
Creates a plural and underscored database table name based on Rails conventions. Used by Active Record to determine the proper table name for a model class. This method uses the pluralize
method on the last word in the string.
"RawScaledScorer".tableize #=> "raw_scaled_scorers"
"egg_and_ham".tableize #=> "egg_and_hams"
"fancyCategory".tableize #=> "fancy_categories"
titlecase
Alias for titleize
.
titleize
Capitalizes all the words and replaces some characters in the string to create a nicer-looking title. The titleize
method is meant for creating pretty output and is not used in the Rails internals.
>> "The light on the beach was like a sinus headache".titleize
=> "The Light On The Beach Was Like A Sinus Headache"
It’s also not perfect. Among other things, it capitalizes words inside the sentence that it probably shouldn’t, like “a” and “the.” It also has a hard time with apostrophes:
>> "Her uncle's cousin's record albums".titleize
=> "Her Uncle'S Cousin'S Record Albums"
The Linguistics
gem mentioned in the beginning of this section has an excellent proper_noun
method that in my experience works much better than titleize
:
>> "Her uncle's cousin's record albums".en.proper_noun
=> "Her Uncle's Cousin's Record Albums"
underscore
The reverse of camelize
. Makes an underscored form from the expression in the string. Changes “::” to “/” to convert namespaces to paths.
"ActiveRecord".underscore #=> "active_record"
"ActiveRecord::Errors".underscore #=> active_record/errors
active_support/core_ext/string/multibyte
Defines a mutibyte safe proxy for string methods.
mb_chars
In Ruby 1.8 and older mb_chars
creates and returns an instance of ActiveSupport::Multibyte::Chars
encapsulating the original string. A Unicode safe version of all the String
methods are defined on the proxy class. If the proxy class doesn’t respond to a certain method, it’s forwarded to the encapsuled string.
In Ruby 1.9 and newer mb_chars
returns self
because String
is (mostly) encoding aware. This means that it becomes easy to run one version of your code on multiple Ruby versions.
All the methods on the Chars
proxy which normally return a string will return a Chars
object. This allows method chaining on the result of any of these methods.
>> name.mb_chars.reverse.length
=> 12
The Chars
object tries to be as interchangeable with String
objects as possible: sorting and comparing between String
and Char
work like expected. The bang! methods change the internal string representation in the Chars
object. Interoperability problems can be resolved easily with a to_s
call.
For more information about the methods defined on the Chars
proxy see ActiveSupport::Multibyte::Chars
. For information about how to change the default Multibyte
behavior see ActiveSupport::Multibyte
.
is_utf8?(suffix)
Returns true
if the string has UTF-8 semantics, versus strings that are simply being used as byte streams.
active_support/core_ext/string/output_safety
html_safe
Returns an html-escaped version of self
. See ERB::Util#html_escape
for more information.
active_support/core_ext/string/starts_ends_with
Provides String
with additional condition methods.
starts_with?(prefix)
Returns true
if the string starts with the specified prefix
.
ends_with?(suffix)
Returns true
if the string ends with the specified suffix
.
active_support/core_ext/string/xchar
Requires the fast_xs
gem2, which provides C extensions for quickly escaping text. Rails will automatically use fast_xs
from either Hpricot
or the gem version with the bundled Builder
package.
ActiveSupport::StringInquirer
Wrapping a string in this class gives you a prettier way to test for equality. The value returned by Rails.env
is wrapped in a StringInquirer
object so instead of calling this:
Rails.env == "production"
you can call this:
Rails.env.production?
This class is really simple, so you only really want to do this with strings that contain no whitespace or special characters.
>> s = ActiveSupport::StringInquirer.new("obie")
=> "obie"
>> s.obie?
=> true
Symbol
Extensions to Ruby’s Symbol
class.
active_support/json/encoding
as_json
Returns to_s
version of itself.
ActiveSupport::Testing::Assertions
active_support/testing/assertions
Rails adds a number of assertions to the basic ones provided with Test::Unit
.
assert_blank(object)
Test if an expression is blank. Passes if object.blank?
is true
.
assert_blank [] # => true
assert_present(object)
Tests if an expression is not blank. Passes if object.present?
is true
.
assert_present {:data => 'x'}#=> true
assert_difference(expressions, difference = 1, message = nil, &block)
Tests whether a numeric difference in the return value of an expression is a result of what is evaluated in the yielded block. (Easier to demonstrate than to explain!)
The following example eval’s the expression Article.count
and saves the result. Then it yields to the block, which will execute the post :create
and return control to the assert_difference
method. At that point, Article.count
is eval’d again, and the difference is asserted to be 1
(the default difference).
assert_difference 'Article.count' do
post :create, :article => {...}
end
Any arbitrary expression can be passed in and evaluated:
assert_difference 'assigns(:article).comments(:reload).size' do
post :create, :comment => {...}
end
Arbitrary difference values may be specified. The default is +1, but negative numbers are okay too:
assert_difference 'Article.count', -1 do
post :delete, :id => ...
end
An array of expressions can also be passed in—each will be evaluated:
assert_difference [ 'Article.count', 'Post.count' ], +2 do
post :create, :article => {...}
end
A error message can be specified:
assert_difference 'Article.count', -1, "Article should be destroyed" do
post :delete, :id => ...
end
assert_no_difference(expressions, message = nil, &block)
Tests that the return value of the supplied expression does not change as a result of what is evaluated in the yielded block.
assert_no_difference 'Article.count' do
post :create, :article => invalid_attributes
end
Time
Extensions to Ruby’s built-in Time
class.
active_support/json/encoding
as_json
Returns self
as a JSON string. The ActiveSupport.use_standard_json_time_format
configuration setting determines whether the output is formatted using :xmlschema
or the following pattern:
%(#{strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)})
active_support/core_ext/time/acts_like
Duck-types as a Time-like class. See Object#acts_like?
for more explanation.
active_support/core_ext/time/calculations
Contains methods that facilitate time calculations.
===(other)
Overriding case equality method so that it returns true
for ActiveSupport::TimeWithZone
instances.
+ (other)
Implemented by the plus_with_duration
method. It allows addition of times like this:
expiration_time = Time.now + 3.days
- (other)
Implemented by the minus_with_duration
method. It allows addition of times like this:
two_weeks_ago = Time.now - 2.weeks
advance(options)
Provides precise Time
calculations. The options
parameter takes a hash with any of the keys :months
, :days
, :years
, :hour
, :min
, :sec
, and :usec
.
ago(seconds)
Returns a new Time
representing the time a number of seconds into the past; this is basically a wrapper around the Numeric
extension of the same name. For the best accuracy, do not use this method in combination with x.months
; use months_ago
instead!
at_beginning_of_day
Alias for beginning_of_day
.
at_beginning_of_month
Alias for beginning_of_month
.
at_beginning_of_week
Alias for beginning_of_week
.
at_beginning_of_year
Alias for beginning_of_year
.
at_end_of_day
Alias for end_of_day
.
at_end_of_month
Alias for end_of_month
.
at_end_of_week
Alias for end_of_week
.
at_end_of_year
Alias for end_of_year
.
beginning_of_day
Returns a new Time
representing the “start” of the current instance’s day, hard-coded to 00:00 hours.
beginning_of_month
Returns a new Time
representing the start of the month (1st of the month, 00:00 hours).
beginning_of_quarter
Returns a new Time
representing the start of the calendar quarter (1st of January, April, July, October, 00:00 hours).
beginning_of_week
Returns a new Time
representing the “start” of the current instance’s week, hard-coded to Monday at 00:00 hours.
beginning_of_year
Returns a new Time
representing the start of the year (1st of January, 00:00 hours).
change(options)
Returns a new Time
where one or more of the elements have been changed according to the options
parameter. The valid date options are :year
, :month
, :day
. The valid time options are :hour
, :min
, :sec
, :offset
, and :start
.
Time.days_in_month(month, year = nil)
Returns the number of days in the given month. If a year is given, February will return the correct number of days for leap years. Otherwise, this method will always report February as having 28 days.
>> Time.days_in_month(7, 1974)
=> 31
end_of_day
Returns a new Time
representing the end of the day (23:59:59).
end_of_month
Returns a new Time
representing the end of the month (last day of the month, 00:00 hours).
last_month
Convenience method for months_ago(1)
.
last_year
Convenience method for years_ago(1)
.
local_time(*args)
Wraps the class method time_with_datetime_fallback
with utc_or_local
argument set to :local
.
monday
Alias for beginning of_week
.
months_ago(months)
Returns a new Time
representing the time a number of specified months
into the past.
months_since(months)
The opposite of months_ago
. Returns a new Time
representing the time a number of specified months
into the future.
next_month
Convenience method for months_since(1)
.
next_year
Convenience method for years_since(1)
.
seconds_since_midnight
Returns the number of seconds that have transpired since midnight.
since(seconds)
Returns a new Time
representing the time a number of seconds
into the future starting from the instance time. This method is basically a wrapper around the Numeric
extension of the same name. For best accuracy, do not use this method in combination with x.months
; use months_since
instead!
time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0)
Returns a new Time
if the requested year can be accommodated by Ruby’s Time
class. The range of the Time
class is either 1970..2038 or 1902..2038, depending on the host system’s architecture. Years outside the supported range will return a DateTime
object.
tomorrow
Convenience method for self.since(1.day)
.
utc_time(*args)
Wraps the class method time_with_datetime_fallback
with utc_or_local
argument set to :utc
.
years_ago(years)
Returns a new Time
representing the time a number of specified years
into the past.
years_since(years)
The opposite of years_ago
. Returns a new Time
representing the time a number of specified years
into the future.
yesterday
Convenience method for self.ago(1.day)
.
active_support/core_ext/time/conversions
Extensions to Ruby’s Time
class to convert time objects into different convenient string representations and other objects.
The DATE_FORMATS
hash constant holds formatting patterns used by the to_formatted_s
method to convert a Time
object into a string representation:
formatted_offset(colon = true, alternate_utc_string = nil)
Returns the UTC offset as an HH:MM
formatted string.
Time.local(2000).formatted_offset # => "-06:00"
Time.local(2000).formatted_offset(false) # => "-0600"
to_date
Returns a new Date
object based on a Time
, discarding time data.
to_datetime
Returns a new DateTime
object based on a Time
, preserving the utc
offset. Basically a wrapper around the DateTime.civil
factory method:
DateTime.civil(year, month, day, hour, min, sec,
Rational(utc_offset,86400), 0)
to_formatted_s(format = :default)
Converts a Time
object into a string representation. The :default
option corresponds to the Time
object’s own to_s
method.
to_time
Returns self
.
active_support/core_ext/time/marshal
Pre-1.9 versions of Ruby have a bug with marshaling Time
instances, where utc instances are unmarshalled in the local zone, instead of utc. Rails layers behavior on the _dump
and _load
methods so that utc instances can be flagged on dump, and coerced back to utc on load.
Ruby 1.9.2 adds utc_offset
and zone to Time
, but marshaling only preserves utc_offset
. Rails preserves zone also, even though it may not work in some edge cases.
active_support/core_ext/time/zones
Extensions to Time
having to do with support for time zones.
current
Returns Time.zone.now
when config.time_zone
is set, otherwise just returns Time.now
.
use_zone(time_zone, &block)
Allows override of Time.zone
locally inside supplied block; resets Time.zone
to existing value when done.
zone
Returns the TimeZone
for the current request, if this has been set (via Time.zone=
). If Time.zone
> has not been set for the current request, returns the TimeZone
specified in config.time_zone
.
zone=(time_zone)
Sets Time.zone
to a TimeZone
object for the current request/thread.
This method accepts any of the following:
• A Rails TimeZone
object.
• An identifier for a Rails TimeZone
object (e.g., “Eastern Time (US & Canada)”, -5.hours
).
• A TZInfo::Timezone
object.
• An identifier for a TZInfo::Timezone
object (e.g., “America/New_York”).
Here’s an example of how you might set Time.zone
on a per request basis. The code assumes that current_user.time_zone
returns a string identifying the user’s preferred TimeZone
:
ActiveSupport::TimeWithZone
A Time
-like class that can represent a time in any time zone. Necessary because standard Ruby Time
instances are limited to UTC and the system’s <tt>ENV[‘TZ’]</tt> zone.
You shouldn’t ever need to create a TimeWithZone
instance directly via new
. Rails provides the methods local
, parse
, at
and now
on TimeZone
instances, and in_time_zone
on Time
and DateTime
instances, for a more user-friendly syntax.
See Time
and ActiveSupport::TimeZone
for further documentation of these methods. TimeWithZone
instances implement the same API as Ruby Time instances, so that Time and TimeWithZone
instances are interchangable.
ActiveSupport::TimeZone
The TimeZone
class serves as a wrapper around TZInfo::Timezone
instances. It allows Rails to do the following:
• Limit the set of zones provided by TZInfo
to a meaningful subset of 142 zones
• Retrieve and display zones with a friendlier name (e.g., “Eastern Time (US & Canada)” instead of “America/New_York”)
• Lazily load TZInfo::Timezone
instances only when they’re needed
• Create ActiveSupport::TimeWithZone
instances via TimeZone’s local
, parse
, at
and now
methods.
If you set config.time_zone
in an initializer, you can access this TimeZone
object via Time.zone
:
config.time_zone = "Eastern Time (US & Canada)"
active_support/values/time_zone
The version of TZInfo
bundled with Active Support only includes the definitions necessary to support the zones defined by the TimeZone
class. If you need to use zones that aren’t defined by TimeZone
, you’ll need to install the TZInfo
gem. If a recent version of the gem is installed locally, this will be used instead of the bundled version.
<=> (other)
Compares this timezone to the parameter. The two are compared first based on their offsets, and then by name.
TimeZone[] (arg)
Locates a specific timezone object. If the argument is a string, it is interpreted to mean the name of the timezone to locate.
>> TimeZone['Dublin']
=> #<TimeZone:0x3208390 @name="Dublin", @utc_offset=0>
If it is a numeric value it is either the hour offset, or the second offset, of the timezone to find. (The first one with that offset will be returned.)
Returns nil
if no such timezone is known to the system.
TimeZone.all
Returns an array of all 142 TimeZone
objects. There are multiple TimeZone
objects per timezone (in many cases) to make it easier for users to find their own timezone.
>> ActiveSupport::TimeZone.all
=> [#<ActiveSupport::TimeZone:0x551c34...
TimeZone.create(name, offset)
Creates a new TimeZone
instance with the given name and offset.
>> ActiveSupport::TimeZone.create("Atlanta", -5.hours)
=> #<ActiveSupport::TimeZone:0x26c3a48 @current_period=nil, @tzinfo=nil,
@utc_offset=-18000 seconds, @name="Atlanta">
TimeZone.find_tzinfo(name)
Returns a TZInfo
instance matching the specified name
.
formatted_offset(colon = true)
Returns the offset of this timezone as a formatted string, in the format HH:MM
. If the offset is zero, this method will return an empty string. If colon
is false
, a colon will not be inserted into the output.
initialize(name, utc_offset = nil, tzinfo = nil)
Creates a new TimeZone object with the given name
and offset
. The offset
is the number of seconds that this time zone is offset from UTC (GMT). Seconds were chosen as the offset unit because that is the unit that Ruby uses to represent time zone offsets (see Time#utc_offset
). The tzinfo
parameter can be explicitly passed in, otherwise the name
will be used to find it: TimeZone.find_tzinfo(name)
now
Returns Time.now
adjusted to this timezone.
>> Time.now
=> Fri Aug 31 22:39:58 -0400 2007
>> TimeZone['Fiji'].now
=> Sat Sep 01 14:40:00 UTC 2007
TimeZone.seconds_to_utc_offset (seconds, colon = true)
Assumes self
represents an offset from UTC in seconds (as returned from Time#utc_offset
) and turns this into an +HH:MM formatted string.
TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"
to_s
Returns a textual representation of this timezone.
TimeZone['Dublin'].to_s #=> "(GMT) Dublin"
today
Returns the current date in this timezone.
>> Date.today.to_s
=> "2007-08-31"
>> TimeZone['Fiji'].today.to_s
=> "2007-09-01"
TimeZone.us_zones
A convenience method for returning a collection of TimeZone
objects for timezones in the United States.
ActiveSupport::TrueClass
active_support/core_ext/object/blank
blank?
Returns false
.
active_support/json/encoding
as_json
Returns "true"
.
ActiveSupport::XmlMini
The XmlMini
module contains code that allows Rails to serialize/deserialize and parse XML using a number of different libraries.
• JDOM (requires JRuby)
• LibXML (fast native XML parser)
• Nokogiri (requires Nokogiri gem)
• ReXML
active_support/xml_mini
If you’re doing anything of significance with XML in your application, you should definitely use the super-fast native libxml
parser. Install the binaries (instructions vary depending on platform) then the Ruby binding:
gem 'libxml-ruby', '=0.9.7'
Set XmlMini
to use libxml
in application.rb
or an initializer.
XmlMini.backend = 'LibXML'
The TYPE_NAMES
constant holds a mapping of Ruby types to their representation when serialized as XML.
The FORMATTING
constant holds a mapping of lambdas that define how Ruby values are serialized to strings for representation in XML.
The PARSING
constant holds a mapping of lambdas used to deserialize values stored in XML back into Ruby objects.
18.116.43.36