Active Support API Reference - The Rails 4 Way (2014)

The Rails 4 Way (2014)

Active Support API Reference

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 just creates a string representation of the array.

>> %w(foo bar baz quux).to_s

=> "[\"foo\", \"bar\", \"baz\", \"quux\"]"

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 Active Record objects (or other types of objects that properly respond to id). If the contents of the array do not respond to id, a NoMethodError exception is raised.

>> %w(foo bar baz quux).to_s(:db)

NoMethodError: undefined method `id' for "foo":String

to_s

The to_s method of Array is aliased to to_formatted_s.

to_default_s

The to_default_s method of Array is aliased to to_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:

:words_connector

The sign or word used to join the elements in arrays with two or more elements (default: “, “).

:two_words_connector

The sign or word used to join the elements in arrays with two elements (default: “ and “).

:last_word_connector

The sign or word used to join the last element in arrays with three or more elements (default: “, and “).

:locale

If i18n is available, you can set a locale and use the connector options defined on the ‘support.array’ namespace.

to_xml(options = {}) |xml| ...

As covered in Chapter 22, “XML”, 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. If the array element does not respond to to_xml, an XML representation of the object will be returned.

>> ["riding","high"].to_xml

=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<strings type=\"array\">\n

<string>riding</string>\n <string>high</string>\n</strings>\n"

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.

1 {foo: "foo", bar: 42}.to_xml do |xml|

2 xml.did_it "again"

3 end

outputs the following XML:

1 <?xml version="1.0" encoding="UTF-8"?>

2 <hash>

3 <bar type="integer">42</bar>

4 <foo>foo</foo>

5 <did_it>again</did_it>

6 </hash>

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

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

1 def options(*args)

2 args.extract_options!

3 end

4

5 >> options(1, 2)

6 => {}

7

8 >> options(1, 2, a: :b)

9 => {:a=>:b}

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.

1 %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) { |group| p group }

2 ["1", "2", "3", "4"]

3 ["5", "6", "7", nil]

4 ["8", "9", "10", nil]

5

6 %w(1 2 3 4 5 6 7).in_groups(3, ' ') { |group| p group }

7 ["1", "2", "3"]

8 ["4", "5", " "]

9 ["6", "7", " "]

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.

1 %w(1 2 3 4 5 6 7).in_groups(3, false) { |group| p group }

2 ["1", "2", "3"]

3 ["4", "5"]

4 ["6", "7"]

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.to_s }

=> ["1", "2"]

["3", " "]

nil

Passing false to the fill_with parameter inhibits the fill behavior.

>> %w(1 2 3).in_groups_of(2, false) { |group| puts group.to_s }

=> ["1", "2"]

["3"]

nil

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

Adds two aliases that are more the human way of thinking about adding stuff to a list.

append

The append method of Array is aliased to <<.

prepend

The prepend method of Array is aliased to unshift.

active_support/core_ext/array/wrap

A convenience method added to the Array class.

Array.wrap(object)

Wraps the object in an Array unless it’s an Array. If nil is supplied, and empty list is returned. Otherwise, the wrap method will convert the supplied 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:

1 Array(foo: :bar) # => [[:foo, :bar]]

2 Array.wrap(foo: :bar) # => [{:foo => :bar}]

3

4 Array("foo\nbar") # => ["foo\nbar"]

5 Array.wrap("foo\nbar") # => ["foo\nbar"]

6

7 Array(nil) # => []

8 Array.wrap(nil) # => []

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.

>> ["riding","high","and","I","want","to","make"].to_param

=> "riding/high/and/I/want/to/make"

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

1 bc = ActiveSupport::BacktraceCleaner.new

2 bc.add_filter { |line| line.gsub(Rails.root, '') }

3 bc.add_silencer { |line| line =~ /mongrel|rubygems/ }

4

5 # will strip the Rails.root prefix and skip any lines from mongrel or rubygems

6 bc.clean(exception.backtrace)

Inspired by the Quiet Backtrace gem by Thoughtbot.

Benchmark

The following method provides additional functionality for returning in benchmark results in a human readable format.

ms

Benchmark realtime in milliseconds

>> Benchmark.realtime { User.all }

=> 8.0e-05

>> Benchmark.ms { User.all }

=> 0.074

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.

1 benchmark "Process data files" do

2 expensive_files_operation

3 end

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.

1 benchmark "Low-level files", level: :debug do

2 lowlevel_files_operation

3 end

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:

1 benchmark "Process data files", level: :info, silence: true do

2 expensive_and_chatty_files_operation

3 end

BigDecimal

active_support/core_ext/big_decimal/conversions

to_formatted_s(*args)

Emits a string representation of the number without any scientific notation and without losing precision.

>> bd = BigDecimal.new("84394878749783498749834734987.839723497347")

=> #<BigDecimal:269fabc,'0.8439487874 9783498749 8347349878 3972349734 7E29',44(48)>

>> bd.to_s

=> "84394878749783498749834734987.839723497347"

to_s

The to_s method of BigDecimal is aliased to to_formatted_s.

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::Cache::Store

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, read, write,exist?, and delete.

ActiveSupport::Cache::Store can store any serializable Ruby object.

>> cache = ActiveSupport::Cache::MemoryStore.new

=> <#ActiveSupport::Cache::MemoryStore entries=0, size=0, options={}>

>> cache.read("city")

=> nil

>> cache.write("city", "Duckburgh")

=> true

>> cache.read("city")

=> "Duckburgh"

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.

>> r = Report.first

=> #<Report id: 1, name: "Special", created_at: ...>

>> r.cache_key

=> "reports/1-20131001152655016228000"

>> r.to_param

=> "1"

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.

>> cache.write ["USA","FL","Jacksonville"], "Obie"

=> true

>> cache.read "USA/FL/Jacksonville"

=> "Obie"

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. To set a global namespace, set the :namespace to the constructor of the cache store. The default value will include the application name and Rails environment.

cache = ActiveSupport::Cache::MemoryStore.new(namespace: 'tr4w')

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.

1 cache = ActiveSupport::Cache::MemoryStore.new(expire_in: 5.minutes)

2 cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry

It’s a recommended practice to set the :race_condition_ttl option in conjunction with :expires_in. When a cache entry is used frequently and the system is under a heavy load, a dog pile effect can occur during expiration. During this scenario, since the cache has expired, multiple processes will try to read the data natively and all attempt to regenerate the same cache entry simultaneously. Using :race_condition_ttl, one can set the number of seconds an expired entry can be reused while a new value is being regenerated. The first process to encounter the stale cache will attempt to write a new value, while other processes will continue to use slightly state data for the period defined in :race_condition_ttl. Like the :expires_in option, :race_condition_ttl can be set globally or in the fetch or write methods for a single 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 16K.

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.

>> Rails.cache.write :color, :red

=> true

>> Rails.cache.read :color

=> :red

>> Rails.cache.delete_matched "c"

=> ["city", "color", "USA/FL/Jacksonville"]

>> Rails.cache.read :color

=> nil

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.

1 cache.write("today", "Monday")

2 cache.fetch("today") # => "Monday"

3

4 cache.fetch("city") # => nil

5 cache.fetch("city") do

6 "Duckburgh"

7 end

8 cache.fetch("city") # => "Duckburgh"

You may also specify additional options via the options argument. Setting :force => true will force a cache miss:

1 cache.write("today", "Monday")

2 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 where 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.

1 # Set all values to expire after one minute.

2 cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)

3

4 cache.write("foo", "original value")

5 val_1 = nil

6 val_2 = nil

7 sleep 60

8

9 Thread.new do

10 val_1 = cache.fetch("foo", race_condition_ttl: 10) do

11 sleep 1

12 "new value 1"

13 end

14 end

15

16 Thread.new do

17 val_2 = cache.fetch("foo", race_condition_ttl: 10) do

18 "new value 2"

19 end

20 end

21

22 # val_1 => "new value 1"

23 # val_2 => "original value"

24 # sleep 10 # First thread extend the life of cache by another 10 seconds

25 # cache.fetch("foo") => "new value 1"

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:

1 cache = ActiveSupport::Cache::MemCacheStore.new

2 cache.fetch("foo", force: true, raw: true) do

3 :bar

4 end

5 cache.fetch("foo") # => "bar"

increment(name, amount = 1, options = nil)

Increment an integer value in the cache. Options are passed to the underlying cache implementation.

mute

Silence the logger within a block.

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.

>> cache.write :color, :red

=> true

>> cache.write :smell, :roses

=> true

>> cache.read_multi :color, :smell

=> {:color=>:red, :smell=>:roses}

silence!

Silences the logger.

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

CachingKeyGenerator is a wrapper around KeyGenerator which avoids re-executing the key generation process when it’s called using the same salt and key_size.

active_support/key_generator

initialize(key_generator)

Creates a new instance of CachingKeyGenerator.

generate_key(salt, key_size=64)

Returns a derived key suitable for use. The default key_size is chosen to be compatible with the default settings of ActiveSupport::MessageVerifier, such as OpenSSL::Digest::SHA1#block_length. Subsequent calls to generate_key will return a cached key if the supplied salt and key_size are the same.

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:

1 classStorage

2 include ActiveSupport::Callbacks

3

4 define_callbacks :save

5 end

6

7 classConfigStorage < Storage

8 set_callback :save, :before, :saving_message

9

10 def saving_message

11 puts "saving..."

12 end

13

14 set_callback :save, :after do |object|

15 puts "saved"

16 end

17

18 def save

19 run_callbacks :save do

20 puts "- running save callbacks"

21 end

22 end

23 end

Running the following code using

1 config = ConfigStorage.new

2 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_action 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)

Define callbacks types for your custom class.

1 moduleMyOwnORM

2 classBase

3 define_callbacks :validate

4 end

5 end

The following options determine the operation of the callback:

:terminator

Indicates when a before callback is considered to be halted.

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

:skip_after_callbacks_if_terminated

Determines if after callbacks should be terminated by the :terminator option. By default, after callbacks are executed no matter if callback chain was terminated or not.

:scope

Specify which methods should be executed when a class is given as callback.

1 classAudit

2 def before(caller)

3 puts 'before is called'

4 end

5

6 def before_save(caller)

7 puts 'before_save is called'

8 end

9 end

10

11 classAccount

12 include ActiveSupport::Callbacks

13

14 define_callbacks :save

15 set_callback :save, :before, Audit.new

16

17 def save

18 run_callbacks :save do

19 puts 'saving...'

20 end

21 end

22 end

Calling save in the above example will execute Audit#before. If the callback is defined with a [:kind, :name] scope

1 define_callbacks :save, scope: [:kind, :name]

the method named "#{kind}_#{name}" would be invoked in the given class. In this case, Audit#before_save would be invoked.

The :scope option defaults to :kind.

reset_callbacks(symbol)

Remove all set callbacks for the given event.

set_callback(name, *filter_list, &block)

Set callbacks for a given event.

1 set_callback :save, :before, :before_method

2 set_callback :save, :after, :after_method, if: :condition

3 set_callback :save, :around,

4 ->(r, &block) { stuff; result = block.call; stuff }

The second argument indicates the whether callback :before, :after, or :around is to be run. By default, if nothing is set, :before is assumed. The first example can also be expressed as:

set_callback :save, :before_method

The callback that the callback invokes can be specified as a symbol, that references the name of an instance method, or as a proc, lambda, or block. If a proc, lambda, or block is supplied, its body is evaluated in the context of the current object. A current object can optionally be set.

skip_callback(name, *filter_list, &block)

Skip a previously defined callback for a given type. The options :if or :unless may be passed in order to control when the callback is skipped.

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)

Declare one or more class-level attributes whose value is inheritable and overwritable by subclasses and instances, like so:

1 classBase

2 class_attribute :setting

3 end

4

5 classSubclass < Base

6 end

7

8 >> Base.setting = "foo"

9 => "foo"

10

11 >> Subclass.setting

12 => "foo"

13

14 >> Subclass.setting = "bar"

15 => "bar"

16

17 >> Subclass.setting

18 => "bar"

19

20 >> Base.setting

21 => "foo"

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

1 klass = Class.new { class_attribute :setting }

2 object = klass.new

3

4 >> klass.setting = "foo

5 => "foo"

6

7 >> object.setting = "bar"

8 => "bar"

9

10 >> klass.setting

11 => "foo"

To opt out of the instance writer method, pass instance_writer: false.

1 klass = Class.new { class_attribute :setting, instance_writer: false }

2

3 >> klass.new.setting

4 NoMethodError: undefined method `setting='

The class_attribute method also works with singleton classes, as can be seen in the following example.

1 klass = Class.new { class_attribute :setting }

2

3 >> klass.singleton_class.setting = "foo"

4 => "foo"

Alternatively, setting instance_reader: false causes class_attribute to not define a reader method.

For convenience, a predicate method is defined as well, which allows you to see if an attribute has been set on a particular class instance.

1 klass = Class.new { class_attribute :setting }

2

3 >> klass.setting?

4 => false

5

6 >> klass.setting = "foo"

7 => "foo"

8

9 >> klass.setting?

10 => true

To opt out of defining a predicate method, set instance_predicate to false.

1 klass = Class.new { class_attribute :setting, instance_predicate: false }

2

3 >> klass.setting?

4 NoMethodError: undefined method `setting?'

active_support/core_ext/class/attribute_accessors

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.

1 classPerson

2 cattr_accessor :hair_colors

3 end

4

5 >> Person.hair_colors = [:brown, :black, :blonde, :red]

6

7 >> Person.new.hair_colors

8 => [:brown, :black, :blonde, :red]

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

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

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

1 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 26 lines of Ruby code. 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 two elements: the included block and the ClassMethods module.

1 require 'active_support/concern'

2

3 moduleFoo

4 extend ActiveSupport::Concern

5

6 included do

7 self.send(:do_something_in_mixin_class)

8 end

9

10 moduleClassMethods

11 def bar

12 ...

13 end

14 end

15

16 def baz

17 ...

18 end

19 end

To use your custom Concern module, just mix it into a class.

1 classWidget

2 include Foo

3 end

The included block will be triggered at inclusion time. Methods in ClassMethods will get added to Widget as class methods. All other methods will get added to Widget as instance methods.

See ActiveSupport::Configurable for a good example of how Concern is used internally by Rails.

ActiveSupport::Concurrency

ActiveSupport::Concurrency::Latch

The Latch class is used internally by Rails to test streaming controllers. It is being included here for completeness. The initializer of Latch accepts a single argument, representing the number of threads in the test.

await

Creates lock object for blocks with mutual exclusion and waits until the latch count is greater than zero.

release

Creates lock object for blocks with mutual exclusion. It decreases the latch count if its greater than zero, and wakes up all threads waiting for this lock if the count reaches zero.

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

Return the configuration of the object instance.

config_accessor(*names)

Creates configuration properties accessible via class and instance contexts. The names parameter expects one or more symbols corresponding to property names.

1 moduleActionController

2 classBase < Metal

3 config_accessor :assets_dir, :javascripts_dir, :stylesheets_dir

4 end

5 end

configure

Yields config.

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.

1 classDate

2 def acts_like_date?

3 true

4 end

5 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: :years, :months, :weeks, and :days.

>> 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.utc(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.utc(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 Date object 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 object representing the start of the calendar-based quarter (1st of January, April, July, and October).

>> Date.new(2005, 4, 1) == Date.new(2005, 6, 30).beginning_of_quarter

=> true

at_beginning_of_week

Alias for beginning_of_week.

at_beginning_of_year / beginning_of_year

Returns a new Date object representing the start of the calendar year (1st of January).

>> Date.new(2005, 1, 1) == Date.new(2005, 2, 22).beginning_of_year

=> true

at_end_of_day / 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).

at_end_of_month / end_of_month

Returns a new Date object representing the last day of the calendar month.

>> Date.new(2005, 3, 31) == Date.new(2005,3,20).end_of_month

=> true

at_end_of_quarter / end_of_quarter

Returns a new Date object representing the end of the calendar-based quarter (31st March, 30th June, 30th September).

at_end_of_week

Alias for end_of_week.

at_end_of_year / end_of_year

Returns a new Date object representing the end of the year.

>> Date.new(2013, 12, 31) == Date.new(2013, 10, 1).end_of_year

=> true

beginning_of_week

Returns a new Date object representing the beginning of the week. By default, based on Date.beginning_of_week.

>> Date.new(2005, 1, 31) == Date.new(2005, 2, 4).beginning_of_week

=> true

Date.beginning_of_week

Returns the week start for the current request/thread.

>> Date.beginning_of_week

=> :monday

Can be set Date.beginning_of_week or configuration option beginning_of_week in your Rails application configuration.

Date.beginning_of_week=(week_start)

Sets Date.beginning_of_week to a week start for current request/thread.

The method accepts the following symbols:

· :monday

· :tuesday

· :wednesday

· :thursday

· :friday

· :saturday

· :sunday

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.new(2007, 5, 12).change(day: 1) == Date.new(2007, 5, 1)

=> true

>> Date.new(2007, 5, 12).change(year: 2005, month: 1) == Date.new(2005, 1, 12)

=> true

Date.current

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.

days_ago(days)

Returns a new Date object minus the specified number of days.

>> Date.new(2013, 10, 1).days_ago(5)

=> Thu, 26 Sep 2013

days_since(days)

Returns a new Date object representing the time a number of specified days into the future.

>> Date.new(2013, 10, 5) == Date.new(2013, 10, 1).days_since(4)

=> true

days_to_week_start(start_day = Date.beginning_of_week)

Returns the number of days to the start of the week.

>> Date.new(2013, 10, 10).days_to_week_start

=> 3

end_of_week(start_day = Date.beginning_of_week)

Returns a new Date object representing the end of the week.

>> Date.new(2013, 10, 13) == Date.new(2013, 10, 10).end_of_week

=> true

Date.find_beginning_of_week!(week_start)

Returns the week start day symbol or raises an ArgumentError if an invalid symbol is set.

>> Date.find_beginning_of_week!(:saturday)

=> :saturday

>> Date.find_beginning_of_week!(:foobar)

ArgumentError: Invalid beginning of week: foobar

future?

Returns true if the Date instance is in the future.

>> (Date.current + 1.day).future?

=> true

last_month / prev_month

Convenience method for months_ago(1).

last_quarter / prev_quarter

Convenience method for months_ago(3).

last_week(start_day = Date.beginning_of_week) / prev_week

Returns a new Date object representing the given day in the previous week.

last_year / prev_year

Convenience method for years_ago(1).

middle_of_day / noon

Returns a new Date object representing the middle of the day.

monday

Convenience method for beginning_of_week(:monday).

months_ago(months)

Returns a new Date object 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 object 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

Convenience method for months_since(1).

next_quarter

Convenience method for months_since(3).

next_week(given_day_in_next_week = Date.beginning_of_week))

Returns a new Date object representing the start of the given day in the following calendar week.

>> Date.new(2005, 3, 4) == Date.new(2005, 2, 22).next_week(:friday)

=> true

next_year

Convenience method for years_since(1).

past?

Returns true if Date is in the past.

>> (Date.current - 1.day).past?

=> true

since(seconds) / in(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

sunday

Convenience method for end_of_week(:monday).

today?

Returns true if the Date instance is today.

>> Date.current.today?

=> true

Date.tomorrow

Convenience method that returns a new Date (or DateTime) representing the time one day in the future.

>> Date.tomorrow

=> Thu, 10 Oct 2013

tomorrow

Returns a new Date object advanced by one day.

>> Date.new(2007, 3, 1) == Date.new(2007, 2, 28).tomorrow

=> true

weeks_ago(weeks)

Returns a new Date object representing the time a number of specified weeks ago.

>> Date.new(2013, 10, 1) == Date.new(2013, 10, 8).weeks_ago(1)

=> true

weeks_since(weeks)

Returns a new Date object representing the time a number of specified weeks into the future.

>> Date.new(2013, 10, 8) == Date.new(2013, 10, 1).weeks_since(1)

=> true

years_ago(years)

Returns a new Date object 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 object 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 object representing the time one day in the past.

>> Date.yesterday

=> Tue, 08 Oct 2013

yesterday

Returns a new Date object subtracted by one day.

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

1 DATE_FORMATS = {

2 :short => '%e %b',

3 :long => '%B %e, %Y',

4 :db => '%Y-%m-%d',

5 :number => '%Y%m%d',

6 :long_ordinal => lambda { |date|

7 day_format = ActiveSupport::Inflector.ordinalize(date.day)

8 date.strftime("%B #{day_format}, %Y") # => "April 25th, 2007"

9 },

10 :rfc822 => '%e %b %Y'

11 }

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

Note that Active Support explicitly removes the Date#to_time method in Ruby 2.0, as it converts localtime only.

xmlschema

Returns a string that represents the time as defined by XML Schema within the current time zone (also known as iso8601):

CCYY-MM-DDThh:mm:ssTZD

Note that Active Support explicitly removes the Date#xmlschema method in Ruby 2.0, as it converts a date to a string without the time component.

active_support/core_ext/date/zones

in_time_zone

Converts Date object into a Ruby Time object in the current time zone. If Time.zone or Time.zone_default is not set, converts Date to a Time via #to_time.

>> Time.zone = "Eastern Time (US & Canada)"

=> "Eastern Time (US & Canada)"

>> Thu, 10 Oct 2013 00:00:00 EDT -04: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 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.

1 classDateTime

2 def acts_like_date?

3 true

4 end

5

6 def acts_like_time?

7 true

8 endd

9 end

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.

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.

at_beginning_of_day / at_midnight / beginning_of_day / midnight

Convenience method that represents the beginning of a day (00:00:00). Implemented simply as change(hour: 0).

at_beginning_of_hour / beginning_of_hour

Returns a new DateTime object representing the start of the hour (hh:00:00). Implemented simply as change(min: 0).

at_beginning_of_minute / beginning_of_minute

Returns a new DateTime object representing the start of the minute (hh:mm:00). Implemented simply as change(sec: 0).

at_end_of_day / 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).

at_end_of_hour / end_of_hour

Returns a new DateTime object representing the end of the hour (hh:59:59). Implemented simply as change(min: 59, sec: 59).

at_end_of_minute / end_of_minute

Returns a new DateTime object representing the end of the minute (hh:mm:59). Implemented simply as change(sec: 59).

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.

DateTime.current

Timezone-aware implementation of Time.now returns a DateTime instance.

future?

Tells whether the DateTime is in the future.

middle_of_day / noon

Returns a new DateTime object representing the middle of the day (12:00:00). Implemented simply as change(hour: 12).

past?

Tells whether the DateTime is in the past.

seconds_since_midnight

Returns how many seconds have passed since midnight.

seconds_until_end_of_day

Returns how many seconds left in the day until 23:59:59.

since(seconds) \ in(seconds)

Returns a new DateTime representing the time a number of seconds since the instance time (Aliased as in). 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.

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"

nsec

Returns the fraction of a second as nanoseconds.

readable_inspect

Overrides the default inspect method with a human-readable one that looks like this:

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

>> Date.new(2000, 4,4).to_datetime.to_f

=> 954806400.0

>> Date.new(1800, 4,4).to_datetime.to_f

=> -5356627200.0

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.

>> Date.new(2000, 4,4).to_datetime.to_i

=> 954806400

>> Date.new(1800, 4,4).to_datetime.to_i

=> -5356627200

usec

Returns the fraction of a second as microseconds.

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 class loading mechanism, which is what makes it possible to reference any constant in the Rails varied load paths 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:

1 moduleDependencies

2 extend self

3 ...

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/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_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 autoload_paths.

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

>> ActiveSupport::Dependencies.load_paths

=> ["/Users/kfaustino/code/active/example_app/app/assets",

"/Users/kfaustino/code/active/example_app/app/controllers",

"/Users/kfaustino/code/active/example_app/app/helpers",

"/Users/kfaustino/code/active/example_app/app/mailers",

"/Users/kfaustino/code/active/example_app/app/models",

"/Users/kfaustino/code/active/example_app/app/controllers/concerns",

"/Users/kfaustino/code/active/example_app/app/models/concerns"]

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.

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.

clear

Clear all loaded items.

constantize(name)

Gets the reference for a specified class name. Raises an exception if the class does not exist.

depend_on(file_name, message = "No such file to load -- %s.rb")

Searches for the file_name specified and uses require_or_load to establish a new dependency. If the file fails to load, a LoadError is raised. Setting message, one can replace the error message set by LoadError.

hook!

Includes Rails specific modules into some Ruby classes.

· Object includes Loadable

· Module includes ModuleConstMissing

· Exception includes Blamable

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(from_mod, const_name)

Loads the constant named const_name, which is missing from from_mod. If it is not possible to load the constant from from_mod, try its parent module by calling const_missing on it.

loadable_constants_for_path(path, bases = autoload_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.

reference(klass)

Store a reference to a class.

remove_constant(const)

Removes an explicit constant.

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.

safe_constantize(name)

Gets the reference for class named name if one exists.

search_for_file(path_suffix)

Searches for a file in the autoload paths matching the provided path_suffix.

to_constant_name(desc)

Convert the provided constant description to a qualified constant name.

will_unload?(constant)

Returns true if the specified constant is queued for unloading on the next request.

unhook!

Exclude module ModuleConstMissing from Module and Loadable from Object.

active_support/dependencies/autoload

This module allows you to define autoloads based on Rails conventions.

autoload(const_name, path = @_at_path)

Autoload a constant.

1 autoload :Model

autoload_under(path)

Set the name of a relative directory for all nested autoload declarations. For example, if the current file was action_controller.rb, and we call autoload_under("metal"), the path used to autoload from is action_controller/metal.

1 moduleActionController

2 extend ActiveSupport::Autoload

3

4 autoload_under "metal" do

5 autoload :Compatibility

6 ...

7 end

8 ...

9 end

autoload_at(path)

Sets an explicit path to autoload at.

1 moduleActionView

2 extend ActiveSupport::Autoload

3

4 autoload_at "action_view/template/resolver" do

5 autoload :Resolver

6 ...

7 end

8 ...

9 end

eager_autoload

Eagerly autoload any nested autoload declarations.

1 moduleActionMailer

2 extend ::ActiveSupport::Autoload

3

4 eager_autoload do

5 autoload :Collector

6 end

7 ...

8 end

eager_load!

Require each file defined in autoloads.

autoloads

Collection of files to be autoloaded.

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.

active_support/deprecation

Deprecation.behavior

Returns the current behavior or if one isn’t set, defaults to :stderr.

Deprecation.behavior=(behavior)

Sets the behavior to the specified value. Can be a single value, array, or an object that responds to call.

The following are available behaviors:

:stderr

Log all deprecation warnings to $stderr

:log

Log all deprecation warnings to Rails.logger.

:notify

Use ActiveSupport::Notifications to notify deprecation.rails.

:silence

Do nothing.

Deprecation.deprecation_warning(deprecated_method_name, message = nil, caller_backtrace = nil)

Outputs a deprecating warning for a specific method.

>> ActiveSupport::Deprecation.

deprecation_warning(:page_cache_extension, :default_static_extension)

=> "page_cache_extension is deprecated and will be removed from Rails 4.1

(use default_static_extension instead)"

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.

Deprecation.warn(message = nil, callstack = nil)

Outputs a deprecation warning to the output configured by ActiveSupport::Deprecation.behavior.

1 ActiveSupport::Deprecation.warn('something broke!')

2 # => "DEPRECATION WARNING: something broke! (called from your_code.rb:1)"

ActiveSupport::DescendantsTracker

A module used internally by Rails to track descendants, which is faster than iterating through ObjectSpace.

active_support/descendants_tracker

DescendantsTracker.clear

Clears all descendants.

DescendantsTracker.descendants(klass)

Returns a set of all the descendants of a class.

descendants

A convenience method for returning the descendants of a class. Implemented simply as DescendantsTracker.descendants(self).

DescendantsTracker.direct_descendants(klass)

Returns a set of the direct descendants of a class.

direct_descendants

A convenience method for returning the direct descendants of a class. Implemented simply as DescendantsTracker.direct_descendants(self).

inherited(base)

Sets a class as a direct descendant of another base class. Implemented simply as DescendantsTracker.store_inherited(base, self).

DescendantsTracker.store_inherited(klass, descendant)

Adds a direct descendant to a class. Warning this method is not thread safe, but is only called during the eager loading phase.

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.current)

Calculates a new Time or Date that is as far in the past as this Duration represents.

>> birth = 35.years.ago

=> Tue, 10 Oct 1978 16:21:34 EDT -04:00

from_now(time = Time.current)

Alias for since, which reads a little bit more naturally when using the default Time.current as the time argument.

>> expiration = 1.year.from_now

=> Fri, 10 Oct 2014 16:22:35 EDT -04: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

=> Fri, 10 Oct 2003 16:23:10 EDT -04:00

since(time = Time.current)

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.current)

Alias for ago. Reads a little more naturally when specifying a time argument instead of using the default value, Time.current.

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.

exclude?

The negative of the Enumerable#include?. Returns true if the collection does not include the object.

index_by(&block)

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

many?

Returns true if the enumerable has more than one element.

Use full block syntax to determine if there is more than one element based on a condition:

people.many? { |p| p.age > 26 }

sum(identity = 0, &block)

Calculates a sum from the elements of an enumerable, based on a block.

payments.sum(&:price)

It’s easier to understand than Ruby’s 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

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 ERB::Util.html_escape("is a > 0 & a < 10?")

=> "is a > 0 & a < 10?"

html_escape_once(s)

A utility method for escaping HTML without affecting existing escaped entities.

>> puts ERB::Util.html_escape_once('1 < 2 & 3')

=> "1 < 2 & 3"

json_escape(s)

A utility method for escaping HTML entities in JSON strings.

In your ERb templates, use this method to escape any HTML entities:

= json_escape @person.to_json

The method primarily escapes angle brackets and ampersands.

>> puts ERB::Util.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.

1 File.atomic_write("important.file") do |file|

2 file.write("hello")

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

1 File.atomic_write("/data/something.imporant", "/data/tmp") do |f|

2 file.write("hello")

3 end

Hash

active_support/core_ext/hash/compact

compact

Returns a hash with non nil values.

hash = { name: 'Marisa', email: nil }

=> hash.compact

>> { name: 'Marisa' }

compact!

Replaces current hash with non nil values.

active_support/core_ext/hash/conversions

Contains code that adds the ability to convert hashes to and from xml.

Hash.from_trusted_xml(xml)

Builds a Hash from XML just like Hash.from_xml, but also allows Symbol and YAML.

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.

1 >> xml = %(<people>

2 <person id="1">

3 <name><family>Boss</family> <given>Big</given></name>

4 <email>chief@foo.com</email>

5 </person>

6 <person id="2">

7 <name>

8 <family>Worker</family>

9 <given>Two</given></name>

10 <email>two@foo.com</email>

11 </person>

12 </people>)

13 => "<people>...</people>"

14

15 >> h = Hash.from_xml(xml)

16 => {"people"=>{"person"=>[{"name"=>{"given"=>"Big", "family"=>"Boss"},

17 "id"=>"1", "email"=>"chief@foo.com"}, {"name"=>{"given"=>"Two",

18 "family"=>"Worker"}, "id"=>"2", "email"=>"two@foo.com"}]}}

Now you can easily access the data from the XML:

>> h["people"]["person"].first["name"]["given"]

=> "Big"

An exception DisallowedType is raised if the XML contains attributes with type="yaml" or type="symbol".

to_xml(options={})

Collects the keys and values of a hash and composes a simple XML representation.

1 print ({greetings: {

2 english: "hello",

3 spanish: "hola"}}).to_xml

1 <?xml version="1.0" encoding="UTF-8"?>

2 <hash>

3 <greetings>

4 <english>hello</english>

5 <spanish>hola</spanish>

6 </greetings>

7 </hash>

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

deep_merge(other_hash)

active_support/core_ext/hash/except

except(*keys)

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

1 person.update(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.

>> {a: 1}.with_indifferent_access.except(:a)

=> {}

>> {a: 1}.with_indifferent_access.except("a")

=> {}

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.

1 def my_method(some_value, options={})

2 options.assert_valid_keys(:my_conditions, :my_order, ...)

3 ...

4 end

Note that keys are NOT treated indifferently, meaning if you use strings for keys but assert symbols as keys, this will fail.

>> { name: "Rob", years: "28" }.assert_valid_keys(:name, :age)

=> ArgumentError: Unknown key(s): years

>> { name: "Rob", age: "28" }.assert_valid_keys("name", "age")

=> ArgumentError: Unknown key(s): name, age

>> { name: "Rob", age: "28" }.assert_valid_keys(:name, :age)

=> {:name=>"Rob", :age=>"28"} # passes, returns hash

deep_stringify_keys

Return a copy of the hash with all keys converted to strings. This includes the keys from the root hash and from all nested hashes.

deep_stringify_keys!

Destructively converts all keys in the hash to strings. This includes the keys from the root hash and from all nested hashes.

deep_symbolize_keys

Returns a new hash with all keys converted to symbols, as long as they respond to to_sym. This includes the keys from the root hash and from all nested hashes.

deep_symbolize_keys!

Destructively converts all keys in the hash to symbols, as long as they respond to to_sym. This includes the keys from the root hash and from all nested hashes.

deep_transform_keys(&block)

Return a copy of the hash with all keys converted by the block operation. This includes the keys from the root hash and from all nested hashes.

deep_transform_keys!(&block)

Destructively converts all keys in the hash by the block operation. This includes the keys from the root hash and from all nested hashes.

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.

transform_keys(&block)

Return a copy of the hash with all keys converted by the block operation.

transform_keys!(&block)

Destructively converts all keys in the hash by the block operation.

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:

1 def setup(options = {})

2 options.reverse_merge! size: 25, velocity: 10

3 end

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

extract!(*keys)

Removes and returns the key/value pairs matching the given keys.

>> { a: 1, b: 2 }.extract!(:a, :x)

=> {:a => 1}

slice(*keys)

Slice a hash to include only the given keys. This is useful for limiting an options hash to valid keys before passing to a method:

1 def search(criteria = {})

2 assert_valid_keys(:mass, :velocity, :time)

3 end

4

5 search(options.slice(:mass, :velocity, :time))

If you have an array of keys you want to limit to, you should splat them:

1 valid_keys = %i(mass velocity time)

2 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).

>> { name: 'David', nationality: 'Danish' }.to_param

=> "name=David&nationality=Danish"

>> { name: 'David', nationality: 'Danish' }.to_param('user')

=> "user%5Bname%5D=David&user%5Bnationality%5D=Danish"

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?

ActiveSupport::Gzip

A wrapper for the zlib standard library that allows the compression/decompression of strings with gzip.

active_support/gzip

Gzip.compress(source, level=Zlib::DEFAULT_COMPRESSION, strategy=Zlib::DEFAULT_STRATEGY)

Compresses a string with gzip.

>> gzip = ActiveSupport::Gzip.compress('compress me!')

=> "\x1F\x8B\b\x00\x9D\x18WR\x00\x03K\xCE\xCF-

(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"

Gzip.decompress(source)

Decompresses a string that has been compressed with gzip.

>> ActiveSupport::Gzip.

decompress("\x1F\x8B\b\x00\x9D\x18WR\x00\x03K\xCE\xCF-

(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00")

=> "compress me!"

ActiveSupport::HashWithIndifferentAccess

A subclass of Hash used internally by Rails.

active_support/hash_with_indifferent_access

Implements a hash where keys set as a string or symbol are considered to be the same.

>> hash = HashWithIndifferentAccess.new

=> {}

>> hash[:foo] = "bar"

=> "bar"

>> hash[:foo]

=> "bar"

>> hash["foo"]

=> "bar"

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.

1 moduleActiveSupport

2 Inflector.inflections(:en) do |inflect|

3 inflect.plural(/$/, 's')

4 inflect.plural(/s$/i, 's')

5 inflect.plural(/^(ax|test)is$/i, '\1es')

6 inflect.plural(/(octop|vir)us$/i, '\1i')

7 inflect.plural(/(octop|vir)i$/i, '\1i')

8 inflect.plural(/(alias|status)$/i, '\1es')

9 inflect.plural(/(bu)s$/i, '\1ses')

10 inflect.plural(/(buffal|tomat)o$/i, '\1oes')

11 inflect.plural(/([ti])um$/i, '\1a')

12 inflect.plural(/([ti])a$/i, '\1a')

13 inflect.plural(/sis$/i, 'ses')

14 inflect.plural(/(?:([^f])fe|([lr])f)$/i, '\1\2ves')

15 inflect.plural(/(hive)$/i, '\1s')

16 inflect.plural(/([^aeiouy]|qu)y$/i, '\1ies')

17 inflect.plural(/(x|ch|ss|sh)$/i, '\1es')

18 inflect.plural(/(matr|vert|ind)(?:ix|ex)$/i, '\1ices')

19 inflect.plural(/^(m|l)ouse$/i, '\1ice')

20 inflect.plural(/^(m|l)ice$/i, '\1ice')

21 inflect.plural(/^(ox)$/i, '\1en')

22 inflect.plural(/^(oxen)$/i, '\1')

23 inflect.plural(/(quiz)$/i, '\1zes')

24

25 inflect.singular(/s$/i, '')

26 inflect.singular(/(ss)$/i, '\1')

27 inflect.singular(/(n)ews$/i, '\1ews')

28 inflect.singular(/([ti])a$/i, '\1um')

29 inflect.singular(/((a)naly|(b)a|(d)iagno|(p)arenthe|

30 (p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '\1sis')

31 inflect.singular(/(^analy)(sis|ses)$/i, '\1sis')

32 inflect.singular(/([^f])ves$/i, '\1fe')

33 inflect.singular(/(hive)s$/i, '\1')

34 inflect.singular(/(tive)s$/i, '\1')

35 inflect.singular(/([lr])ves$/i, '\1f')

36 inflect.singular(/([^aeiouy]|qu)ies$/i, '\1y')

37 inflect.singular(/(s)eries$/i, '\1eries')

38 inflect.singular(/(m)ovies$/i, '\1ovie')

39 inflect.singular(/(x|ch|ss|sh)es$/i, '\1')

40 inflect.singular(/^(m|l)ice$/i, '\1ouse')

41 inflect.singular(/(bus)(es)?$/i, '\1')

42 inflect.singular(/(o)es$/i, '\1')

43 inflect.singular(/(shoe)s$/i, '\1')

44 inflect.singular(/(cris|test)(is|es)$/i, '\1is')

45 inflect.singular(/^(a)x[ie]s$/i, '\1xis')

46 inflect.singular(/(octop|vir)(us|i)$/i, '\1us')

47 inflect.singular(/(alias|status)(es)?$/i, '\1')

48 inflect.singular(/^(ox)en/i, '\1')

49 inflect.singular(/(vert|ind)ices$/i, '\1ex')

50 inflect.singular(/(matr)ices$/i, '\1ix')

51 inflect.singular(/(quiz)zes$/i, '\1')

52 inflect.singular(/(database)s$/i, '\1')

53

54 inflect.irregular('person', 'people')

55 inflect.irregular('man', 'men')

56 inflect.irregular('child', 'children')

57 inflect.irregular('sex', 'sexes')

58 inflect.irregular('move', 'moves')

59 inflect.irregular('zombie', 'zombies')

60

61 inflect.uncountable(%w(equipment information rice money species

62 series fish sheep jeans police))

63 end

64 end

A singleton instance of Inflections is yielded by Inflector.inflections, which can then be used to specify additional inflection rules in an initializer.

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.plural /^(ox)$/i, '\1en'

3 inflect.singular /^(ox)en/i, '\1'

4 inflect.irregular 'person', 'people'

5 inflect.uncountable %w( fish sheep )

6 end

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.

acronym(word)

Specifies a new acronym. An acronym must be specified as it will appear in a camelized string. An underscore string that contains the acronym will retain the acronym when passed to camelize, humanize, or titleize. A camelized string that contains the acronym will maintain the acronym when titleized or humanized, and will convert the acronym into a non-delimited single lowercase word when passed to underscore. An acronym word must start with a capital letter.

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.acronym 'HTML'

3 end

4

5 >> 'html'.titleize

6 => "HTML"

7

8 >> 'html'.camelize

9 => "HTML"

10

11 >> 'MyHTML'.underscore

12 => "my_html"

The acronym must occur as a delimited unit and not be part of another word for conversions to recognize it:

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.acronym 'HTTP'

3 end

4

5 >> 'HTTPS'.underscore

6 => "http_s" # => 'http_s', not 'https'

7

8 # Alternatively

9 ActiveSupport::Inflector.inflections(:en) do |inflect|

10 inflect.acronym 'HTTPS'

11 end

12

13 >> 'HTTPS'.underscore

14 => "https"

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.

1 ActiveSupport::Inflector.inflections.clear

2 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”)

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.human /_cnt$/i, '\1_count'

3 inflect.human "legacy_col_person_name", "Name"

4 end

inflections(locale = :en)

Yields a singleton instance of ActiveSupport::Inflector::Inflections so you can specify additional inflector rules. If passed an optional locale, rules for other languages can be specified.

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.uncountable "rails"

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

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.irregular 'octopus', 'octopi'

3 inflect.irregular 'person', 'people'

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

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.plural /^(ox)$/i, '\1en'

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

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.singular /^(ox)en/i, '\1'

3 end

uncountable(*words)

Adds uncountable words that should not be inflected to the list of inflection rules.

1 ActiveSupport::Inflector.inflections(:en) do |inflect|

2 inflect.uncountable "money"

3 inflect.uncountable "money", "information"

active_support/inflector/transliterate

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.

1 classPerson < ActiveRecord::Base

2 def to_param

3 "#{id}-#{name.parameterize}"

4 end

5 end

6

7 >> @person = Person.find(1)

8 => #<Person id: 1, name: "Donald E. Knuth">

9

10 >> helper.link_to(@person.name, person_path(@person))

11 => <a href="/person/1-donald-e-knuth">Donald E. Knuth</a>

transliterate(string, replacement = "?")

Replaces non-ASCII characters with an ASCII approximation, or if none exists, a replacement character which defaults to “?”.

1 transliterate("Ærøskøbing")

2 # => "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 i18n.transliterate.rule i18n key:

1 # Store the transliterations in locales/de.yml

2 i18n:

3 transliterate:

4 rule:

5 ü: "ue"

6 ö: "oe"

1 # Or set them using Ruby

2 I18n.backend.store_translations(:de, i18n: {

3 transliterate: {

4 rule: {

5 "ü" => "ue",

6 "ö" => "oe"

7 }

8 }

9 })

The value for i18n.transliterate.rule can be a simple Hash that maps characters to ASCII approximations as shown above, or, for more complex requirements, a Proc:

1 I18n.backend.store_translations(:de, i18n: {

2 transliterate: {

3 rule: ->(string) { MyTransliterator.transliterate(string) }

4 }

5 })

Now you can have different transliterations for each locale:

1 I18n.locale = :en

2 transliterate("Jürgen")

3 # => "Jurgen"

1 I18n.locale = :de

2 transliterate("Jürgen")

3 # => "Juergen"

Integer

Extensions to Ruby’s built-in Integer class.

active_support/core_ext/integer/inflections

ordinal

Returns the suffix used to denote the position in an ordered sequence, such as 1st, 2nd, 3rd, 4th.

1 1.ordinal # => "st"

2 2.ordinal # => "nd"

3 1002.ordinal # => "nd"

4 1003.ordinal # => "rd"

ordinalize

Turns an integer into an ordinal string used to denote the position in an ordered sequence, such as 1st, 2nd, 3rd, 4th.

1 1.ordinalize # => "1st"

2 2.ordinalize # => "2nd"

3 1002.ordinalize # => "1002nd"

4 1003.ordinalize # => "1003rd"

active_support/core_ext/integer/multiple

multiple_of?(number)

Returns true if the integer is a multiple of number.

1 9.multiple_of? 3 # => true

ActiveSupport::JSON

The JSON module adds JSON decoding and encoding support to Rails which takes advantage of the JSON gem.

active_support/json/decoding

decode(json)

Parses a JSON string or IO object and converts it into a hash.

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 the debugger gem has been loaded. Use rails server --debugger to start Rails with the debugger enabled.

active_support/core_ext/kernel/reporting

capture(stream)

Captures the given stream and returns it.

1 stream = capture(:stdout) { puts 'notice' }

2 stream # => "notice\n"

enable_warnings

Sets $VERBOSE to true for the duration of the block provided and back to its original value afterward.

quietly(&block)

Silences both STDOUT and STDERR, even for subprocesses.

silence_stream(stream)

Silences any stream for the duration of the block provided.

1 silence_stream(STDOUT) do

2 puts 'This will never be seen'

3 end

4

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

A method 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/singleton_class

class_eval

Forces class_eval to behave like singleton_class.class_eval.

ActiveSupport::KeyGenerator

active_support/key_generator

initialize(secret, options = {})

Creates a new instance of MessageEncryptor.

generate_key(salt, key_size=64)

Returns a derived key suitable for use. The default key_size is chosen to be compatible with the default settings of ActiveSupport::MessageVerifier, such as OpenSSL::Digest::SHA1#block_length.

>> key_generator = ActiveSupport::KeyGenerator.new('my_secret_key')

=> #<ActiveSupport::KeyGenerator:0x007fde6788b5d8

@secret="my_secret_key", @iterations=65536>

>> key_generator.generate_key('my_salt')

=> "\xB6o5\xB2v\xBA\x03\x8E\xE0\xA0\x06[7<>\x81\xBB\xD6B\xB6,

\xF3@a\x153\xB5\xC1\x8C\x8B\xEF\x04\x1C\xB9\x8D\x93I~`\

xCD\xCB\"IKw\\u\xE9v\x15\xEEl\x99\"\xBD\xC7a\x92Y\x1EY\x94d\xFB"

ActiveSupport::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, “Rails Environments and Configuration”.

active_support/logger

Logger.broadcast(logger)

Generates an anonymous module, that is used to extend an existing logger, which adds the behavior to broadcast to multiple loggers. For instance, when initializing a Rails console, Rails.logger is extended to broadcast to STDERR, causing Rails to log to both a log file and STDERR.

1 console = ActiveSupport::Logger.new(STDERR)

2 Rails.logger.extend ActiveSupport::Logger.broadcast(console)

active_support/logger_silence

silence(temporary_level = Logger::ERROR, &block)

Silences the logger for the duration of the block.

ActiveSupport::MessageEncryptor

MessageEncryptor is a simple way to encrypt values which 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, *signature_key_or_options)

Creates a new instance of MessageEncryptor. The supplied secret must be at least as long as the cipher key size. By default, the cipher is aes-256-cbc, which would require a cipher key size of at least 256 bits. If you are using a user-entered secret, you can generate a suitable key withOpenSSL::Digest::SHA256.new(user_secret).digest.

Available options are:

:cipher

The cipher to use. Can be any cipher returned by

OpenSSL::Cipher.ciphers

Default is ‘aes-256-cbc’

:serializer

Object serializer to use (Default is Marshal).

encrypt_and_sign(value)

Encrypt and sign a value. The value needs to be signed to avoid padding attacks.

decrypt_and_verify(value)

Decrypts and verifies a value. The value needs to be verified to avoid padding attacks.

ActiveSupport::MessageVerifier

MessageVerifier makes it easy to generate and verify signed messages to prevent tampering.

>> v = ActiveSupport::MessageVerifier.new("A_SECRET_STRING")

=> #<ActiveSupport::MessageVerifier:0x007fde68036918

@secret="A_SECRET_STRING", @digest="SHA1", @serializer=Marshal>

>> msg = v.generate([1, 2.weeks.from_now])

=> "BAhbB2kGVTogQWN0aXZlU3VwcG9ydDo..."

>> id, time = v.verify(msg)

=> [1, Fri, 25 Oct 2013 18:03:27 UTC +00:00]

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, options = {})

Creates a new MessageVerifier with the supplied secret.

Available options are:

:digest

Default is ‘SHA1’.

:serializer

Object serializer to use (Default is Marshal).

generate(value)

Generate a signed message.

cookies[:remember_me] = verifier.generate([user.id, 2.weeks.from_now])

verify(signed_message)

Verify a signed message.

1 id, time = @verifier.verify(cookies[:remember_me])

2 if time < Time.now

3 self.current_user = User.find(id)

4 end

Module

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:

1 classContent < ActiveRecord::Base

2 # has column named 'title'

3 end

4

5 classEmail < Content

6 alias_attribute :subject, :title

7 end

As a result of the alias_attribute, you can see in the following example that the title and subject attributes become interchangeable:

>> e = Email.find(:first)

>> e.title

=> "Superstars"

>> e.subject

=> "Superstars"

>> e.subject?

=> true

>> e.subject = "Megastars"

=> "Megastars"

>> e.title

=> "Megastars"

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

1 moduleM

2 end

3

4 >> M.name

5 => "M"

6

7 m = Module.new

8

9 >> m.name

10 => ""

or by an explicit assignment

1 m = Module.new

2

3 >> M = m # m gets a name here as a side-effect

4

5 >> m.name

6 => "M"

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

concerning(topic, &block)

Equivalent to defining an inline module within a class, having it extend ActiveSupport::Concern, and then mixing it into the class.

1 classFoo < ActiveRecord::Base

2 concerning :Bar do

3 included do

4 has_many :things

5 end

6

7 private

8

9 def baz

10 ...

11 end

12 end

13 end

concern(topic, &module_definition)

Shorthand form of defining an ActiveSupport::Concern.

1 concern :Bar do

2 ...

3 end

4

5 # equivalent to

6

7 moduleBar

8 extend ActiveSupport::Concern

9 ...

10 end

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:

1 classGreeter < ActiveRecord::Base

2 def hello

3 "hello"

4 end

5

6 def goodbye

7 "goodbye"

8 end

9 end

1 classFoo < ActiveRecord::Base

2 belongs_to :greeter

3 delegate :hello, to: :greeter

4 end

1 Foo.new.hello # => "hello"

2 Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c>

Multiple delegates to the same target are allowed:

1 classFoo < ActiveRecord::Base

2 belongs_to :greeter

3 delegate :hello, :goodbye, to: :greeter

4 end

1 Foo.new.goodbye # => "goodbye"

Methods can be delegated to instance variables, class variables, or constants by providing them as a symbols:

1 classFoo

2 CONSTANT_ARRAY = [0,1,2,3]

3 @@class_array = [4,5,6,7]

4

5 def initialize

6 @instance_array = [8,9,10,11]

7 end

8 delegate :sum, to: :CONSTANT_ARRAY

9 delegate :min, to: :@@class_array

10 delegate :max, to: :@instance_array

11 end

12

13 Foo.new.sum # => 6

14 Foo.new.min # => 4

15 Foo.new.max # => 11

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.

1 Person = Struct.new(:name, :address)

2

3 classInvoice < Struct.new(:client)

4 delegate :name, :address, to: :client, prefix: true

5 end

6

7 john_doe = Person.new("John Doe", "Vimmersvej 13")

8 invoice = Invoice.new(john_doe)

9 invoice.client_name # => "John Doe"

10 invoice.client_address # => "Vimmersvej 13"

It is also possible to supply a custom prefix.

1 classInvoice < Struct.new(:client)

2 delegate :name, :address, to: :client, prefix: :customer

3 end

4

5 invoice = Invoice.new(john_doe)

6 invoice.customer_name # => "John Doe"

7 invoice.customer_address # => "Vimmersvej 13"

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.

1 classFoo

2 attr_accessor :bar

3 def initialize(bar = nil)

4 @bar = bar

5 end

6 delegate :zoo, to: :bar

7 end

8

9 Foo.new.zoo # raises NoMethodError exception (you called nil.zoo)

10

11 classFoo

12 attr_accessor :bar

13 def initialize(bar = nil)

14 @bar = bar

15 end

16 delegate :zoo, to: :bar, allow_nil: true

17 end

18

19 Foo.new.zoo # returns nil

active_support/core_ext/module/deprecation

deprecate(*method_names)

Provides a deprecate class method to easily deprecate methods. Convenience wrapper for ActiveSupport::Deprecation.deprecate_methods(self, *method_names).

1 deprecate :foo

2 deprecate bar: 'message'

3 deprecate :foo, :bar, baz: 'warning!', qux: 'gone!'

active_support/core_ext/module/introspection

local_constants

Returns the constants that have been defined locally by this object and not in an ancestor.

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.

1 >> ActiveRecord::Validations.parent_name

2 => "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.

1 moduleM

2 moduleN

3 end

4 end

5 X = M::N

6

7 >> M.parents

8 => [Object]

9

10 >> M::N.parents

11 => [M, Object]

12

13 >> X.parents

14 => [M, Object]

active_support/core_ext/module/qualified_const

Extends the API for constants to be able to deal with relative qualified constant names.

qualified_const_defined?

Returns true if the qualified constant is defined, nil otherwise.

Object.qualified_const_defined?(“Math::PI”) # ⇒ true

>> Object.const_defined?("Math::PI")

NameError: wrong constant name Math::PI

>> Object.qualified_const_defined?("Math::PI")

=> true

qualified_const_get(path)

Returns the relative qualified constant given a path.

>> Object.qualified_const_get("Math::PI")

=> 3.141592653589793

qualified_const_set(path, value)

Sets a relative qualified constant.

>> Object.qualified_const_set("Math::Phi", 1.618034)

=> 1.618034

active_support/core_ext/module/reachable

reachable?

Returns true if a named module is reachable through its corresponding constant.

1 moduleM

2 end

3

4 M.reachable? # => true

However, since constants and modules are decoupled, modules can become unreachable.

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

=> M

>> orphan.reachable?

=> false

active_support/core_ext/module/remove_method

remove_possible_method(method)

Removes a method definition if it exists.

redefine_method(method, &block)

The method define_method in Ruby allows the definition of methods dynamically. However, define_method doesn’t check for the existence of the method beforehand, which issues a warning if it does exist. The method redefine_method resolves this by first removing the method definition if it exists, and internally calling define_method.

active_support/dependencies

const_missing(const_name)

The const_missing callback is invoked when Ruby can’t find a specified constant in the current scope, which is what makes Rails autoclass loading 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.

1 >> "The Perfect String".mb_chars.downcase.strip.normalize

2 => #<ActiveSupport::Multibyte::Chars:0x007ffdcac6f7d0

3 @wrapped_string="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:

1 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

1 classCharsForUTF32

2 def size

3 @wrapped_string.size / 4

4 end

5

6 defself.accepts?(string)

7 string.length % 4 == 0

8 end

9 end

10

11 ActiveSupport::Multibyte.proxy_class = CharsForUTF32

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.

capitalize

Converts the first character to uppercase and the remainder to lowercase.

>> 'über'.mb_chars.capitalize.to_s

=> "Über"

compose

Performs composition on all the characters.

decompose

Performs canonical decomposition on all the characters.

downcase

Converts characters in the string to lowercase.

>> 'VĚDA A VÝZKUM'.mb_chars.downcase.to_s

=> "věda a výzkum"

grapheme_length

Returns the number of grapheme clusters in the string.

limit(limit)

Limits the byte size of the string to a number of bytes without breaking characters.

method_missing(m, *a, &b)

Tries to forward all undefined methods to the enclosed string instance. Also responsible for making the bang (!) methods destructive, since a handler doesn’t have access to change an enclosed string instance.

normalize(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.

A normalization form can be one of the following:

· :c

· :kc

· :d

· :kd

Default is ActiveSupport::Multibyte::Unicode#default_normalization_form.

reverse

Reverses all characters in the string.

>> 'Café'.mb_chars.reverse.to_s

=> 'éfaC'

slice!(*args)

Works like like String’s slice!, with the exception that the items in the resulting list are Char instances instead of String.

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.

>> 'Café périferôl'.mb_chars.split(/é/).map { |part| part.upcase.to_s }

=> ["CAF", " P", "RIFERÔL"]

swapcase

Converts characters in the string to the opposite case.

>> "El Cañón".mb_chars.swapcase.to_s

=> "eL cAÑÓN"

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.

> "obie".mb_chars.tidy_bytes

=> #<ActiveSupport::Multibyte::Chars:0x007ffdcb76ecf8

@wrapped_string="obie">

active_support/multibyte/unicode

Contains methods handling Unicode strings.

Unicode.compose(codepoints)

Compose decomposed characters to the composed form.

Unicode.decompose(type, codepoints)

Decompose composed characters to the decomposed form. The type argument accepts :canonical or :compatability.

Unicode.downcase(string)

Converts a unicode string to lowercase.

Unicode.in_char_class?(codepoint, classes)

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

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 theActiveSupport::Multibyte.default_normalization_form attribute and is overridable in an initializer.

Unicode.pack_graphemes(unpacked)

Reverse operation of unpack_graphemes.

Unicode.reorder_characters(codepoints)

Re-order codepoints so the string becomes canonical.

Unicode.swapcase(string)

Swapcase on a unicode string.

Unicode.tidy_bytes(string, force = false)

Replaces all ISO-8859-1 or CP1252 characters by their UTF-8 equivalent resulting in a valid UTF-8 string.

Unicode.unpack_graphemes(string)

Unpack the string at grapheme boundaries. Returns a list of character lists.

>> ActiveSupport::Multibyte::Unicode.unpack_graphemes('ffff')

=> [[102], [102], [102], [102]]

>> ActiveSupport::Multibyte::Unicode.unpack_graphemes('Café')

=> [[67], [97], [102], [233]]

Unicode.upcase(string)

Converts a unicode string to uppercase.

NilClass

Remember 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".

ActiveSupport::Notifications

Notifications provides an instrumentation API for Ruby. To instrument an action in Ruby you just need to do:

1 ActiveSupport::Notifications.instrument(:render, extra: :information) do

2 render text: "Foo"

3 end

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:

1 @events = []

2

3 ActiveSupport::Notifications.subscribe do |*args|

4 @events << ActiveSupport::Notifications::Event.new(*args)

5 end

6

7 ActiveSupport::Notifications.instrument(:render, extra: :information) do

8 render text: "Foo"

9 end

10

11 event = @events.first

12 event.name # => :render

13 event.duration # => 10 (in miliseconds)

14 event.result # => "Foo"

15 event.payload # => { :extra => :information }

When subscribing to Notifications, you can pass a pattern, to only consume events that match the pattern:

1 ActiveSupport::Notifications.subscribe(/render/) do |event|

2 @render_events << event

3 end

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/core_ext/numeric/bytes

Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes.

Constants

The following constants are defined in bytes.rb.

1 classNumeric

2 KILOBYTE = 1024

3 MEGABYTE = KILOBYTE * 1024

4 GIGABYTE = MEGABYTE * 1024

5 TERABYTE = GIGABYTE * 1024

6 PETABYTE = TERABYTE * 1024

7 EXABYTE = PETABYTE * 1024

8 ...

9 end

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

Returns self * 1024.petabytes.

active_support/core_ext/numeric/conversions

to_formatted_s(format = :default, options = {})

Generates a formatted string representation of a number. Options are provided for phone numbers, currency, percentage, precision, positional notation, file size and pretty printing.

Aliased as to_s.

:currency

Formats a number into a currency string. The :currency formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to ",".

:format

Sets the format for non-negative numbers, defaults to "%u%n".

:locale

Sets the locale to be used for formatting, defaults to current locale.

:negative_format

Sets the format for negative numbers, defaults to prepending an hyphen to the formatted number.

:precision

Sets the level of precision, defaults to 2.

:separator

Sets the separator between the units, defaults to ".".

:unit

Sets the denomination of the currency, defaults to "$".

>> 1234567890.50.to_s(:currency)

=> $1,234,567,890.50

>> 1234567890.506.to_s(:currency)

=> $1,234,567,890.51

>> 1234567890.506.to_s(:currency, precision: 3)

=> $1,234,567,890.506

>> 1234567890.506.to_s(:currency, locale: :fr)

=> 1 234 567 890,51 €

>> -1234567890.50.to_s(:currency, negative_format: '(%u%n)')

=> ($1,234,567,890.50)

>> 1234567890.50.to_s(:currency, unit: '£', separator: ',',

delimiter: '')

=> £1234567890,50

:delimited

Formats a number with grouped thousands using delimiter. The :delimited formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to ",".

:locale

Sets the locale to be used for formatting, defaults to current locale.

:separator

Sets the separator between the units, defaults to ".".

>> 12345678.to_s(:delimited)

=> 12,345,678

>> 12345678.05.to_s(:delimited)

=> 12,345,678.05

>> 12345678.to_s(:delimited, delimiter: '.')

=> 12.345.678

:human

Formats a number that is more readable to humans. Useful for numbers that are extremely large.The :human formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to "".

:format

Sets the format for non-negative numbers, defaults to "%n %u". The field types are:

· %u: The quantifier

· %n: The number

:locale

Sets the locale to be used for formatting, defaults to current locale.

:precision

Sets the level of precision, defaults to 3.

:separator

Sets the separator between fractional and integer digits, defaults to ".".

:significant

If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to true.

:strip_insignificant_zeros

Setting to true removes insignificant zeros after the decimal separator, defaults to true.

:units

A hash of unit quantifier names, or a string containing an i18n scope where to find this hash. It might have the following keys:

· integers: :unit, :ten, *:hundred, :thousand, :million, *:billion, :trillion, *:quadrillion

· fractionals: :deci, :centi, *:mili, :micro, :nano, *:pico, :femto

>> 123.to_s(:human)

=> "123"

>> 1234.to_s(:human)

=> "1.23 Thousand"

>> 1234567.to_s(:human)

=> "1.23 Million"

>> 489939.to_s(:human, precision: 4)

=> "489.9 Thousand"

:human_size

Formats the bytes in size into a more understandable representation. Useful for reporting file sizes to users. The :human_size formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to "".

:format

Sets the format for non-negative numbers, defaults to "%u%n".

:locale

Sets the locale to be used for formatting, defaults to current locale.

:precision

Sets the level of precision, defaults to 3.

:prefix

Setting to :si formats the number using the SI prefix, defaults to :binary.

:separator

Sets the separator between fractional and integer digits, defaults to ".".

:significant

If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to true.

:strip_insignificant_zeros

Setting to true removes insignificant zeros after the decimal separator, defaults to true.

:raise

Setting to true raises InvalidNumberError when the number is invalid.

1 >> 123.to_s(:human_size)

2 => 123 Bytes

3

4 >> 1234.to_s(:human_size)

5 => 1.21 KB

6

7 >> 12345.to_s(:human_size)

8 => 12.1 KB

9

10 >> 1234567.to_s(:human_size)

11 => 1.18 MB

12

13 >> 1234567.to_s(:human_size, precision: 2)

14 => 1.2 MB

:percentage

Formats a number as a percentage string. The :percentage formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to "".

:format

Sets the format of the percentage string, defaults to "%n%".

:locale

Sets the locale to be used for formatting, defaults to current locale.

:precision

Sets the level of precision, defaults to 3.

:separator

Sets the separator between the units, defaults to "."

:significant

If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to false.

:strip_insignificant_zeros

Setting to true removes insignificant zeros after the decimal separator, defaults to false.

>> 100.to_s(:percentage)

=> 100.000%

>> 100.to_s(:percentage, precision: 0)

=> 100%

>> 1000.to_s(:percentage, delimiter: '.', separator: ',')

=> 1.000,000%

>> 302.24398923423.to_s(:percentage, precision: 5)

=> 302.24399%

>> 1000.to_s(:percentage, locale: :fr)

=> 1 000,000%

>> 100.to_s(:percentage, format: '%n %')

=> 100 %

:phone

Formats a number into a US phone number. The :phone formatting option can be combined with the following:

:area_code

Adds parentheses around the area code.

:country_code

Sets the country code for the phone number.

:delimiter

Specifies the delimiter to use, defaults to "-".

:extension

Specifies an extension to add to the end of the generated number.

>> 5551234.to_s(:phone)

=> 555-1234

>> 1235551234.to_s(:phone)

=> 123-555-1234

>> 1235551234.to_s(:phone, area_code: true)

=> (123) 555-1234

>> 1235551234.to_s(:phone, delimiter: ' ')

=> 123 555 1234

>> 1235551234.to_s(:phone, area_code: true, extension: 555)

=> (123) 555-1234 x 555

>> 1235551234.to_s(:phone, country_code: 1)

=> +1-123-555-1234

>> 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.')

=> +1.123.555.1234 x 1343

:round

Formats a number with the specified level of precision.The :rounded formatting option can be combined with the following:

:delimiter

Sets the thousands delimiter, defaults to "".

:locale

Sets the locale to be used for formatting, defaults to current locale.

:precision

Sets the level of precision, defaults to 3.

:separator

Sets the separator between the units, defaults to ".".

:significant

If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to false.

:strip_insignificant_zeros

Setting to true removes insignificant zeros after the decimal separator, defaults to false.

>> 111.2345.to_s(:rounded)

=> 111.235

>> 111.2345.to_s(:rounded, precision: 2)

=> 111.23

>> 13.to_s(:rounded, precision: 5)

=> 13.00000

>> 389.32314.to_s(:rounded, precision: 0)

=> 389

>> 111.2345.to_s(:rounded, significant: true)

=> 111

>> 111.2345.to_s(:rounded, precision: 1, significant: true)

=> 100

active_support/core_ext/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:

1 # equivalent to Time.now.advance(months: 1)

2 1.month.from_now

3

4 # equivalent to Time.now.advance(years: 2)

5 2.years.from_now

6

7 # equivalent to Time.now.advance(months: 4, years: 5)

8 (4.months + 5.years).from_now

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:

1 # equivalent to 30.days.to_i.from_now

2 1.month.to_i.from_now

3

4 # equivalent to 365.25.days.to_f.from_now

5 1.year.to_f.from_now

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.

1 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.current) / since(time = Time.current)

An amount of time in the future, from a specified time (which defaults to Time.current).

hour / hours

A duration equivalent to self * 3600.seconds.

in_milliseconds

An equivalent to self * 1000. This value can be set in JavaScript functions like getTime().

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

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:

state = params[:state] if params[:state].present?

country = params[:country] if params[:country].present?

region = state || country || 'US'

becomes

region = params[:state].presence || params[:country].presence || 'US'

present?

An object is present if it’s not blank.

active_support/core_ext/object/deep_dup

Returns a deep copy of object if it’s duplicable. If it’s not duplicable, returns self.

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

in?(object)

Returns true if this object is included in the argument. The argument must respond to include?.

1 characters = %w(Hulk Thor Hawkeye)

2

3 >> "Thor".in?(characters)

4 => true

active_support/core_ext/object/instance_variables

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.

1 classC

2 def initialize(x, y)

3 @x, @y = x, y

4 end

5 end

6

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

instance_variable_names

Returns an array of instance variable names including “@”.

1 classC

2 def initialize(x, y)

3 @x, @y = x, y

4 end

5 end

6

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

active_support/core_ext/object/json

to_json

A basic definition of to_json which prevents calls to to_json from going directly to the json gem on the following core classes:

· Object

· Array

· FalseClass

· Float

· Hash

· Integer

· NilClass

· String

· TrueClass

active_support/core_ext/object/to_param

to_param

Alias of to_s.

active_support/core_ext/object/to_query

to_query(key)

Converts an object into a string suitable for use as a URL query string, using the given key as the param name.

active_support/core_ext/object/try

try(*a, &block)

Attempts to call a public method whose name is the first argument. Unlike public_send, if the object does not respond to the method, nil is returned rather than an exception being raised.

This simplifies:

@person ? @person.name : nil

to

@person.try(:name)

If try is invoked without arguments, it yields the receiver unless it’s nil.

@person.try do |p|

...

end

Arguments and blocks are forwarded to the method if invoked:

@posts.try(:each_slice, 2) do |a, b|

...

end

active_support/core_ext/object/with_options

with_options(options)

An elegant way to refactor out common options.

1 classPost < ActiveRecord::Base

2 with_options(dependent: :destroy) do |post|

3 post.has_many :comments

4 post.has_many :photos

5 end

6 end

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_dependency(file_name, file_name, message = "No such file to load -- %s")

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.

ActiveSupport::OrderedHash

active_support/ordered_hash

A hash implementation that preserves the ordering of its elements. 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:

>> oh = ActiveSupport::OrderedHash.new

=> []

>> oh[:one] = 1

=> 1

>> oh[:two] = 2

=> 2

>> oh[:three] = 3

=> 3

>> oh

=> [[:one, 1], [:two, 2], [:three, 3]]

Note that as of Ruby 1.9, hashes preserve their insertion order.

ActiveSupport::OrderedOptions

active_support/ordered_options

A subclass of Hash that adds a method-missing implementation so that hash elements can be accessed and modified using normal attribute semantics, dot-notation:

1 def method_missing(name, *args)

2 if name.to_s =~ /(.*)=$/

3 self[$1.to_sym] = args.first

4 else

5 self[name]

6 end

7 end

ActiveSupport::PerThreadRegistry

active_support/per_thread_registry

A module that encapsulates access to thread local variables, which prevents the polluting of the thread locals namespace. Instead of setting and getting variables via Thread.current:

Thread.current[:handler]

you can define a class that extends ActiveSupport::PerThreadRegistry.

1 classRegistry

2 extend ActiveSupport::PerThreadRegistry

3

4 attr_accessor :handler

5 end

This creates class level methods to get/set attributes on the current thread based on the defined accessors.

>> Registry.handler

=> nil

>> Registry.handler = handler

=> #<Object:0x007fbeb326ea20>

>> Registry.handler

=> #<Object:0x007fbeb326ea20>

The key on Thread.current for the above example would be the class name “Registry”.

>> Thread.current["Registry"]

=> #<Registry:0x007fbeb3279880 @handler=#<Object:0x007fbeb326ea20>>

ActiveSupport::ProxyObject

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

The implementation of ProxyObject inherits from BasicObject, and un-defines two methods, and allows exceptions to be raised. The implementation is reproduced here for your reference.

1 classProxyObject < ::BasicObject

2 undef_method :==

3 undef_method :equal?

4

5 # Let ActiveSupport::ProxyObject at least raise exceptions.

6 def raise(*args)

7 ::Object.send(:raise, *args)

8 end

9 end

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.

1 moduleActiveSupport

2 classRailtie < Rails::Railtie # :nodoc:

3 config.active_support = ActiveSupport::OrderedOptions.new

4

5 config.eager_load_namespaces << ActiveSupport

6

7 initializer "active_support.deprecation_behavior" do |app|

8 if deprecation = app.config.active_support.deprecation

9 ActiveSupport::Deprecation.behavior = deprecation

10 end

11 end

12

13 # Sets the default value for Time.zone

14 # If assigned value cannot be matched to a TimeZone, an exception will be raised.

15 initializer "active_support.initialize_time_zone" do |app|

16 require 'active_support/core_ext/time/zones'

17 zone_default = Time.find_zone!(app.config.time_zone)

18

19 unless zone_default

20 raise 'Value assigned to config.time_zone not recognized. ' \

21 'Run "rake -D time" for a list of tasks for finding appropriate time zone names.'

22 end

23

24 Time.zone_default = zone_default

25 end

26

27 # Sets the default week start

28 # If assigned value is not a valid day symbol

29 # (e.g. :sunday, :monday, ...), an exception will be raised.

30 initializer "active_support.initialize_beginning_of_week" do |app|

31 require 'active_support/core_ext/date/calculations'

32 beginning_of_week_default = Date.

33 find_beginning_of_week!(app.config.beginning_of_week)

34

35 Date.beginning_of_week_default = beginning_of_week_default

36 end

37

38 initializer "active_support.set_configs" do |app|

39 app.config.active_support.each do |k, v|

40 k = "#{k}="

41 ActiveSupport.send(k, v) if ActiveSupport.respond_to? k

42 end

43 end

44 end

45 end

Range

Extensions to Ruby’s Range class.

active_support/core_ext/range/conversions

to_formatted_s(format = :default)

Generates a formatted string representation of the range.

>> (20.days.ago..10.days.ago).to_formatted_s

=> "Fri Aug 10 22:12:33 -0400 2007..Mon Aug 20 22:12:33 -0400 2007"

>> (20.days.ago..10.days.ago).to_formatted_s(:db)

=> "BETWEEN '2007-08-10 22:12:36' AND '2007-08-20 22:12:36'"

active_support/core_ext/range/each

For internal use by Rails. Disables the ability to iterate over a range of ActiveSupport::TimeWithZone due to significant performance issues.

active_support/core_ext/range/include_range

include?(value)

Extends the default Range#include? to support range comparisons.

>> (1..5).include?(1..5)

=> true

>> (1..5).include?(2..3)

=> true

>> (1..5).include?(2..6)

=> false

The native include? behavior is untouched.

>> ("a".."f").include?("c")

=> true

>> (5..9).include?(11)

=> false

active_support/core_ext/range/overlaps

overlaps?(other)

Compare two ranges and see if they overlap each other

>> (1..5).overlaps?(4..6)

=> true

>> (1..5).overlaps?(7..9)

=> false

active_support/core_ext/enumerable

sum(identity = 0)

Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.

Regexp

Extensions to Ruby’s Regexp class.

active_support/core_ext/regexp

multiline?

Returns true if a multiline regular expression.

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.

1 classApplicationController < ActionController::Base

2 rescue_from User::NotAuthorized, with: :deny_access

3 rescue_from ActiveRecord::RecordInvalid, with: :show_errors

4

5 rescue_from 'MyAppError::Base' do |exception|

6 render xml: exception, status: 500

7 end

8

9 protected

10 def deny_access

11 ...

12 end

13

14 def show_errors(exception)

15 exception.record.new? ? ...

16 end

17 end

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.

1 classString

2 def blank?

3 self !~ /\S/

4 end

5 end

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.

>> "hello".at(0)

=> "h"

>> "hello".at(4)

=> "o"

>> "hello".at(10)

=> nil

first(number)

Returns the first number of characters in a string.

1 "hello".first # => "h"

2 "hello".first(2) # => "he"

3 "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.

1 "hello".at(0) # => "hello"

2 "hello".at(2) # => "llo"

3 "hello".at(10) # => nil

last(number)

Returns the last number of characters in a string.

1 "hello".last # => "o"

2 "hello".last(2) # => "lo"

3 "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.

1 "hello".at(0) # => "h"

2 "hello".at(2) # => "hel"

3 "hello".at(10) # => "hello"

active_support/core_ext/string/behavior

Duck-types as a String-like class. See Object#acts_like? for more explanation.

1 classString

2 def acts_like_time?

3 true

4 end

5 end

active_support/core_ext/string/conversions

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

Uses Date.parse to turn a string into a Time either using either :utc or :local (default).

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

remove(pattern)

A convenience method for gsub(pattern, ''). It returns a new string with all occurrences of the pattern removed.

remove!(pattern)

Performs a destructive remove. See remove.

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.

>> %{ Multi-line

string }.squish

=> "Multi-line string"

>> " foo bar \n \t boo".squish

=> "foo bar boo"

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.

>> "Once upon a time in a world far far away".truncate(30)

=> "Once upon a time in a world..."

>> "Once upon a time in a world far far away".truncate(30, separator: ' ')

=> "Once upon a time in a world..."

>> "Once upon a time in a world far far away".truncate(14)

=> "Once upon a..."

>> "And they found that many people were sleeping better.".

truncate(25, omission: "... (continued)")

=> "And they f... (continued)"

active_support/core_ext/string/indent

indent(amount, indent_string=nil, indent_empty_lines=false)

Indents a string by the given amount.

>> "foo".indent(2)

=> " foo"

=> "foo\nbar"

>> " foo\n bar"

The second argument indent_string specifies what indent string to use. If no indent_string is specified, it will use the first indented line, otherwise a space is used. If indent_empty_lines is set to true, empty lines will also be indented.

indent!

Performs a destructive indent. See indent.

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 https://github.com/ged/linguistics 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.)

camelcase

Alias for camelize.

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.

>> "active_record".camelize

=> "ActiveRecord"

>> "active_record".camelize(:lower)

=> "activeRecord"

>> "active_record/errors".camelize

=> "ActiveRecord::Errors"

>> "active_record/errors".camelize(:lower)

=> "activeRecord::Errors"

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.

>> "ActiveRecord::CoreExtensions::String::Inflections".demodulize

=> "Inflections"

>> "Inflections".demodulize

=> "Inflections"

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(options = {})

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".humanize

=> "Employee salary"

>> "author_id".humanize

=> "Author"

Setting the :capitalize option to false results in the string being humanized without being capitalized.

>> "employee_salary".humanize(capitalize: false)

=> "employee salary"

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.

1 "post".pluralize # => "posts"

2 "octopus".pluralize # => "octopi"

3 "sheep".pluralize # => "sheep"

4 "words".pluralize # => "words"

5 "the blue mailman".pluralize # => "the blue mailmen"

6 "CamelOctopus".pluralize # => "CamelOctopi"

safe_constantize

The safe_constantize method tries to find a declared constant with the name specified in the string. It returns nil when the name is not in CamelCase or is not initialized.

singularize

The reverse of pluralize; returns the singular form of a word in a string.

1 "posts".singularize # => "post"

2 "octopi".singularize # => "octopus"

3 "sheep".singluarize # => "sheep"

4 "word".singluarize # => "word"

5 "the blue mailmen".singularize # => "the blue mailman"

6 "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.

1 "RawScaledScorer".tableize # => "raw_scaled_scorers"

2 "egg_and_ham".tableize # => "egg_and_hams"

3 "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”.

underscore

The reverse of camelize. Makes an underscored form from the expression in the string. Changes “::” to “/” to convert namespaces to paths.

1 "ActiveRecord".underscore # => "active_record"

2 "ActiveRecord::Errors".underscore # => active_record/errors

active_support/core_ext/string/inquiry

inquiry

Wraps the current string in the ActiveSupport::StringInquirer class, providing an elegant way to test for equality.

1 env = 'production'.inquiry

2 env.production? # => true

3 env.development? # => false

active_support/core_ext/string/multibyte

Defines a mutibyte safe proxy for string methods.

mb_chars

The mb_chars method 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.

>> name = 'Claus Müller'

>> name.reverse

=> "rell??M sualC"

>> name.length

=> 13

>> name.mb_chars.reverse.to_s

=> "rellüM sualC"

>> name.mb_chars.length

=> 12

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

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)

Alias for start_with?.

`ends_with?(suffix)

Alias for end_with?.

active_support/core_ext/string/strip

strip_heredoc

Strips indentation in heredocs. For example,

1 if options[:usage]

2 puts <<-USAGE.strip_heredoc

3 This command does such and such.

4

5 Supported options are:

6 -h This message

7 ...

8 USAGE

9 end

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

active_support/core_ext/string/in_time_zone

in_time_zone(zone = ::Time.zone)

Converts the string to a TimeWithZone in the current zone if Time.zone or Time.zone_default are set. Otherwise returns String#to_time.

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

Struct

Extensions to Ruby’s Struct class.

active_support/core_ext/struct

to_h

Backports of Struct#to_h from Ruby 2.0 unless defined.

ActiveSupport::Subscriber

The ActiveSupport::Subscriber object is used to consume ActiveSupport::Notifications. The subscriber dispatches notifications to a registered object based on its given namespace.

For example, a subscriber could collect statistics about Active Record queries:

1 moduleActiveRecord

2 classStatsSubscriber < ActiveSupport::Subscriber

3 def sql(event)

4 Statsd.timing("sql.#{event.payload[:name]}", event.duration)

5 end

6 end

7 end

To attach a subscriber to a namespace, use the attach_to method.

1 ActiveRecord::StatsSubscriber.attach_to :active_record

Symbol

Extensions to Ruby’s Symbol class.

active_support/json/encoding

as_json

Returns to_s version of itself.

ActiveSupport::TaggedLogging

Wraps any standard Logger object to provide tagging capabilities.

active_support/tagged_logger

flush

Clear all tags and invoke the parent definition if it exists.

tagged(*tags, &block)

Prefix tags to each log message in the yielded block.

1 logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))

2 logger.tagged("tr4w") { logger.info "Stuff" } # [tr4w] Stuff

ActiveSupport::TestCase

Inheriting from MiniTest::Unit::TestCase, adds Rails specific testing methods and behavior.

active_support/test_case

assert_no_match

Alias for refute_match for Test::Unit backwards compatibility.

assert_not_empty

Alias for refute_empty for Test::Unit backwards compatibility.

assert_not_equal

Alias for refute_equal for Test::Unit backwards compatibility.

assert_not_in_delta

Alias for refute_in_delta for Test::Unit backwards compatibility.

assert_not_in_epsilon

Alias for refute_in_epsilon for Test::Unit backwards compatibility.

assert_not_includes

Alias for refute_includes for Test::Unit backwards compatibility.

assert_not_instance_of

Alias for refute_instance_of for Test::Unit backwards compatibility.

assert_not_kind_of

Alias for refute_kind_of for Test::Unit backwards compatibility.

assert_not_nil

Alias for refute_nil for Test::Unit backwards compatibility.

assert_not_operator

Alias for refute_operator for Test::Unit backwards compatibility

assert_not_predicate

Alias for refute_predicate for Test::Unit backwards compatibility

assert_not_respond_to

Alias for refute_respond_to for Test::Unit backwards compatibility

assert_not_same

Alias for refute_same for Test::Unit backwards compatibility

assert_nothing_raised(*args)

Tests if the block doesn’t raise an exception.

assert_raise

Alias for assert_raises for Test::Unit backwards compatibility

ActiveSupport::Testing::Assertions

active_support/testing/assertions

Rails adds a number of assertions to the basic ones provided with MiniTest.

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

1 assert_difference 'Article.count' do

2 post :create, article: {...}

3 end

Any arbitrary expression can be passed in and evaluated:

1 assert_difference 'assigns(:article).comments(:reload).size' do

2 post :create, comment: {...}

3 end

Arbitrary difference values may be specified. The default is 1, but negative numbers are okay too:

1 assert_difference 'Article.count', -1 do

2 post :delete, id: ...

3 end

An array of expressions can also be passed in—each will be evaluated:

1 assert_difference [ 'Article.count', 'Post.count' ], 2 do

2 post :create, article: {...}

3 end

A lambda or a list of lambdas can be passed in and evaluated:

1 assert_difference ->{ Article.count }, 2 do

2 post :create, article: {...}

3 end

4

5 assert_difference [->{ Article.count }, ->{ Post.count }], 2 do

6 post :create, article: {...}

7 end

A error message can be specified:

1 assert_difference 'Article.count', -1, "Article should be destroyed" do

2 post :delete, id: ...

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

1 assert_no_difference 'Article.count' do

2 post :create, article: invalid_attributes

3 end

assert_not(object, message = nil)

Assert that an expression is not truthy.

1 assert_not nil # => true

2 assert_not false # => true

3 assert_not 'foo' # => 'foo' is not nil or false

active_support/testing/time_helpers

travel(duration, &block)

Changes the current time to the time in the future or in the past by a given time difference. This is accomplished by stubbing Time.now and Date.today.

1 Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00

2 travel 1.day

3 Time.current # => Sun, 10 Nov 2013 15:34:49 EST -05:00

4 Date.current # => Sun, 10 Nov 2013

travel_to(date_or_time, &block)

Changes the current time to the supplied date or time. This is accomplished by stubbing Time.now and Date.today.

Thread

Extensions to Ruby’s built-in Thread class.

active_support/core_ext/thread

freeze

Freeze thread local variables.

thread_variable?(key)

Returns true if the given string (or symbol) exists as a thread local variable.

>> current_thread = Thread.current

=> #<Thread:0x007fd2c08c0da8 run>

>> current_thread.thread_variable?(:tr4w)

=> false

>> current_thread.thread_variable_set(:tr4w, 'is awesome')

=> "is awesome"

>> current_thread.thread_variable?(:tr4w)

=> true

thread_variable_get(key)

Returns the value of a thread local variable that has been set.

thread_variable_set(key, value)

Set a thread local variable .

>> Thread.current.thread_variable_set(:tr4w, 'is awesome')

=> "is awesome"

thread_variables

Returns an array of thread local variables represented as symbols.

>> Thread.current.thread_variables

=> [:tr4w]

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.

1 classTime

2 def acts_like_time?

3 true

4 end

5 end

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

<=>

Implemented by the compare_with_coercion method. Layers additional behavior on Time#eql? so that ActiveSupport::TimeWithZone instances can be compared with Time instances.

advance(options)

Provides precise Time calculations. The options parameter takes a hash with any of the keys :months, :days, :years, :hours, :minutes, and :seconds.

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!

all_day

Convenience method for beginning_of_day..end_of_day. Returns a Range representing the whole day of the current time.

all_month

Convenience method for beginning_of_month..end_of_month. Returns a Range representing the whole month of the current time.

all_quarter

Convenience method for beginning_of_quarter..end_of_quarter. Returns a Range representing the whole quarter of the current time.

all_week(start_day = Date.beginning_of_week)

Convenience method for beginning_of_week(start_day)..end_of_week(start_day). Returns a Range representing the whole week of the current time.

all_year

Convenience method for beginning_of_year..end_of_year. Returns a Range representing the whole year of the current time.

at_beginning_of_day / at_midnight / beginning_of_day / midnight

Returns a new Time object representing the “start” of the current instance’s day, hard-coded to 00:00 hours.

at_beginning_of_hour / beginning_of_hour

Returns a new Time object representing the start of the hour (hh:00:00). Implemented simply as change(min: 0).

at_beginning_of_minute / beginning_of_minute

Returns a new Time object representing the start of the minute (hh:mm:00). Implemented simply as change(sec: 0).

at_beginning_of_quarter / beginning_of_quarter

Returns a new Time object representing the start of the calendar quarter (1st of January, April, July, October, 00:00 hours).

at_beginning_of_week

Alias for beginning_of_week.

at_beginning_of_year / beginning_of_year

Returns a new Time object representing the start of the year (1st of January, 00:00 hours).

at_end_of_day / end_of_day

Returns a new Time object representing the end of a day (23:59:59). Implemented simply as change(hour: 23, min: 59, sec: 59).

at_end_of_hour / end_of_hour

Returns a new Time object representing the end of the hour (hh:59:59). Implemented simply as change(min: 59, sec: 59).

at_end_of_minute / end_of_minute

Returns a new Time object representing the end of the minute (hh:mm:59). Implemented simply as change(sec: 59).

at_end_of_month / end_of_month

Returns a new Time object representing the end of the month (last day of the month at 23:59:59 hours).

at_end_of_quarter / end_of_quarter

Returns a new Time object representing the end of the quarter (31st of March, 30th June, 30th September, 31st December, at 23:59:59 hours)

at_end_of_week

Alias for end_of_week.

at_end_of_year / end_of_year

Returns a new Time object representing the end of the year (last day of the year at 23:59:59 hours).

beginning_of_week(start_day = Date.beginning_of_week)

Returns a new Time object representing the “start” of the current instance’s week, defaulting to Date.beginning_of_week.

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

Returns Time.zone.now when Time.zone or config.time_zone are set, otherwise returns Time.now.

days_ago(days)

Returns a new Time object minus the specified number of days.

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

days_since(days)

Returns a new Time object representing the time a number of specified days into the future.

days_to_week_start(start_day = Date.beginning_of_week)

Returns the number of days to the start of the week.

end_of_week(start_day = Date.beginning_of_week)

Returns a new Time object representing the “end” of the current instance’s week, with the week start_day defaulting to Date.beginning_of_week.

future?

Returns true if the Time instance is in the future.

middle_of_day / noon

Returns a new Time object representing the middle of the day (12:00:00). Implemented simply as change(hour: 12).

last_month / prev_month

Convenience method for months_ago(1).

last_quarter / prev_quarter

Convenience method for months_ago(3).

last_week(start_day = Date.beginning_of_week) / prev_week

Returns a new Time object representing the given day in the previous week, with the week start_day defaulting to Date.beginning_of_week.

last_year / prev_year

Convenience method for years_ago(1).

monday

Convenience method for beginning_of_week(:monday).

months_ago(months)

Returns a new Time object representing the time a number of specified months into the past.

months_since(months)

The opposite of months_ago. Returns a new Time object representing the time a number of specified months into the future.

next_month

Convenience method for months_since(1).

next_quarter

Convenience method for months_since(3).

next_week(given_day_in_next_week = Date.beginning_of_week)

Returns a new Time object representing the start of the given day in the following calendar week.

next_year

Convenience method for years_since(1).

seconds_since_midnight

Returns the number of seconds that have transpired since midnight.

seconds_until_end_of_day

Returns how many seconds left in the day until 23:59:59.

since(seconds) / in(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!

sunday

Convenience method for end_of_week(:monday).

today?

Returns true if the Time is today.

tomorrow

Returns a new Time object advanced by one day.

weeks_ago(weeks)

Returns a new Time object representing the time a number of specified weeks ago.

weeks_since(weeks)

Returns a new Time object representing the time a number of specified weeks into the future.

years_ago(years)

Returns a new Time object representing the time a number of specified years into the past.

years_since(years)

The opposite of years_ago. Returns a new Time object representing the time a number of specified years into the future.

yesterday

Returns a new Time object subtracted by one 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.

Date Formats

The DATE_FORMATS hash constant holds formatting patterns used by the to_formatted_s method to convert a Time object into a string representation:

1 DATE_FORMATS = {

2 :db => '%Y-%m-%d %H:%M:%S',

3 :number => '%Y%m%d%H%M%S',

4 :nsec => '%Y%m%d%H%M%S%9N',

5 :time => '%H:%M',

6 :short => '%d %b %H:%M',

7 :long => '%B %d, %Y %H:%M',

8 :long_ordinal => lambda { |time|

9 day_format = ActiveSupport::Inflector.ordinalize(time.day)

10 time.strftime("%B #{day_format}, %Y %H:%M")

11 },

12 :rfc822 => lambda { |time|

13 offset_format = time.formatted_offset(false)

14 time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}")

15 }

16 }

formatted_offset(colon = true, alternate_utc_string = nil)

Returns the UTC offset as an HH:MM formatted string.

1 Time.local(2000).formatted_offset # => "-06:00"

2 Time.local(2000).formatted_offset(false) # => "-0600"

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.

>> time = Time.now

=> Thu Jan 18 06:10:17 CST 2007

>> time.to_formatted_s(:time)

=> "06:10"

>> time.to_formatted_s(:db)

=> "2007-01-18 06:10:17"

>> time.to_formatted_s(:number)

=> "20070118061017"

>> time.to_formatted_s(:short)

=> "18 Jan 06:10"

>> time.to_formatted_s(:long)

=> "January 18, 2007 06:10"

>> time.to_formatted_s(:long_ordinal)

=> "January 18th, 2007 06:10"

>> time.to_formatted_s(:rfc822)

=> "Thu, 18 Jan 2007 06:10:17 -0600"

to_s

Aliased to to_formatted_s.

active_support/core_ext/time/marshal

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.

find_zone(time_zone)

Returns a TimeZone instance or nil it does not exist.

>> Time.find_zone("Eastern Time (US & Canada)")

=> #<ActiveSupport::TimeZone:0x007fd2c0bc49c8

@name="Eastern Time (US & Canada)", ...>

find_zone!(time_zone)

Same as find_zone, except it raises an ArgumentError if an invalid time_zone is provided.

in_time_zone(zone = ::Time.zone)

Returns the simultaneous time in the supplied zone.

>> Time.zone = 'Hawaii'

=> "Hawaii"

>> Time.utc(2000).in_time_zone

=> Fri, 31 Dec 1999 14:00:00 HST -10:00

use_zone(time_zone, &block)

Allows override of Time.zone locally inside supplied block; resets Time.zone to existing value when done.

>> Date.today

=> Wed, 02 Jun 2010

>> Time.use_zone(ActiveSupport::TimeZone['Hong Kong']) { Date.today }

=> Thu, 03 Jun 2010

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:

1 classApplicationController < ActionController::Base

2 before_action :set_time_zone

3

4 def set_time_zone

5 Time.zone = current_user.time_zone

6 end

7 end

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 ENV['TZ'] 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.

>> Time.zone = 'Eastern Time (US & Canada)'

=> 'Eastern Time (US & Canada)'

>> Time.zone.local(2007, 2, 10, 15, 30, 45)

=> Sat, 10 Feb 2007 15:30:45 EST -05:00

>> Time.zone.parse('2007-02-01 15:30:45')

=> Sat, 10 Feb 2007 15:30:45 EST -05:00

>> Time.zone.at(1170361845)

=> Sat, 10 Feb 2007 15:30:45 EST -05:00

>> Time.zone.now

=> Sun, 18 May 2008 13:07:55 EDT -04:00

>> Time.utc(2007, 2, 10, 20, 30, 45).in_time_zone

=> Sat, 10 Feb 2007 15:30:45 EST -05:00

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

>> t = Time.zone.now

=> Sun, 18 May 2008 13:27:25 EDT -04:00

>> t.class

=> ActiveSupport::TimeWithZone

>> t.hour

=> 13

>> t.dst?

=> true

>> t.utc_offset

=> -14400

>> t.zone

=> "EDT"

>> t.to_s(:rfc822)

=> "Sun, 18 May 2008 13:27:25 -0400"

>> t + 1.day

=> Mon, 19 May 2008 13:27:25 EDT -04:00

>> t.beginning_of_year

=> Tue, 01 Jan 2008 00:00:00 EST -05:00

>> t > Time.utc(1999)

=> true

>> t.is_a?(Time)

=> true

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

1 config.time_zone = "Eastern Time (US & Canada)"

2

3 Time.zone # => #<TimeZone:0x514834...>

4 Time.zone.name # => "Eastern Time (US & Canada)"

5 Time.zone.now # => Sun, 18 May 2008 14:30:44 EDT -04:00

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.

=~(re)

Compare name and TZInfo identifier to a supplied regexp. Returns true if a match is found.

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.

>> ActiveSupport::TimeZone['Dublin']

=> #<TimeZone:0x3208390 @name="Dublin", @utc_offset=nil ...>

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

at(seconds)

Creates a new ActiveSupport::TimeWithZone instance in time zone of self from the number of seconds since the Unix epoch.

1 Time.zone = 'Hawaii' # => "Hawaii"

2 Time.utc(2000).to_f # => 946684800.0

3 Time.zone.at(946684800.0) # => Fri, 31 Dec 1999 14:00:00 HST -10:00

TimeZone.create(name, offset)

Creates a new TimeZone instance with the given name and offset.

>> ActiveSupport::TimeZone.create("Atlanta", -5.hours)

=> #<ActiveSupport::TimeZone:0x007fd2c136b118 @name="Atlanta",

@utc_offset=-18000 seconds, @tzinfo=#<TZInfo::TimezoneProxy: Atlanta>,

@current_period=nil>

TimeZone.find_tzinfo(name)

Returns a TZInfo instance matching the specified name.

formatted_offset(colon=true, alternate_utc_string = nil)

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)

Create 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 tzinfoparameter can be explicitly passed in, otherwise the name will be used to find it: TimeZone.find_tzinfo(name)

local(*args)

Creates a new ActiveSupport::TimeWithZone instance in time zone of self from given values.

local_to_utc(time, dst=true)

Adjust the given time to the simultaneous time in UTC. Returns a Time.utc() instance.

now

Returns Time.now adjusted to this timezone.

>> Time.now

=> 2013-10-16 17:45:49 -0400

>> ActiveSupport::TimeZone['Hawaii'].now

=> Wed, 16 Oct 2013 11:46:05 HST -10:00

parse(str, now=now)

Creates a new ActiveSupport::TimeWithZone instance in time zone of self from parsed string.

>> Time.zone = 'Hawaii'

=> "Hawaii"

>> Time.zone.parse('1999-12-31 14:00:00')

=> Fri, 31 Dec 1999 14:00:00 HST -10:00

period_for_local(time, dst=true)

Method exists so that TimeZone instances respond like TZInfo::Timezone.

period_for_utf(time)

Method exists so that TimeZone instances respond like TZInfo::Timezone.

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.

1 ActiveSupport::TimeZone.seconds_to_utc_offset(-21_600) # => "-06:00"

to_s

Returns a textual representation of this timezone.

1 ActiveSupport::TimeZone['Dublin'].to_s # => "(GMT+00:00) Dublin"

today

Returns the current date in this timezone.

>> Date.today

=> Wed, 16 Oct 2013

>> ActiveSupport::TimeZone['Darwin'].today

=> Thu, 17 Oct 2013

TimeZone.us_zones

A convenience method for returning a collection of TimeZone objects for timezones in the USA.

>> ActiveSupport::TimeZone.us_zones.map(&:name)

=> ["Hawaii", "Alaska", "Pacific Time (US & Canada)", "Arizona",

"Mountain Time (US & Canada)", "Central Time (US & Canada)", "Eastern

Time (US & Canada)", "Indiana (East)"]

utc_offset

Returns the offset of this time zone from UTC in seconds.

utc_to_local(time)

Adjust the given time to the simultaneous time in the timezone.

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)

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'

Constants

The TYPE_NAMES constant holds a mapping of Ruby types to their representation when serialized as XML.

1 TYPE_NAMES = {

2 "Symbol" => "symbol",

3 "Fixnum" => "integer",

4 "Bignum" => "integer",

5 "BigDecimal" => "decimal",

6 "Float" => "float",

7 "TrueClass" => "boolean",

8 "FalseClass" => "boolean",

9 "Date" => "date",

10 "DateTime" => "dateTime",

11 "Time" => "dateTime",

12 "Array" => "array",

13 "Hash" => "hash"

14 }

The FORMATTING constant holds a mapping of lambdas that define how Ruby values are serialized to strings for representation in XML.

1 FORMATTING = {

2 "symbol" => Proc.new { |symbol| symbol.to_s },

3 "date" => Proc.new { |date| date.to_s(:db) },

4 "dateTime" => Proc.new { |time| time.xmlschema },

5 "binary" => Proc.new { |binary| ::Base64.encode64(binary) },

6 "yaml" => Proc.new { |yaml| yaml.to_yaml }

7 }

The PARSING constant holds a mapping of lambdas used to deserialize values stored in XML back into Ruby objects.

1 PARSING = {

2 "symbol" => Proc.new { |symbol| symbol.to_sym },

3 "date" => Proc.new { |date| ::Date.parse(date) },

4 "datetime" => Proc.new {

5 |time| Time.xmlschema(time).utc rescue ::DateTime.parse(time).utc },

6 "integer" => Proc.new { |integer| integer.to_i },

7 "float" => Proc.new { |float| float.to_f },

8 "decimal" => Proc.new { |number| BigDecimal(number) },

9 "boolean" => Proc.new {

10 |boolean| %w(1 true).include?(boolean.strip) },

11 "string" => Proc.new { |string| string.to_s },

12 "yaml" => Proc.new { |yaml| YAML::load(yaml) rescue yaml },

13 "base64Binary" => Proc.new { |bin| ::Base64.decode64(bin) },

14 "binary" => Proc.new { |bin, entity| _parse_binary(bin, entity) },

15 "file" => Proc.new { |file, entity| _parse_file(file, entity) }

16 }

1 PARSING.update(

2 "double" => PARSING["float"],

3 "dateTime" => PARSING["datetime"]

4 )