h2. Active Support Core Extensions Active Support is the Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff. It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Rails itself. By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Rails. endprologue. h3. How to Load Core Extensions h4. Stand-Alone Active Support In order to have a near zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you may load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything. Thus, after a simple require like: require 'active_support' objects do not even respond to +blank?+, let's see how to load its definition. h5. Cherry-picking a Definition The most lightweight way to get +blank?+ is to cherry-pick the file that defines it. For every single method defined as a core extension this guide has a note that says where is such a method defined. In the case of +blank?+ the note reads: NOTE: Defined in +active_support/core_ext/object/blank.rb+. That means that this single call is enough: require 'active_support/core_ext/object/blank' Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any. h5. Loading Grouped Core Extensions The next level is to simply load all extensions to +Object+. As a rule of thumb, extensions to +SomeClass+ are available in one shot by loading +active_support/core_ext/some_class+. Thus, if that would do, to have +blank?+ available we could just load all extensions to +Object+: require 'active_support/core_ext/object' h5. Loading All Core Extensions You may prefer just to load all core extensions, there is a file for that: require 'active_support/core_ext' h5. Loading All Active Support And finally, if you want to have all Active Support available just issue: require 'active_support/all' That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via +autoload+, so it is only loaded if used. h4. Active Support Within a Ruby on Rails Application A Ruby on Rails application loads all Active Support unless +config.active_support.bare+ is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section. h3. Extensions to All Objects h4. +blank?+ and +present?+ The following values are considered to be blank in a Rails application: * +nil+ and +false+, * strings composed only of whitespace, i.e. matching +/\A\s*\z/+, * empty arrays and hashes, and * any other object that responds to +empty?+ and it is empty. WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank. For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot: def charset charset = String(headers["Content-Type"] || headers["type"]).split(";")[1] charset.blank? ? nil : charset.strip.split("=")[1] end That's a typical use case for +blank?+. Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none: def instantiate_observers return if @observers.blank? # ... end The method +present?+ is equivalent to +!blank?+: assert @response.body.present? # same as !@response.body.blank? NOTE: Defined in +active_support/core_ext/object/blank.rb+. h4. +presence+ The +presence+ method returns its receiver if +present?+, and +nil+ otherwise. It is useful for idioms like this: host = config[:host].presence || 'localhost' NOTE: Defined in +active_support/core_ext/object/blank.rb+. h4. +duplicable?+ A few fundamental objects in Ruby are singletons. For example, in the whole live of a program the integer 1 refers always to the same instance: 1.object_id # => 3 Math.cos(0).to_i.object_id # => 3 Hence, there's no way these objects can be duplicated through +dup+ or +clone+: true.dup # => TypeError: can't dup TrueClass Some numbers which are not singletons are not duplicable either: 0.0.clone # => allocator undefined for Float (2**1024).clone # => allocator undefined for Bignum Active Support provides +duplicable?+ to programmatically query an object about this property: "".duplicable? # => true false.duplicable? # => false By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects. WARNING. Using +duplicable?+ is discouraged because it depends on a hard-coded list. Classes have means to disallow duplication like removing +dup+ and +clone+ or raising exceptions from them, only +rescue+ can tell. NOTE: Defined in +active_support/core_ext/object/duplicable.rb+. h4. +returning+ The method +returning+ yields its argument to a block and returns it. You tipically use it with a mutable object that gets modified in the block: def html_options_for_form(url_for_options, options, *parameters_for_url) returning options.stringify_keys do |html_options| html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart") html_options["action"] = url_for(url_for_options, *parameters_for_url) end end NOTE: Defined in +active_support/core_ext/object/returning.rb+. h4. +try+ Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first. For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+: def log_info(sql, name, ms) if @logger && @logger.debug? name = '%s (%.1fms)' % [name || 'SQL', ms] @logger.debug(format_log_entry(name, sql.squeeze(' '))) end end You can shorten that using +Object#try+. This method is a synonim for +Object#send+ except that it returns +nil+ if sent to +nil+. The previous example could then be rewritten as: def log_info(sql, name, ms) if @logger.try(:debug?) name = '%s (%.1fms)' % [name || 'SQL', ms] @logger.debug(format_log_entry(name, sql.squeeze(' '))) end end NOTE: Defined in +active_support/core_ext/object/try.rb+. h4. +singleton_class+ The method +singleton_class+ returns the singleton class of the receiver: String.singleton_class # => # String.new.singleton_class # => #> WARNING: Fixnums and symbols have no singleton classes, +singleton_class+ raises +TypeError+ on them. Moreover, the singleton classes of +nil+, +true+, and +false+, are +NilClass+, +TrueClass+, and +FalseClass+, respectively. NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+. h4. +class_eval(*args, &block)+ You can evaluate code in the context of any object's singleton class using +class_eval+: class Proc def bind(object) block, time = self, Time.now object.class_eval do method_name = "__bind_#{time.to_i}_#{time.usec}" define_method(method_name, &block) method = instance_method(method_name) remove_method(method_name) method end.bind(object) end end NOTE: Defined in +active_support/core_ext/kernel/singleton_class.rb+. h4. +acts_like?(duck)+ The method +acts_like+ provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as +String+ defines def acts_like_string? end which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way: some_klass.acts_like?(:string) Rails has classes that act like +Date+ or +Time+ and follow this contract. NOTE: Defined in +active_support/core_ext/object/acts_like.rb+. h4. +to_param+ All objects in Rails respond to the method +to_param+, which is meant to return something that represents them as values in a query string, or as a URL fragments. By default +to_param+ just calls +to_s+: 7.to_param # => "7" The return value of +to_param+ should *not* be escaped: "Tom & Jerry".to_param # => "Tom & Jerry" Several classes in Rails overwrite this method. For example +nil+, +true+, and +false+ return themselves. +Array#to_param+ calls +to_param+ on the elements and joins the result with "/": [0, true, String].to_param # => "0/true/String" Notably, the Rails routing system calls +to_param+ on models to get a value for the +:id+ placeholder. +ActiveRecord::Base#to_param+ returns the +id+ of a model, but you can redefine that method in your models. For example, given class User def to_param "#{id}-#{name.parameterize}" end end we get: user_path(@user) # => "/users/357-john-smith" WARNING. Controllers need to be aware of any redifinition of +to_param+ because when a request like that comes in "357-john-smith" is the value of +params[:id]+. NOTE: Defined in +active_support/core_ext/object/to_param.rb+. h4. +to_query+ Except for hashes, given an unescaped +key+ this method constructs the part of a query string that would map such key to what +to_param+ returns. For example, given class User def to_param "#{id}-#{name.parameterize}" end end we get: current_user.to_query('user') # => user=357-john-smith This method escapes whatever is needed, both for the key and the value: account.to_query('company[name]') # => "company%5Bname%5D=Johnson+%26+Johnson" so its output is ready to be used in a query string. Arrays return the result of applying +to_query+ to each element with _key_[] as key, and join the result with "&": [3.4, -45.6].to_query('sample') # => "sample%5B%5D=3.4&sample%5B%5D=-45.6" Hashes also respond to +to_query+ but with a different signature. If no argument is passed a call generates a sorted series of key/value assigments calling +to_query(key)+ on its values. Then it joins the result with "&": {:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3" The method +Hash#to_query+ accepts an optional namespace for the keys: {:id => 89, :name => "John Smith"}.to_query('user') # => "user%5Bid%5D=89&user%5Bname%5D=John+Smith" NOTE: Defined in +active_support/core_ext/object/to_query.rb+. h4. +with_options+ The method +with_options+ provides a way to factor out common options in a series of method calls. Given a default options hash, +with_options+ yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in: class Account < ActiveRecord::Base has_many :customers, :dependent => :destroy has_many :products, :dependent => :destroy has_many :invoices, :dependent => :destroy has_many :expenses, :dependent => :destroy end this way: class Account < ActiveRecord::Base with_options :dependent => :destroy do |assoc| assoc.has_many :customers assoc.has_many :products assoc.has_many :invoices assoc.has_many :expenses end end That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this: I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n| subject i18n.t :subject body i18n.t :body, :user_name => user.name end TIP: Since +with_options+ forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own. NOTE: Defined in +active_support/core_ext/object/with_options.rb+. h5. +subclasses_of+ The method +subclasses_of+ receives an arbitrary number of class objects and returns all their anonymous or reachable descendants as a single array: class C; end subclasses_of(C) # => [] subclasses_of(Integer) # => [Bignum, Fixnum] module M class A; end class B1 < A; end class B2 < A; end end module N class C < M::B1; end end subclasses_of(M::A) # => [N::C, M::B2, M::B1] The order in which these classes are returned is unspecified. The returned collection may have duplicates: subclasses_of(Numeric, Integer) # => [Bignum, Float, Fixnum, Integer, Date::Infinity, Rational, BigDecimal, Bignum, Fixnum] See also +Class#subclasses+ in "Extensions to +Class+ FIX THIS LINK":FIXME. NOTE: Defined in +active_support/core_ext/object/extending.rb+. h4. Instance Variables Active Support provides several methods to ease access to instance variables. h5. +instance_variable_names+ Ruby 1.8 and 1.9 have a method called +instance_variables+ that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines +instance_variable_names+ as a portable way to obtain them as strings: class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_variable_names # => ["@y", "@x"] WARNING: The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter. NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+. h5. +instance_values+ The method +instance_values+ returns a hash that maps instance variable names without "@" to their corresponding values. Keys are strings both in Ruby 1.8 and 1.9: class C def initialize(x, y) @x, @y = x, y end end C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+. h5. +copy_instance_variables_from(object, exclude = [])+ Copies the instance variables of +object+ into +self+. Instance variable names in the +exclude+ array are ignored. If +object+ responds to +protected_instance_variables+ the ones returned are also ignored. For example, Rails controllers implement that method. In both arrays strings and symbols are understood, and they have to include the at sign. class C def initialize(x, y, z) @x, @y, @z = x, y, z end def protected_instance_variables %w(@z) end end a = C.new(0, 1, 2) b = C.new(3, 4, 5) a.copy_instance_variables_from(b, [:@y]) # a is now: @x = 3, @y = 1, @z = 2 In the example +object+ and +self+ are of the same type, but they don't need to. NOTE: Defined in +active_support/core_ext/object/instance_variables.rb+. h4. Silencing Warnings, Streams, and Exceptions The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards: silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger } You can silence any stream while a block runs with +silence_stream+: silence_stream(STDOUT) do # STDOUT is silent here end Silencing exceptions is also possible with +suppress+. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is +kind_of?+ any of the arguments, +suppress+ captures it and returns silently. Otherwise the exception is reraised: # If the user is locked the increment is lost, no big deal. suppress(ActiveRecord::StaleObjectError) do current_user.increment! :visits end NOTE: Defined in +active_support/core_ext/kernel/reporting.rb+. h4. +require_library_or_gem+ The convenience method +require_library_or_gem+ tries to load its argument with a regular +require+ first. If it fails loads +rubygems+ and tries again. If the first attempt is a failure and +rubygems+ can't be loaded the method raises +LoadError+. On the other hand, if +rubygems+ is available but the argument is not loadable as a gem, the method gives up and +LoadError+ is also raised. For example, that's the way the MySQL adapter loads the MySQL library: require_library_or_gem('mysql') NOTE: Defined in +active_support/core_ext/kernel/requires.rb+. h3. Extensions to +Module+ h4. +alias_method_chain+ Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_. For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap +ActionController::TestCase#process+ this way in +test/test_helper.rb+: ActionController::TestCase.class_eval do # save a reference to the original process method alias_method :original_process, :process # now redefine process and delegate to original_process def process(action, params=nil, session=nil, flash=nil, http_method='GET') params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten] original_process(action, params, session, flash, http_method) end end That's the method +get+, +post+, etc., delegate the work to. That technique has a risk, it could be the case that +:original_process+ was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about: ActionController::TestCase.class_eval do def process_with_stringified_params(...) params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten] process_without_stringified_params(action, params, session, flash, http_method) end alias_method :process_without_stringified_params, :process alias_method :process, :process_with_stringified_params end The method +alias_method_chain+ provides a shortcut for that pattern: ActionController::TestCase.class_eval do def process_with_stringified_params(...) params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten] process_without_stringified_params(action, params, session, flash, http_method) end alias_method_chain :process, :stringified_params end Rails uses +alias_method_chain+ all over the code base. For example validations are added to +ActiveRecord::Base#save+ by wrapping the method that way in a separate module specialised in validations. NOTE: Defined in +active_support/core_ext/module/aliasing.rb+. h4. Attributes h5. +alias_attribute+ Model attributes have a reader, a writer, and a predicate. You can aliase a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (my mnemonic is they go in the same order as if you did an assignment): class User < ActiveRecord::Base # let me refer to the email column as "login", # much meaningful for authentication code alias_attribute :login, :email end NOTE: Defined in +active_support/core_ext/module/aliasing.rb+. h5. +attr_accessor_with_default+ The method +attr_accessor_with_default+ serves the same purpose as the Ruby macro +attr_accessor+ but allows you to set a default value for the attribute: class Url attr_accessor_with_default :port, 80 end Url.new.port # => 80 The default value can be also specified with a block, which is called in the context of the corresponding object: class User attr_accessor :name, :surname attr_accessor_with_default(:full_name) { [name, surname].compact.join(" ") } end u = User.new u.name = 'Xavier' u.surname = 'Noria' u.full_name # => "Xavier Noria" The result is not cached, the block is invoked in each call to the reader. You can overwrite the default with the writer: url = Url.new url.host # => 80 url.host = 8080 url.host # => 8080 The default value is returned as long as the attribute is unset. The reader does not rely on the value of the attribute to know whether it has to return the default. It rather monitors the writer: if there's any assignment the value is no longer considered to be unset. Active Resource uses this macro to set a default value for the +:primary_key+ attribute: attr_accessor_with_default :primary_key, 'id' NOTE: Defined in +active_support/core_ext/module/attr_accessor_with_default.rb+. h5. Internal Attributes When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries. Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the unerlying instace variable in a way that makes collisions less likely. The macro +attr_internal+ is a synonim for +attr_internal_accessor+: # library class ThirdPartyLibrary::Crawler attr_internal :log_level end # client code class MyCrawler < ThirdPartyLibrary::Crawler attr_accessor :log_level end In the previous example it could be the case that +:log_level+ does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own +:log_level+. Thanks to +attr_internal+ there's no collision. By default the internal instance variable is named with a leading underscore, +@_log_level+ in the example above. That's configurable via +Module.attr_internal_naming_format+ though, you can pass any +sprintf+-like format string with a leading +@+ and a +%s+ somewhere, which is where the name will be placed. The default is +"@_%s"+. Rails uses internal attributes in a few spots, for examples for views: module ActionView class Base attr_internal :captures attr_internal :request, :layout attr_internal :controller, :template end end NOTE: Defined in +active_support/core_ext/module/attr_internal.rb+. h5. Module Attributes The macros +mattr_reader+, +mattr_writer+, and +mattr_accessor+ are analogous to the +cattr_*+ macros defined for class. Check "Class Attributes":#class-attributes. For example, the dependencies mechanism uses them: module ActiveSupport module Dependencies mattr_accessor :warnings_on_first_load mattr_accessor :history mattr_accessor :loaded mattr_accessor :mechanism mattr_accessor :load_paths mattr_accessor :load_once_paths mattr_accessor :autoloaded_constants mattr_accessor :explicitly_unloadable_constants mattr_accessor :logger mattr_accessor :log_activity mattr_accessor :constant_watch_stack mattr_accessor :constant_watch_stack_mutex end end NOTE: Defined in +active_support/core_ext/module/attribute_accessors.rb+. h4. Method Delegation The class method +delegate+ offers an easy way to forward methods. For example, if +User+ has some details like the age factored out to +Profile+, it could be handy to still be able to acces such attribute directly, user.age, instead of having to explicit the chain user.profile.age. That can be accomplished by hand: class User has_one :profile def age profile.age end end But with +delegate+ you can make that shorter and the intention even more obvious: class User has_one :profile delegate :age, to => :profile end The macro accepts more than one method: class User has_one :profile delegate :age, :avatar, :twitter_username, to => :profile end Methods can be delegated to objects returned by methods, as in the examples above, but also to instance variables, class variables, and constants. Just pass their names as symbols or strings, including the at signs in the last cases. For example, +ActionView::Base+ delegates +erb_trim_mode=+: module ActionView class Base delegate :erb_trim_mode=, :to => 'ActionView::Template::Handlers::ERB' end end In fact, you can delegate to any expression passed as a string. It will be evaluated in the context of the receiver. Controllers for example delegate alerts and notices to the current flash: delegate :alert, :notice, :to => "request.flash" If the target is +nil+ calling any delegated method will raise an exception even if +nil+ responds to such method. You can override this behavior setting the option +:allow_nil+ to true, in which case the forwarded call will simply return +nil+. If the target is a method, the name of delegated methods can also be prefixed. If the +:prefix+ option is set to (exactly) the +true+ object, the value of the +:to+ option is prefixed: class Invoice belongs_to :customer # defines a method called customer_name delegate :name, :to => :customer, :prefix => true end And a custom prefix can be set as well, in that case it does not matter wheter the target is a method or not: class Account belongs_to :user # defines a method called admin_email delegate :email, :to => :user, :prefix => 'admin' end NOTE: Defined in +active_support/core_ext/module/delegation.rb+. h4. Method Removal h5. +remove_possible_method+ The method +remove_possible_method+ is like the standard +remove_method+, except it silently returns on failure: class A; end A.class_eval do remove_method(:nonexistent) # raises NameError remove_possible_method(:nonexistent) # no problem, continue end This may come in handy if you need to define a method that may already exist, since redefining a method issues a warning "method redefined; discarding old redefined_method_name". NOTE: Defined in +active_support/core_ext/module/remove_method.rb+. h4. Parents h5. +parent+ The +parent+ method on a nested named module returns the module that contains its corresponding constant: module X module Y module Z end end end M = X::Y::Z X::Y::Z.parent # => X::Y M.parent # => X::Y If the module is anonymous or belongs to the top-level, +parent+ returns +Object+. WARNING: Note that in that case +parent_name+ returns +nil+. NOTE: Defined in +active_support/core_ext/module/introspection.rb+. h5. +parent_name+ The +parent_name+ method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant: module X module Y module Z end end end M = X::Y::Z X::Y::Z.parent_name # => "X::Y" M.parent_name # => "X::Y" For top-level or anonymous modules +parent_name+ returns +nil+. WARNING: Note that in that case +parent+ returns +Object+. NOTE: Defined in +active_support/core_ext/module/introspection.rb+. h5(#module-parents). +parents+ The method +parents+ calls +parent+ on the receiver and upwards until +Object+ is reached. The chain is returned in an array, from bottom to top: module X module Y module Z end end end M = X::Y::Z X::Y::Z.parents # => [X::Y, X, Object] M.parents # => [X::Y, X, Object] NOTE: Defined in +active_support/core_ext/module/introspection.rb+. h4. Constants The method +local_constants+ returns the names of the constants that have been defined in the receiver module: module X X1 = 1 X2 = 2 module Y Y1 = :y1 X1 = :overrides_X1_above end end X.local_constants # => ["X2", "X1", "Y"], assumes Ruby 1.8 X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8 The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method +local_constant_names+ returns always strings. WARNING: This method is exact if running under Ruby 1.9. In previous versions it may miss some constants if their value in some ancestor stores the exact same object than in the receiver. NOTE: Defined in +active_support/core_ext/module/introspection.rb+. h4. Synchronization The +synchronize+ macro declares a method to be synchronized: class Counter @@mutex = Mutex.new attr_reader :value def initialize @value = 0 end def incr @value += 1 # non-atomic end synchronize :incr, :with => '@@mutex' end The method receives the name of an action, and a +:with+ option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a +Mutex+ instance or any other object that responds to +synchronize+ and accepts a block. NOTE: Defined in +active_support/core_ext/module/synchronization.rb+. h4. Reachable A named module is reachable if it is stored in its correspoding constant. It means you can reach the module object via the constant. That is what ordinarily happens, if a module is called "M", the +M+ constant exists and holds it: module M end M.reachable? # => true But since constants and modules are indeed kind of decoupled, module objects can become unreachable: module M end orphan = Object.send(:remove_const, :M) # The module object is orphan now but it still has a name. orphan.name # => "M" # You cannot reach it via the constant M because it does not even exist. orphan.reachable? # => false # Let's define a module called "M" again. module M end # The constant M exists now again, and it stores a module # object called "M", but it is a new instance. orphan.reachable? # => false NOTE: Defined in +active_support/core_ext/module/reachable.rb+. h4. Anonymous A module may or may not have a name: module M end M.name # => "M" N = Module.new N.name # => "N" Module.new.name # => "" in 1.8, nil in 1.9 You can check whether a module has a name with the predicate +anonymous?+: module M end M.anonymous? # => false Module.new.anonymous? # => true Note that being unreachable does not imply being anonymous: module M end m = Object.send(:remove_const, :M) m.reachable? # => false m.anonymous? # => false though an anonymous module is unreachable by definition. NOTE: Defined in +active_support/core_ext/module/anonymous.rb+. h3. Extensions to +Class+ h4. Class Attributes The method +Class#class_attribute+ declares one or more inheritable class attributes that can be overriden at any level down the hierarchy: class A class_attribute :x end class B < A; end class C < B; end A.x = :a B.x # => :a C.x # => :a B.x = :b A.x # => :a C.x # => :b C.x = :c A.x # => :a B.x # => :b For example that's the way the +allow_forgery_protection+ flag is implemented for controllers: class_attribute :allow_forgery_protection self.allow_forgery_protection = true For convenience +class_attribute+ defines also a predicate, so that declaration also generates +allow_forgery_protection?+. Such predicate returns the double boolean negation of the value. NOTE: Defined in +active_support/core_ext/class/attribute.rb+ The macros +cattr_reader+, +cattr_writer+, and +cattr_accessor+ are analogous to their +attr_*+ counterparts but for classes. They initialize a class variable to +nil+ unless it already exists, and generate the corresponding class methods to access it: class MysqlAdapter < AbstractAdapter # Generates class methods to access @@emulate_booleans. cattr_accessor :emulate_booleans self.emulate_booleans = true end Instance methods are created as well for convenience. For example given module ActionController class Base cattr_accessor :logger end end we can access +logger+ in actions. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+): module ActiveRecord class Base # No pluralize_table_names= instance writer is generated. cattr_accessor :pluralize_table_names, :instance_writer => false end end A model may find that option useful as a way to prevent mass-assignment from setting the attribute. NOTE: Defined in +active_support/core_ext/class/attribute_accessors.rb+. h4. Class Inheritable Attributes Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros +class_inheritable_reader+, +class_inheritable_writer+, and +class_inheritable_accessor+ provide accesors for class-level data which is inherited but not shared with children: module ActionController class Base # FIXME: REVISE/SIMPLIFY THIS COMMENT. # The value of allow_forgery_protection is inherited, # but its value in a particular class does not affect # the value in the rest of the controllers hierarchy. class_inheritable_accessor :allow_forgery_protection end end They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with +dup+ as long as the value is duplicable. There are some variants specialised in arrays and hashes: class_inheritable_array class_inheritable_hash Those writers take any inherited array or hash into account and extend them rather than overwrite them. As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting +:instance_writer+ to +false+ (not any false value, but exactly +false+): module ActiveRecord class Base class_inheritable_accessor :default_scoping, :instance_writer => false end end Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That's the point. NOTE: Defined in +active_support/core_ext/class/inheritable_attributes.rb+. There's a related macro called +superclass_delegating_accessor+, however, that does not copy the value when the base class is subclassed. Instead, it delegates reading to the superclass as long as the attribute is not set via its own writer. For example, +ActionMailer::Base+ defines +delivery_method+ this way: module ActionMailer class Base superclass_delegating_accessor :delivery_method self.delivery_method = :smtp end end If for whatever reason an application loads the definition of a mailer class and after that sets +ActionMailer::Base.delivery_method+, the mailer class will still see the new value. In addition, the mailer class is able to change the +delivery_method+ without affecting the value in the parent using its own inherited class attribute writer. NOTE: Defined in +active_support/core_ext/class/delegating_attributes.rb+. h4. Descendants h5. +subclasses+ The +subclasses+ method returns the names of all the anonymous or reachable descendants of its receiver as an array of strings: class C; end C.subclasses # => [] Integer.subclasses # => ["Bignum", "Fixnum"] module M class A; end class B1 < A; end class B2 < A; end end module N class C < M::B1; end end M::A.subclasses # => ["N::C", "M::B2", "M::B1"] The order in which these class names are returned is unspecified. See also +Object#subclasses_of+ in "Extensions to All Objects FIX THIS LINK":FIXME. WARNING: This method is redefined in some Rails core classes. NOTE: Defined in +active_support/core_ext/class/subclasses.rb+. h3. Extensions to +String+ h4. Output Safety Inserting data into HTML templates needs extra care. For example you can't just interpolate +@review.title+ verbatim into an HTML page. On one hand if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;". On the other hand, depending on the application that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the "section about cross-site scripting in the Security guide":security.html#cross-site-scripting-xss for further information about the risks. Active Support has the concept of (html) safe strings since Rails 3. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not. Strings are considered to be unsafe by default: "".html_safe? # => false You can obtain a safe string from a given one with the +html_safe+ method: s = "".html_safe s.html_safe? # => true It is important to understand that +html_safe+ performs no escaping whatsoever, it is just an assertion: s = "".html_safe s.html_safe? # => true s # => "" It is your responsability to ensure calling +html_safe+ on a particular string is fine. NOTE: For performance reasons safe strings are implemented in a way that cannot offer an in-place +html_safe!+ variant. If you append onto a safe string, either in-place with +concat+/<<, or with +, the result is a safe string. Unsafe arguments are escaped: "".html_safe + "<" # => "<" Safe arguments are directly appended: "".html_safe + "<".html_safe # => "<" These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped: <%= @review.title %> <%# fine in Rails 3, escaped if needed %> To insert something verbatim use the +raw+ helper rather than calling +html_safe+: <%= raw @cms.current_template %> <%# inserts @cms.current_template as is %> The +raw+ helper calls +html_safe+ for you: def raw(stringish) stringish.to_s.html_safe end NOTE: Defined in +active_support/core_ext/string/output_safety.rb+. h4. +squish+ The method +String#squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each: " \n foo\n\r \t bar \n".squish # => "foo bar" There's also the destructive version +String#squish!+. NOTE: Defined in +active_support/core_ext/string/filters.rb+. h4. Key-based Interpolation In Ruby 1.9 the % string operator supports key-based interpolation, both formatted and unformatted: "Total is %.02f" % {:total => 43.1} # => Total is 43.10 "I say %{foo}" % {:foo => "wadus"} # => "I say wadus" "I say %{woo}" % {:foo => "wadus"} # => KeyError Active Support adds that functionality to % in previous versions of Ruby. NOTE: Defined in +active_support/core_ext/string/interpolation.rb+. h4. +starts_with?+ and +ends_width?+ Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+: "foo".starts_with?("f") # => true "foo".ends_with?("o") # => true NOTE: Defined in +active_support/core_ext/string/starts_ends_with.rb+. h4. Access h5. +at(position)+ Returns the character of the string at position +position+: "hello".at(0) # => "h" "hello".at(4) # => "o" "hello".at(-1) # => "o" "hello".at(10) # => ERROR if < 1.9, nil in 1.9 NOTE: Defined in +active_support/core_ext/string/access.rb+. h5. +from(position)+ Returns the substring of the string starting at position +position+: "hello".from(0) # => "hello" "hello".from(2) # => "llo" "hello".from(-2) # => "lo" "hello".from(10) # => "" if < 1.9, nil in 1.9 NOTE: Defined in +active_support/core_ext/string/access.rb+. h5. +to(position)+ Returns the substring of the string up to position +position+: "hello".to(0) # => "h" "hello".to(2) # => "hel" "hello".to(-2) # => "hell" "hello".to(10) # => "hello" NOTE: Defined in +active_support/core_ext/string/access.rb+. h5. +first(limit = 1)+ The call +str.first(n)+ is equivalent to +str.to(n-1)+ if +n+ > 0, and returns an empty string for +n+ == 0. NOTE: Defined in +active_support/core_ext/string/access.rb+. h5. +last(limit = 1)+ The call +str.last(n)+ is equivalent to +str.from(-n)+ if +n+ > 0, and returns an empty string for +n+ == 0. NOTE: Defined in +active_support/core_ext/string/access.rb+. h4. Inflections h5. +pluralize+ The method +pluralize+ returns the plural of its receiver: "table".pluralize # => "tables" "ruby".pluralize # => "rubies" "equipment".pluralize # => "equipment" As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Builtin rules can be extended in +config/initializers/inflections.rb+. That file is generated by the +rails+ command and has instructions in comments. Active Record uses this method to compute the default table name that corresponds to a model: # active_record/base.rb def undecorated_table_name(class_name = base_class.name) table_name = class_name.to_s.demodulize.underscore table_name = table_name.pluralize if pluralize_table_names table_name end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +singularize+ The inverse of +pluralize+: "tables".singularize # => "table" "rubies".singularize # => "ruby" "equipment".singularize # => "equipment" Associations compute the name of the corresponding default associated class using this method: # active_record/reflection.rb def derive_class_name class_name = name.to_s.camelize class_name = class_name.singularize if collection? class_name end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +camelize+ The method +camelize+ returns its receiver in camel case: "product".camelize # => "Product" "admin_user".camelize # => "AdminUser" As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces: "backoffice/session".camelize # => "Backoffice::Session" For example, Action Pack uses this method to load the class that provides a certain session store: # action_controller/metal/session_management.rb def session_store=(store) if store == :active_record_store self.session_store = ActiveRecord::SessionStore else @@session_store = store.is_a?(Symbol) ? ActionDispatch::Session.const_get(store.to_s.camelize) : store end end +camelize+ accepts an optional argument, it can be +:upper+ (default), or +:lower+. With the latter the first letter becomes lowercase: "visual_effect".camelize(:lower) # => "visualEffect" That may be handy to compute method names in a language that follows that convention, for example JavaScript. +camelize+ is aliased to +camelcase+. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +underscore+ The method +underscore+ is the inverse of +camelize+, explained above: "Product".underscore # => "product" "AdminUser".underscore # => "admin_user" Also converts "::" back to "/": "Backoffice::Session".underscore # => "backoffice/session" and understands strings that start with lowercase: "visualEffect".underscore # => "visual_effect" +underscore+ accepts no argument though. Rails class and module autoloading uses +underscore+ to infer the relative path without extension of a file that would define a given missing constant: # active_support/dependencies.rb def load_missing_constant(from_mod, const_name) ... qualified_name = qualified_name_for from_mod, const_name path_suffix = qualified_name.underscore ... end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +titleize+ The method +titleize+ capitalizes the words in the receiver: "alice in wonderland".titleize # => "Alice In Wonderland" "fermat's enigma".titleize # => "Fermat's Enigma" +titleize+ is aliased to +titlecase+. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +dasherize+ The method +dasherize+ replaces the underscores in the receiver with dashes: "name".dasherize # => "name" "contact_data".dasherize # => "contact-data" The XML serializer of models uses this method to dasherize node names: # active_model/serializers/xml.rb def reformat_name(name) name = name.camelize if camelize? dasherize? ? name.dasherize : name end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +demodulize+ Given a string with a qualified constant reference expression, +demodulize+ returns the very constant name, that is, the rightmost part of it: "Product".demodulize # => "Product" "Backoffice::UsersController".demodulize # => "UsersController" "Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils" Active Record for example uses this method to compute the name of a counter cache column: # active_record/reflection.rb def counter_cache_column if options[:counter_cache] == true "#{active_record.name.demodulize.underscore.pluralize}_count" elsif options[:counter_cache] options[:counter_cache] end end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +parameterize+ The method +parameterize+ normalizes its receiver in a way that can be used in pretty URLs. "John Smith".parameterize # => "john-smith" "Kurt Gödel".parameterize # => "kurt-godel" In fact, the result string is wrapped in an instance of +ActiveSupport::Multibyte::Chars+. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +tableize+ The method +tableize+ is +underscore+ followed by +pluralize+. "Person".tableize # => "people" "Invoice".tableize # => "invoices" "InvoiceLine".tableize # => "invoice_lines" As a rule of thumb, +tableize+ returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight +tableize+ indeed, because it also demodulizes de class name and checks a few options that may affect the returned string. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +classify+ The method +classify+ is the inverse of +tableize+. It gives you the class name corresponding to a table name: "people".classify # => "Person" "invoices".classify # => "Invoice" "invoice_lines".classify # => "InvoiceLine" The method understands qualified table names: "highrise_production.companies".classify # => "Company" Note that +classify+ returns a class name as a string. You can get the actual class object invoking +constantize+ on it, explained next. NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +constantize+ The method +constantize+ resolves the constant reference expression in its receiver: "Fixnum".constantize # => Fixnum module M X = 1 end "M::X".constantize # => 1 If the string evaluates to no known constant, or its content is not even a valid constant name, +constantize+ raises +NameError+. Constant name resolution by +constantize+ starts always at the top-level +Object+ even if there is no leading "::". X = :in_Object module M X = :in_M X # => :in_M "::X".constantize # => :in_Object "X".constantize # => :in_Object (!) end So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated. Mailer test cases obtain the mailer being tested from the name of the test class using +constantize+: # action_mailer/test_case.rb def determine_default_mailer(name) name.sub(/Test$/, '').constantize rescue NameError => e raise NonInferrableMailerError.new(name) end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +humanize+ The method +humanize+ gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any "_id" suffix, and capitalizes the first word: "name".humanize # => "Name" "author_id".humanize # => "Author" "comments_count".humanize # => "Comments count" The helper method +full_messages+ uses +humanize+ as a fallback to include attribute names: def full_messages full_messages = [] each do |attribute, messages| ... attr_name = attribute.to_s.gsub('.', '_').humanize attr_name = @base.class.human_attribute_name(attribute, :default => attr_name) ... end full_messages end NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h5. +foreign_key+ The method +foreign_key+ gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id": "User".foreign_key # => "user_id" "InvoiceLine".foreign_key # => "invoice_line_id" "Admin::Session".foreign_key # => "session_id" Pass a false argument if you do not want the underscore in "_id": "User".foreign_key(false) # => "userid" Associations use this method to infer foreign keys, for example +has_one+ and +has_many+ do this: # active_record/associations.rb foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key NOTE: Defined in +active_support/core_ext/string/inflections.rb+. h3. Extensions to +Numeric+ h4. Bytes All numbers respond to these methods: bytes kilobytes megabytes gigabytes terabytes petabytes exabytes They return the corresponding amount of bytes, using a conversion factor of 1024: 2.kilobytes # => 2048 3.megabytes # => 3145728 3.5.gigabytes # => 3758096384 -4.exabytes # => -4611686018427387904 Singular forms are aliased so you are able to say: 1.megabyte # => 1048576 NOTE: Defined in +active_support/core_ext/numeric/bytes.rb+. h3. Extensions to +Integer+ h4. +multiple_of?+ The method +multiple_of?+ tests whether an integer is multiple of the argument: 2.multiple_of?(1) # => true 1.multiple_of?(2) # => false NOTE: Defined in +active_support/core_ext/integer/multiple.rb+. h4. +ordinalize+ The method +ordinalize+ returns the ordinal string corresponding to the receiver integer: 1.ordinalize # => "1st" 2.ordinalize # => "2nd" 53.ordinalize # => "53rd" 2009.ordinalize # => "2009th" NOTE: Defined in +active_support/core_ext/integer/inflections.rb+. h3. Extensions to +Float+ h4. +round+ The builtin method +Float#round+ rounds a float to the nearest integer. Active Support adds an optional parameter to let you specify a precision: Math::E.round(4) # => 2.7183 NOTE: Defined in +active_support/core_ext/float/rounding.rb+. h3. Extensions to +BigDecimal+ ... h3. Extensions to +Enumerable+ h4. +group_by+ Ruby 1.8.7 and up define +group_by+, and Active Support does it for previous versions. This iterator takes a block and builds an ordered hash with its return values as keys. Each key is mapped to the array of elements for which the block returned that value: entries_by_surname_initial = address_book.group_by do |entry| entry.surname.at(0).upcase end WARNING. Active Support redefines +group_by+ in Ruby 1.8.7 so that it still returns an ordered hash. NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +sum+ The method +sum+ adds the elements of an enumerable: [1, 2, 3].sum # => 6 (1..100).sum # => 5050 Addition only assumes the elements respond to +: [[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4] %w(foo bar baz).sum # => "foobarbaz" {:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1] The sum of an empty collection is zero by default, but this is customizable: [].sum # => 0 [].sum(1) # => 1 If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values: (1..5).sum {|n| n * 2 } # => 30 [2, 4, 6, 8, 10].sum # => 30 The sum of an empty receiver can be customized in this form as well: [].sum(1) {|n| n**3} # => 1 The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way: def observed_subclasses observed_classes.sum([]) { |klass| klass.send(:subclasses) } end NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +each_with_object+ The +inject+ method offers iteration with an accumulator: [2, 3, 4].inject(1) {|acc, i| product*i } # => 24 The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome: [1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4} See that spurious "+; h+"? Active Support backports +each_with_object+ from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way: [1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4} WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+. NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +index_by+ The method +index_by+ generates a hash with the elements of an enumerable indexed by some key. It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block: invoices.index_by(&:number) # => {'2009-032' => , '2009-008' => , ...} WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win. NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +many?+ The method +many?+ is shorthand for +collection.size > 1+: <% if pages.many? %> <%= pagination_links %> <% end %> If an optional block is given +many?+ only takes into account those elements that return true: @see_more = videos.many? {|video| video.category == params[:category]} NOTE: Defined in +active_support/core_ext/enumerable.rb+. h4. +exclude?+ The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+: to_visit << node if visited.exclude?(node) NOTE: Defined in +active_support/core_ext/enumerable.rb+. h3. Extensions to +Array+ h4. Accessing Active Support augments the API of arrays to ease certain ways of accessing them. For example, +to+ returns the subarray of elements up to the one at the passed index: %w(a b c d).to(2) # => %w(a b c) [].to(7) # => [] Similarly, +from+ returns the tail from the element at the passed index on: %w(a b c d).from(2) # => %w(c d) %w(a b c d).from(10) # => nil [].from(0) # => [] The methods +second+, +third+, +fourth+, and +fifth+ return the corresponding element (+first+ is builtin). Thanks to social wisdom and positive constructiveness all around, +forty_two+ is also available. You can pick a random element with +rand+: shape_type = [Circle, Square, Triangle].rand NOTE: Defined in +active_support/core_ext/array/access.rb+. h4. Options Extraction When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets: User.exists?(:email => params[:email]) That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options. If a method expects a variable number of arguments and uses * in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role. In those cases, you may give an options hash a distinguished treatment with +extract_options!+. That method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise returns an empty hash. Let's see for example the definition of the +caches_action+ controller macro: def caches_action(*actions) return unless cache_configured? options = actions.extract_options! ... end This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to +extract_options!+ you obtain the options hash and remove it from +actions+ in a simple and explicit way. NOTE: Defined in +active_support/core_ext/array/extract_options.rb+. h4. Conversions h5. +to_sentence+ The method +to_sentence+ turns an array into a string containing a sentence that enumerates its items: %w().to_sentence # => "" %w(Earth).to_sentence # => "Earth" %w(Earth Wind).to_sentence # => "Earth and Wind" %w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire" This method accepts three options: * :two_words_connector: What is used for arrays of length 2. Default is " and ". * :words_connector: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ". * :last_word_connector: What is used to join the last items of an array with 3 or more elements. Default is ", and ". The defaults for these options can be localised, their keys are: |_. Option |_. I18n key | | :two_words_connector | support.array.two_words_connector | | :words_connector | support.array.words_connector | | :last_word_connector | support.array.last_word_connector | Options :connector and :skip_last_comma are deprecated. NOTE: Defined in +active_support/core_ext/array/conversions.rb+. h5. +to_formatted_s+ The method +to_formatted_s+ acts like +to_s+ by default. If the array contains items that respond to +id+, however, it may be passed the symbol :db as argument. That's typically used with collections of ARs, though technically any object in Ruby 1.8 responds to +id+ indeed. Returned strings are: [].to_formatted_s(:db) # => "null" [user].to_formatted_s(:db) # => "8456" invoice.lines.to_formatted_s(:db) # => "23,567,556,12" Integers in the example above are supposed to come from the respective calls to +id+. NOTE: Defined in +active_support/core_ext/array/conversions.rb+. h5. +to_xml+ The method +to_xml+ returns a string containing an XML representation of its receiver: Contributor.all(:limit => 2, :order => 'rank ASC').to_xml # => # # # # 4356 # Jeremy Kemper # 1 # jeremy-kemper # # # 4404 # David Heinemeier Hansson # 2 # david-heinemeier-hansson # # To do so it sends +to_xml+ to every item in turn, and collects the results under a root node. All items must respond to +to_xml+, an exception is raised otherwise. By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with is_a?) and they are not hashes. In the example above that's "contributors". If there's any element that does not belong to the type of the first one the root node becomes "records": [Contributor.first, Commit.first].to_xml # => # # # # 4583 # Aaron Batalion # 53 # aaron-batalion # # # Joshua Peek # 2009-09-02T16:44:36Z # origin/master # 2009-09-02T16:44:36Z # Joshua Peek # # 190316 # false # Kill AMo observing wrap_with_notifications since ARes was only using it # 723a47bfb3708f968821bc969a9a3fc873a3ed58 # # If the receiver is an array of hashes the root element is by default also "records": [{:a => 1, :b => 2}, {:c => 3}].to_xml # => # # # # 2 # 1 # # # 3 # # WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the :root option to ensure a consistent root element. The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "record". The option :children allows you to set these node names. The default XML builder is a fresh instance of Builder::XmlMarkup. You can configure your own builder via the :builder option. The method also accepts options like :dasherize and friends, they are forwarded to the builder: Contributor.all(:limit => 2, :order => 'rank ASC').to_xml(:skip_types => true) # => # # # # 4356 # Jeremy Kemper # 1 # jeremy-kemper # # # 4404 # David Heinemeier Hansson # 2 # david-heinemeier-hansson # # NOTE: Defined in +active_support/core_ext/array/conversions.rb+. h4. Wrapping The class method +Array.wrap+ behaves like the function +Array()+ except that it does not try to call +to_a+ on its argument. That changes the behaviour for enumerables: Array.wrap(:foo => :bar) # => [{:foo => :bar}] Array(:foo => :bar) # => [[:foo, :bar]] Array.wrap("foo\nbar") # => ["foo\nbar"] Array("foo\nbar") # => ["foo\n", "bar"], in Ruby 1.8 NOTE: Defined in +active_support/core_ext/array/wrap.rb+. h4. Grouping h5. +in_groups_of(number, fill_with = nil)+ The method +in_groups_of+ splits an array into consecutive groups of a certain size. It returns an array with the groups: [1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]] or yields them in turn if a block is passed: <% sample.in_groups_of(3) do |a, b, c| %> <%=h a %> <%=h b %> <%=h c %> <% end %> The first example shows +in_groups_of+ fills the last group with as many +nil+ elements as needed to have the requested size. You can change this padding value using the second optional argument: [1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]] And you can tell the method not to fill the last group passing +false+: [1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]] As a consequence +false+ can't be a used as a padding value. NOTE: Defined in +active_support/core_ext/array/grouping.rb+. h5. +in_groups(number, fill_with = nil)+ The method +in_groups+ splits an array into a certain number of groups. The method returns and array with the groups: %w(1 2 3 4 5 6 7).in_groups(3) # => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]] or yields them in turn if a block is passed: %w(1 2 3 4 5 6 7).in_groups(3) {|group| p group} ["1", "2", "3"] ["4", "5", nil] ["6", "7", nil] The examples above show that +in_groups+ fills some groups with a trailing +nil+ element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones. You can change this padding value using the second optional argument: %w(1 2 3 4 5 6 7).in_groups(3, "0") # => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]] And you can tell the method not to fill the smaller groups passing +false+: %w(1 2 3 4 5 6 7).in_groups(3, false) # => [["1", "2", "3"], ["4", "5"], ["6", "7"]] As a consequence +false+ can't be a used as a padding value. NOTE: Defined in +active_support/core_ext/array/grouping.rb+. h5. +split(value = nil)+ The method +split+ divides an array by a separator and returns the resulting chunks. If a block is passed the separators are those elements of the array for which the block returns true: (-5..5).to_a.split { |i| i.multiple_of?(4) } # => [[-5], [-3, -2, -1], [1, 2, 3], [5]] Otherwise, the value received as argument, which defaults to +nil+, is the separator: [0, 1, -5, 1, 1, "foo", "bar"].split(1) # => [[0], [-5], [], ["foo", "bar"]] TIP: Observe in the previous example that consecutive separators result in empty arrays. NOTE: Defined in +active_support/core_ext/array/grouping.rb+. h3. Extensions to +Hash+ h4(#hash-conversions). Conversions h5(#hash-to-xml). +to_xml+ The method +to_xml+ returns a string containing an XML representation of its receiver: {"foo" => 1, "bar" => 2}.to_xml # => # # # 1 # 2 # To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair +key+, +value+: * If +value+ is a hash there's a recursive call with +key+ as :root. * If +value+ is an array there's a recursive call with +key+ as :root, and +key+ singularized as :children. * If +value+ is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the +options+ hash as first argument with +key+ as :root, and +key+ singularized as second argument. Its return value becomes a new node. * If +value+ responds to +to_xml+ the method is invoked with +key+ as :root. * Otherwise, a node with +key+ as tag is created with a string representation of +value+ as text node. If +value+ is +nil+ an attribute "nil" set to "true" is added. Unless the option :skip_types exists and is true, an attribute "type" is added as well according to the following mapping: XML_TYPE_NAMES = { "Symbol" => "symbol", "Fixnum" => "integer", "Bignum" => "integer", "BigDecimal" => "decimal", "Float" => "float", "TrueClass" => "boolean", "FalseClass" => "boolean", "Date" => "date", "DateTime" => "datetime", "Time" => "datetime" } By default the root node is "hash", but that's configurable via the :root option. The default XML builder is a fresh instance of Builder::XmlMarkup. You can configure your own builder with the :builder option. The method also accepts options like :dasherize and friends, they are forwarded to the builder. NOTE: Defined in +active_support/core_ext/hash/conversions.rb+. h4. Merging Ruby has a builtin method +Hash#merge+ that merges two hashes: {:a => 1, :b => 1}.merge(:a => 0, :c => 2) # => {:a => 0, :b => 1, :c => 2} Active Support defines a few more ways of merging hashes that may be convenient. h5. +reverse_merge+ and +reverse_merge!+ In case of collision the key in the hash of the argument wins in +merge+. You can support option hashes with default values in a compact way with this idiom: options = {:length => 30, :omission => "..."}.merge(options) Active Support defines +reverse_merge+ in case you prefer this alternative notation: options = options.reverse_merge(:length => 30, :omission => "...") And a bang version +reverse_merge!+ that performs the merge in place: options.reverse_merge!(:length => 30, :omission => "...") WARNING. Take into account that +reverse_merge!+ may change the hash in the caller, which may or may not be a good idea. NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+. h5. +reverse_update+ The method +reverse_update+ is an alias for +reverse_merge!+, explained above. WARNING. Note that +reverse_update+ has no bang. NOTE: Defined in +active_support/core_ext/hash/reverse_merge.rb+. h5. +deep_merge+ and +deep_merge!+ As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins. Active Support defines +Hash#deep_merge+. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash: {:a => {:b => 1}}.deep_merge(:a => {:c => 2}) # => {:a => {:b => 1, :c => 2}} The method +deep_merge!+ performs a deep merge in place. NOTE: Defined in +active_support/core_ext/hash/deep_merge.rb+. h4. Diffing The method +diff+ returns a hash that represents a diff of the receiver and the argument with the following logic: * Pairs +key+, +value+ that exist in both hashes do not belong to the diff hash. * If both hashes have +key+, but with different values, the pair in the receiver wins. * The rest is just merged. {:a => 1}.diff(:a => 1) # => {}, first rule {:a => 1}.diff(:a => 2) # => {:a => 1}, second rule {:a => 1}.diff(:b => 2) # => {:a => 1, :b => 2}, third rule {:a => 1, :b => 2, :c => 3}.diff(:b => 1, :c => 3, :d => 4) # => {:a => 1, :b => 2, :d => 4}, all rules {}.diff({}) # => {} {:a => 1}.diff({}) # => {:a => 1} {}.diff(:a => 1) # => {:a => 1} An important property of this diff hash is that you can retrieve the original hash by applying +diff+ twice: hash.diff(hash2).diff(hash2) == hash Diffing hashes may be useful for error messages related to expected option hashes for example. NOTE: Defined in +active_support/core_ext/hash/diff.rb+. h4. Working with Keys h5. +except+ and +except!+ The method +except+ returns a hash with the keys in the argument list removed, if present: {:a => 1, :b => 2}.except(:a) # => {:b => 2} If the receiver responds to +convert_key+, the method is called on each of the arguments. This allows +except+ to play nice with hashes with indifferent access for instance: {:a => 1}.with_indifferent_access.except(:a) # => {} {:a => 1}.with_indifferent_access.except("a") # => {} The method +except+ may come in handy for example when you want to protect some parameter that can't be globally protected with +attr_protected+: params[:account] = params[:account].except(:plan_id) unless admin? @account.update_attributes(params[:account]) There's also the bang variant +except!+ that removes keys in the very receiver. NOTE: Defined in +active_support/core_ext/hash/except.rb+. h5. +stringify_keys+ and +stringify_keys!+ The method +stringify_keys+ returns a hash that has a stringified version of the keys in the receiver. It does so by sending +to_s+ to them: {nil => nil, 1 => 1, :a => :a}.stringify_keys # => {"" => nil, "a" => :a, "1" => 1} The result in case of collision is undefined: {"a" => 1, :a => 2}.stringify_keys # => {"a" => 2}, in my test, can't rely on this result though This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionView::Helpers::FormHelper+ defines: def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0") options = options.stringify_keys options["type"] = "checkbox" ... end The second line can safely access the "type" key, and let the user to pass either +:type+ or "type". There's also the bang variant +stringify_keys!+ that stringifies keys in the very receiver. NOTE: Defined in +active_support/core_ext/hash/keys.rb+. h5. +symbolize_keys+ and +symbolize_keys!+ The method +symbolize_keys+ returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending +to_sym+ to them: {nil => nil, 1 => 1, "a" => "a"}.symbolize_keys # => {1 => 1, nil => nil, :a => "a"} WARNING. Note in the previous example only one key was symbolized. The result in case of collision is undefined: {"a" => 1, :a => 2}.symbolize_keys # => {:a => 2}, in my test, can't rely on this result though This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionController::UrlRewriter+ defines def rewrite_path(options) options = options.symbolize_keys options.update(options[:params].symbolize_keys) if options[:params] ... end The second line can safely access the +:params+ key, and let the user to pass either +:params+ or "params". There's also the bang variant +symbolize_keys!+ that symbolizes keys in the very receiver. NOTE: Defined in +active_support/core_ext/hash/keys.rb+. h5. +to_options+ and +to_options!+ The methods +to_options+ and +to_options!+ are respectively aliases of +symbolize_keys+ and +symbolize_keys!+. NOTE: Defined in +active_support/core_ext/hash/keys.rb+. h5. +assert_valid_keys+ The method +assert_valid_keys+ receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does +ArgumentError+ is raised. {:a => 1}.assert_valid_keys(:a) # passes {:a => 1}.assert_valid_keys("a") # ArgumentError Active Record does not accept unknown options when building associations for example. It implements that control via +assert_valid_keys+: mattr_accessor :valid_keys_for_has_many_association @@valid_keys_for_has_many_association = [ :class_name, :table_name, :foreign_key, :primary_key, :dependent, :select, :conditions, :include, :order, :group, :having, :limit, :offset, :as, :through, :source, :source_type, :uniq, :finder_sql, :counter_sql, :before_add, :after_add, :before_remove, :after_remove, :extend, :readonly, :validate, :inverse_of ] def create_has_many_reflection(association_id, options, &extension) options.assert_valid_keys(valid_keys_for_has_many_association) ... end NOTE: Defined in +active_support/core_ext/hash/keys.rb+. h4. Slicing Ruby has builtin support for taking slices out of strings and arrays. Active Support extends slicing to hashes: {:a => 1, :b => 2, :c => 3}.slice(:a, :c) # => {:c => 3, :a => 1} {:a => 1, :b => 2, :c => 3}.slice(:b, :X) # => {:b => 2} # non-existing keys are ignored If the receiver responds to +convert_key+ keys are normalized: {:a => 1, :b => 2}.with_indifferent_access.slice("a") # => {:a => 1} NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys. There's also +slice!+ which in addition to perform a slice in place returns what's removed: hash = {:a => 1, :b => 2} rest = hash.slice!(:a) # => {:b => 2} hash # => {:a => 1} NOTE: Defined in +active_support/core_ext/hash/slice.rb+. h4. Indifferent Access The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver: {:a => 1}.with_indifferent_access["a"] # => 1 NOTE: Defined in +active_support/core_ext/hash/indifferent_access.rb+. h3. Extensions to +Regexp+ h4. +multiline?+ The method +multiline?+ says whether a regexp has the +/m+ flag set, that is, whether the dot matches newlines. %r{.}.multiline? # => false %r{.}m.multiline? # => true Regexp.new('.').multiline? # => false Regexp.new('.', Regexp::MULTILINE).multiline? # => true Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint. def assign_route_options(segments, defaults, requirements) ... if requirement.multiline? raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}" end ... end NOTE: Defined in +active_support/core_ext/regexp.rb+. h3. Extensions to +Range+ h4. +to_s+ Active Support extends the method +Range#to_s+ so that it understands an optional format argument. As of this writing the only supported non-default format is +:db+: (Date.today..Date.tomorrow).to_s # => "2009-10-25..2009-10-26" (Date.today..Date.tomorrow).to_s(:db) # => "BETWEEN '2009-10-25' AND '2009-10-26'" As the example depicts, the +:db+ format generates a +BETWEEN+ SQL clause. That is used by Active Record in its support for range values in conditions. NOTE: Defined in +active_support/core_ext/range/conversions.rb+. h4. +step+ Active Support extends the method +Range#step+ so that it can be invoked without a block: (1..10).step(2) # => [1, 3, 5, 7, 9] As the example shows, in that case the method returns and array with the corresponding elements. NOTE: Defined in +active_support/core_ext/range/blockless_step.rb+. h4. +include?+ The method +Range#include?+ says whether some value falls between the ends of a given instance: (2..3).include?(Math::E) # => true Active Support extends this method so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves: (1..10).include?(3..7) # => true (1..10).include?(0..7) # => false (1..10).include?(3..11) # => false (1...9).include?(3..9) # => false WARNING: The orginal +Range#include?+ is still the one aliased to +Range#===+. NOTE: Defined in +active_support/core_ext/range/include_range.rb+. h4. +overlaps?+ The method +Range#overlaps?+ says whether any two given ranges have non-void intersection: (1..10).overlaps?(7..11) # => true (1..10).overlaps?(0..7) # => true (1..10).overlaps?(11..27) # => false NOTE: Defined in +active_support/core_ext/range/overlaps.rb+. h3. Extensions to +Proc+ h4. +bind+ As you surely know Ruby has an +UnboundMethod+ class whose instances are methods that belong to the limbo of methods without a self. The method +Module#instance_method+ returns an unbound method for example: Hash.instance_method(:delete) # => # An unbound method is not callable as is, you need to bind it first to an object with +bind+: clear = Hash.instance_method(:clear) clear.bind({:a => 1}).call # => {} Active Support defines +Proc#bind+ with an analogous purpose: Proc.new { size }.bind([]).call # => 0 As you see that's callable and bound to the argument, the return value is indeed a +Method+. NOTE: To do so +Proc#bind+ actually creates a method under the hood. If you ever see a method with a weird name like +__bind_1256598120_237302+ in a stack trace you know now where it comes from. Action Pack uses this trick in +rescue_from+ for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by +handler_for_rescue+, thus simplifying the code in the caller: def handler_for_rescue(exception) _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler| ... end case rescuer when Symbol method(rescuer) when Proc rescuer.bind(self) end end NOTE: Defined in +active_support/core_ext/proc.rb+. h3. Extensions to +Date+ ... h3. Extensions to +DateTime+ ... h3. Extensions to +Time+ ... h3. Extensions to +Process+ ... h3. Extensions to +Pathname+ ... h3. Extensions to +File+ h4. +atomic_write+ With the class method +File.atomic_write+ you can write to a file in a way that will prevent any reader from seeing half-written content. The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done +atomic_write+ closes the file handle and completes its job. For example, Action Pack uses this method to write asset cache files like +all.css+: File.atomic_write(joined_asset_path) do |cache| cache.write(join_asset_file_contents(asset_paths)) end To accomplish this +atomic_write+ creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists +atomic_write+ overwrites it and keeps owners and permissions. WARNING. Note you can't append with +atomic_write+. The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument. NOTE: Defined in +active_support/core_ext/file/atomic.rb+. h3. Extensions to +NameError+ Active Support adds +missing_name?+ to +NameError+, which tests whether the exception was raised because of the name passed as argument. The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name. TIP: A symbol can represent a fully-qualified constant name as in +:"ActiveRecord::Base"+, so the behaviour for symbols is defined for convenience, not because it has to be that way technically. For example, when an action of +PostsController+ is called Rails tries optimistically to use +PostsHelper+. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that +posts_helper.rb+ raises a +NameError+ due to an actual unknown constant. That should be reraised. The method +missing_name?+ provides a way to distinguish both cases: def default_helper_module! module_name = name.sub(/Controller$/, '') module_path = module_name.underscore helper module_path rescue MissingSourceFile => e raise e unless e.is_missing? "#{module_path}_helper" rescue NameError => e raise e unless e.missing_name? "#{module_name}Helper" end NOTE: Defined in +active_support/core_ext/name_error.rb+. h3. Extensions to +LoadError+ Active Support adds +is_missing?+ to +LoadError+, and also assigns that class to the constant +MissingSourceFile+ for backwards compatibility. Given a path name +is_missing?+ tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension). For example, when an action of +PostsController+ is called Rails tries to load +posts_helper.rb+, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method +is_missing?+ provides a way to distinguish both cases: def default_helper_module! module_name = name.sub(/Controller$/, '') module_path = module_name.underscore helper module_path rescue MissingSourceFile => e raise e unless e.is_missing? "helpers/#{module_path}_helper" rescue NameError => e raise e unless e.missing_name? "#{module_name}Helper" end NOTE: Defined in +active_support/core_ext/load_error.rb+. h3. Changelog "Lighthouse ticket":https://rails.lighthouseapp.com/projects/16213/tickets/67 * April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn