Skip to content
This repository
Browse code

AS guide: removes CGI placeholder section, CGI.escape_skipping_slashe…

…s seems something for internal use
  • Loading branch information...
commit 7c56071c3a3cf3a6d8327e21b5fa8094cb779689 1 parent 97e02fa
Xavier Noria authored October 25, 2009
4  railties/guides/source/active_support_core_extensions.textile
Source Rendered
@@ -1728,10 +1728,6 @@ rescue NameError => e
1728 1728
 end
1729 1729
 </ruby>
1730 1730
 
1731  
-h3. Extensions to +CGI+
1732  
-
1733  
-...
1734  
-
1735 1731
 h3. Extensions to +Benchmark+
1736 1732
 
1737 1733
 ...
1,742  railties/guides/source/active_support_overview.textile
Source Rendered
... ...
@@ -1,1742 +0,0 @@
1  
-h2. Active Support Overview
2  
-
3  
-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.
4  
-
5  
-By referring to this guide you will learn:
6  
-
7  
-* The extensions to the Ruby core modules and classes provided by Rails.
8  
-* The rest of fundamental libraries available in Rails.
9  
-
10  
-endprologue.
11  
-
12  
-h3. Extensions to All Objects
13  
-
14  
-h4. +blank?+ and +present?+
15  
-
16  
-The following values are considered to be blank in a Rails application:
17  
-
18  
-* +nil+ and +false+,
19  
-
20  
-* strings composed only of whitespace, i.e. matching +/\A\s*\z/+,
21  
-
22  
-* empty arrays and hashes, and
23  
-
24  
-* any other object that responds to +empty?+ and it is empty.
25  
-
26  
-WARNING: Note that numbers are not mentioned, in particular 0 and 0.0 are *not* blank.
27  
-
28  
-For example, this method from +ActionDispatch::Response+ uses +blank?+ to easily be robust to +nil+ and whitespace strings in one shot:
29  
-
30  
-<ruby>
31  
-def charset
32  
-  charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
33  
-  charset.blank? ? nil : charset.strip.split("=")[1]
34  
-end
35  
-</ruby>
36  
-
37  
-That's a typical use case for +blank?+.
38  
-
39  
-Here, the method Rails runs to instantiate observers upon initialization has nothing to do if there are none:
40  
-
41  
-<ruby>
42  
-def instantiate_observers
43  
-  return if @observers.blank?
44  
-  # ...
45  
-end
46  
-</ruby>
47  
-
48  
-The method +present?+ is equivalent to +!blank?+:
49  
-
50  
-<ruby>
51  
-assert @response.body.present? # same as !@response.body.blank?
52  
-</ruby>
53  
-
54  
-h4. +duplicable?+
55  
-
56  
-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:
57  
-
58  
-<ruby>
59  
-1.object_id                 # => 3
60  
-Math.cos(0).to_i.object_id  # => 3
61  
-</ruby>
62  
-
63  
-Hence, there's no way these objects can be duplicated through +dup+ or +clone+:
64  
-
65  
-<ruby>
66  
-true.dup  # => TypeError: can't dup TrueClass
67  
-</ruby>
68  
-
69  
-Some numbers which are not singletons are not duplicable either:
70  
-
71  
-<ruby>
72  
-0.0.clone        # => allocator undefined for Float
73  
-(2**1024).clone  # => allocator undefined for Bignum
74  
-</ruby>
75  
-
76  
-Active Support provides +duplicable?+ to programmatically query an object about this property:
77  
-
78  
-<ruby>
79  
-"".duplicable?     # => true
80  
-false.duplicable?  # => false
81  
-</ruby>
82  
-
83  
-By definition all objects are +duplicable?+ except +nil+, +false+, +true+, symbols, numbers, and class objects.
84  
-
85  
-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.
86  
-
87  
-h4. +returning+
88  
-
89  
-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:
90  
-
91  
-<ruby>
92  
-def html_options_for_form(url_for_options, options, *parameters_for_url)
93  
-  returning options.stringify_keys do |html_options|
94  
-    html_options["enctype"] = "multipart/form-data" if html_options.delete("multipart")
95  
-    html_options["action"]  = url_for(url_for_options, *parameters_for_url)
96  
-  end
97  
-end
98  
-</ruby>
99  
-
100  
-See also "+Object#tap+":#tap.
101  
-
102  
-h4. +tap+
103  
-
104  
-+Object#tap+ exists in Ruby 1.8.7 and 1.9, and it is defined by Active Support for previous versions. This method yields its receiver to a block and returns it.
105  
-
106  
-For example, the following class method from +ActionDispatch::TestResponse+ creates, initializes, and returns a new test response using +tap+:
107  
-
108  
-<ruby>
109  
-def self.from_response(response)
110  
-  new.tap do |resp|
111  
-    resp.status  = response.status
112  
-    resp.headers = response.headers
113  
-    resp.body    = response.body
114  
-  end
115  
-end
116  
-</ruby>
117  
-
118  
-See also "+Object#returning+":#returning.
119  
-
120  
-h4. +try+
121  
-
122  
-Sometimes you want to call a method provided the receiver object is not +nil+, which is something you usually check first.
123  
-
124  
-For instance, note how this method of +ActiveRecord::ConnectionAdapters::AbstractAdapter+ checks if there's a +@logger+:
125  
-
126  
-<ruby>
127  
-def log_info(sql, name, ms)
128  
-  if @logger && @logger.debug?
129  
-    name = '%s (%.1fms)' % [name || 'SQL', ms]
130  
-    @logger.debug(format_log_entry(name, sql.squeeze(' ')))
131  
-  end
132  
-end
133  
-</ruby>
134  
-
135  
-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:
136  
-
137  
-<ruby>
138  
-def log_info(sql, name, ms)
139  
-  if @logger.try(:debug?)
140  
-    name = '%s (%.1fms)' % [name || 'SQL', ms]
141  
-    @logger.debug(format_log_entry(name, sql.squeeze(' ')))
142  
-  end
143  
-end
144  
-</ruby>
145  
-
146  
-h4. +metaclass+
147  
-
148  
-The method +metaclass+ returns the singleton class on any object:
149  
-
150  
-<ruby>
151  
-String.metaclass     # => #<Class:String>
152  
-String.new.metaclass # => #<Class:#<String:0x17a1d1c>>
153  
-</ruby>
154  
-
155  
-h4. +class_eval(*args, &block)+
156  
-
157  
-You can evaluate code in the context of any object's singleton class using +class_eval+:
158  
-
159  
-<ruby>
160  
-class Proc
161  
-  def bind(object)
162  
-    block, time = self, Time.now
163  
-    object.class_eval do
164  
-      method_name = "__bind_#{time.to_i}_#{time.usec}"
165  
-      define_method(method_name, &block)
166  
-      method = instance_method(method_name)
167  
-      remove_method(method_name)
168  
-      method
169  
-    end.bind(object)
170  
-  end
171  
-end
172  
-</ruby>
173  
-
174  
-h4. +acts_like?(duck)+
175  
-
176  
-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
177  
-
178  
-<ruby>
179  
-def acts_like_string?
180  
-end
181  
-</ruby>
182  
-
183  
-which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:
184  
-
185  
-<ruby>
186  
-some_klass.acts_like?(:string)
187  
-</ruby>
188  
-
189  
-Rails has classes that act like +Date+ or +Time+ and follow this contract.
190  
-
191  
-h4. +to_param+
192  
-
193  
-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.
194  
-
195  
-By default +to_param+ just calls +to_s+:
196  
-
197  
-<ruby>
198  
-7.to_param # => "7"
199  
-</ruby>
200  
-
201  
-The return value of +to_param+ should *not* be escaped:
202  
-
203  
-<ruby>
204  
-"Tom & Jerry".to_param # => "Tom & Jerry"
205  
-</ruby>
206  
-
207  
-Several classes in Rails overwrite this method.
208  
-
209  
-For example +nil+, +true+, and +false+ return themselves. +Array#to_param+ calls +to_param+ on the elements and joins the result with "/":
210  
-
211  
-<ruby>
212  
-[0, true, String].to_param # => "0/true/String"
213  
-</ruby>
214  
-
215  
-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
216  
-
217  
-<ruby>
218  
-class User
219  
-  def to_param
220  
-    "#{id}-#{name.parameterize}"
221  
-  end
222  
-end
223  
-</ruby>
224  
-
225  
-we get:
226  
-
227  
-<ruby>
228  
-user_path(@user) # => "/users/357-john-smith"
229  
-</ruby>
230  
-
231  
-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]+.
232  
-
233  
-h4. +to_query+
234  
-
235  
-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
236  
-
237  
-<ruby>
238  
-class User
239  
-  def to_param
240  
-    "#{id}-#{name.parameterize}"
241  
-  end
242  
-end
243  
-</ruby>
244  
-
245  
-we get:
246  
-
247  
-<ruby>
248  
-current_user.to_query('user') # => user=357-john-smith
249  
-</ruby>
250  
-
251  
-This method escapes whatever is needed, both for the key and the value:
252  
-
253  
-<ruby>
254  
-account.to_query('company[name]')
255  
-# => "company%5Bname%5D=Johnson+%26+Johnson"
256  
-</ruby>
257  
-
258  
-so its output is ready to be used in a query string.
259  
-
260  
-Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "&":
261  
-
262  
-<ruby>
263  
-[3.4, -45.6].to_query('sample')
264  
-# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
265  
-</ruby>
266  
-
267  
-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 "&":
268  
-
269  
-<ruby>
270  
-{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
271  
-</ruby>
272  
-
273  
-The method +Hash#to_query+ accepts an optional namespace for the keys:
274  
-
275  
-<ruby>
276  
-{:id => 89, :name => "John Smith"}.to_query('user')
277  
-# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
278  
-</ruby>
279  
-
280  
-h4. +with_options+
281  
-
282  
-The method +with_options+ provides a way to factor out common options in a series of method calls.
283  
-
284  
-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:
285  
-
286  
-<ruby>
287  
-class Account < ActiveRecord::Base
288  
-  has_many :customers, :dependent => :destroy
289  
-  has_many :products,  :dependent => :destroy
290  
-  has_many :invoices,  :dependent => :destroy
291  
-  has_many :expenses,  :dependent => :destroy
292  
-end
293  
-</ruby>
294  
-
295  
-this way:
296  
-
297  
-<ruby>
298  
-class Account < ActiveRecord::Base
299  
-  with_options :dependent => :destroy do |assoc|
300  
-    assoc.has_many :customers
301  
-    assoc.has_many :products
302  
-    assoc.has_many :invoices
303  
-    assoc.has_many :expenses
304  
-  end
305  
-end
306  
-</ruby>
307  
-
308  
-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:
309  
-
310  
-<ruby>
311  
-I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
312  
-  subject i18n.t :subject
313  
-  body    i18n.t :body, :user_name => user.name 
314  
-end
315  
-</ruby>
316  
-
317  
-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.
318  
-
319  
-h4. Instance Variables
320  
-
321  
-Active Support provides several methods to ease access to instance variables.
322  
-
323  
-h5. +instance_variable_defined?+
324  
-
325  
-The method +instance_variable_defined?+ exists in Ruby 1.8.6 and later, and it is defined for previous versions anyway:
326  
-
327  
-<ruby>
328  
-class C
329  
-  def initialize
330  
-    @a = 1
331  
-  end
332  
-
333  
-  def m
334  
-    @b = 2
335  
-  end
336  
-end
337  
-
338  
-c = C.new
339  
-
340  
-c.instance_variable_defined?("@a") # => true
341  
-c.instance_variable_defined?(:@a)  # => true
342  
-c.instance_variable_defined?("a")  # => NameError: `a' is not allowed as an instance variable name
343  
-
344  
-c.instance_variable_defined?("@b") # => false
345  
-c.m
346  
-c.instance_variable_defined?("@b") # => true
347  
-</ruby>
348  
-
349  
-h5. +instance_variable_names+
350  
-
351  
-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:
352  
-
353  
-<ruby>
354  
-class C
355  
-  def initialize(x, y)
356  
-    @x, @y = x, y
357  
-  end
358  
-end
359  
-
360  
-C.new(0, 1).instance_variable_names # => ["@y", "@x"]
361  
-</ruby>
362  
-
363  
-WARNING: The order in which the names are returned is unespecified, and it indeed depends on the version of the interpreter.
364  
-
365  
-h5. +instance_values+
366  
-
367  
-The method +instance_values+ returns a hash that maps instance variable names without "@" to their
368  
-corresponding values. Keys are strings both in Ruby 1.8 and 1.9:
369  
-
370  
-<ruby>
371  
-class C
372  
-  def initialize(x, y)
373  
-    @x, @y = x, y
374  
-  end
375  
-end
376  
-
377  
-C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
378  
-</ruby>
379  
-
380  
-h5. +copy_instance_variables_from(object, exclude = [])+
381  
-
382  
-Copies the instance variables of +object+ into +self+.
383  
-
384  
-Instance variable names in the +exclude+ array are ignored. If +object+
385  
-responds to +protected_instance_variables+ the ones returned are
386  
-also ignored. For example, Rails controllers implement that method.
387  
-
388  
-In both arrays strings and symbols are understood, and they have to include
389  
-the at sign.
390  
-
391  
-<ruby>
392  
-class C
393  
-  def initialize(x, y, z)
394  
-    @x, @y, @z = x, y, z
395  
-  end
396  
-
397  
-  def protected_instance_variables
398  
-    %w(@z)
399  
-  end
400  
-end
401  
-
402  
-a = C.new(0, 1, 2)
403  
-b = C.new(3, 4, 5)
404  
-
405  
-a.copy_instance_variables_from(b, [:@y])
406  
-# a is now: @x = 3, @y = 1, @z = 2
407  
-</ruby>
408  
-
409  
-In the example +object+ and +self+ are of the same type, but they don't need to.
410  
-
411  
-h4. Silencing Warnings, Streams, and Exceptions
412  
-
413  
-The methods +silence_warnings+ and +enable_warnings+ change the value of +$VERBOSE+ accordingly for the duration of their block, and reset it afterwards:
414  
-
415  
-<ruby>
416  
-silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
417  
-</ruby>
418  
-
419  
-You can silence any stream while a block runs with +silence_stream+:
420  
-
421  
-<ruby>
422  
-silence_stream(STDOUT) do
423  
-  # STDOUT is silent here
424  
-end
425  
-</ruby>
426  
-
427  
-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:
428  
-
429  
-<ruby>
430  
-# If the user is locked the increment is lost, no big deal.
431  
-suppress(ActiveRecord::StaleObjectError) do
432  
-  current_user.increment! :visits
433  
-end
434  
-</ruby>
435  
-
436  
-h3. Extensions to +Module+
437  
-
438  
-h4. Aliasing
439  
-
440  
-h5. +alias_method_chain+
441  
-
442  
-Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
443  
-
444  
-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+:
445  
-
446  
-<ruby>
447  
-ActionController::TestCase.class_eval do
448  
-  # save a reference to the original process method
449  
-  alias_method :original_process, :process
450  
-
451  
-  # now redefine process and delegate to original_process
452  
-  def process(action, params=nil, session=nil, flash=nil, http_method='GET')
453  
-    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
454  
-    original_process(action, params, session, flash, http_method)
455  
-  end
456  
-end
457  
-</ruby>
458  
-
459  
-That's the method +get+, +post+, etc., delegate the work to.
460  
-
461  
-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:
462  
-
463  
-<ruby>
464  
-ActionController::TestCase.class_eval do
465  
-  def process_with_stringified_params(...)
466  
-    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
467  
-    process_without_stringified_params(action, params, session, flash, http_method)
468  
-  end
469  
-  alias_method :process_without_stringified_params, :process
470  
-  alias_method :process, :process_with_stringified_params
471  
-end
472  
-</ruby>
473  
-
474  
-The method +alias_method_chain+ provides a shortcut for that pattern:
475  
-
476  
-<ruby>
477  
-ActionController::TestCase.class_eval do
478  
-  def process_with_stringified_params(...)
479  
-    params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
480  
-    process_without_stringified_params(action, params, session, flash, http_method)
481  
-  end
482  
-  alias_method_chain :process, :stringified_params
483  
-end
484  
-</ruby>
485  
-
486  
-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.
487  
-
488  
-h5. +alias_attribute+
489  
-
490  
-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):
491  
-
492  
-<ruby>
493  
-class User < ActiveRecord::Base
494  
-  # let me refer to the email column as "login",
495  
-  # much meaningful for authentication code
496  
-  alias_attribute :login, :email
497  
-end
498  
-</ruby>
499  
-
500  
-h3. Extensions to +Class+
501  
-
502  
-h4. Class Attribute Accessors
503  
-
504  
-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:
505  
-
506  
-<ruby>
507  
-class MysqlAdapter < AbstractAdapter
508  
-  # Generates class methods to access @@emulate_booleans.
509  
-  cattr_accessor :emulate_booleans
510  
-  self.emulate_booleans = true
511  
-end
512  
-</ruby>
513  
-
514  
-Instance methods are created as well for convenience. For example given
515  
-
516  
-<ruby>
517  
-module ActionController
518  
-  class Base
519  
-    cattr_accessor :logger
520  
-  end
521  
-end
522  
-</ruby>
523  
-
524  
-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+):
525  
-
526  
-<ruby>
527  
-module ActiveRecord
528  
-  class Base
529  
-    # No pluralize_table_names= instance writer is generated.
530  
-    cattr_accessor :pluralize_table_names, :instance_writer => false
531  
-  end
532  
-end
533  
-</ruby>
534  
-
535  
-h4. Class Inheritable Attributes
536  
-
537  
-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:
538  
-
539  
-<ruby>
540  
-module ActionController
541  
-  class Base
542  
-    # FIXME: REVISE/SIMPLIFY THIS COMMENT.
543  
-    # The value of allow_forgery_protection is inherited,
544  
-    # but its value in a particular class does not affect
545  
-    # the value in the rest of the controllers hierarchy.
546  
-    class_inheritable_accessor :allow_forgery_protection
547  
-  end
548  
-end
549  
-</ruby>
550  
-
551  
-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.
552  
-
553  
-There are some variants specialised in arrays and hashes:
554  
-
555  
-<ruby>
556  
-class_inheritable_array
557  
-class_inheritable_hash
558  
-</ruby>
559  
-
560  
-Those writers take any inherited array or hash into account and extend them rather than overwrite them.
561  
-
562  
-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+):
563  
-
564  
-<ruby>
565  
-module ActiveRecord
566  
-  class Base
567  
-    class_inheritable_accessor :default_scoping, :instance_writer => false
568  
-  end
569  
-end
570  
-</ruby>
571  
-
572  
-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. 
573  
-
574  
-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:
575  
-
576  
-<ruby>
577  
-module ActionMailer
578  
-  class Base
579  
-    superclass_delegating_accessor :delivery_method
580  
-    self.delivery_method = :smtp
581  
-  end
582  
-end
583  
-</ruby>
584  
-
585  
-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.
586  
-
587  
-h4. Subclasses
588  
-
589  
-The +subclasses+ method returns the names of all subclasses of a given class as an array of strings. That comprises not only direct subclasses, but all descendants down the hierarchy:
590  
-
591  
-<ruby>
592  
-class C; end
593  
-C.subclasses # => []
594  
-
595  
-Integer.subclasses # => ["Bignum", "Fixnum"]
596  
-
597  
-module M
598  
-  class A; end
599  
-  class B1 < A; end
600  
-  class B2 < A; end
601  
-end
602  
-
603  
-module N
604  
-  class C < M::B1; end
605  
-end
606  
-
607  
-M::A.subclasses # => ["N::C", "M::B2", "M::B1"]
608  
-</ruby>
609  
-
610  
-The order in which these class names are returned is unspecified.
611  
-
612  
-See also +Object#subclasses_of+ in "Extensions to All Objects FIX THIS LINK":FIXME.
613  
-
614  
-h4. Class Removal
615  
-
616  
-Roughly speaking, the +remove_class+ method removes the class objects passed as arguments:
617  
-
618  
-<ruby>
619  
-Class.remove_class(Hash, Dir) # => [Hash, Dir]
620  
-Hash # => NameError: uninitialized constant Hash
621  
-Dir  # => NameError: uninitialized constant Dir
622  
-</ruby>
623  
-
624  
-More specifically, +remove_class+ attempts to remove constants with the same name as the passed class objects from their parent modules. So technically this method does not guarantee the class objects themselves are not still valid and alive somewhere after the method call:
625  
-
626  
-<ruby>
627  
-module M
628  
-  class A; end
629  
-  class B < A; end
630  
-end
631  
-
632  
-A2 = M::A
633  
-
634  
-M::A.object_id            # => 13053950
635  
-Class.remove_class(M::A)
636  
-
637  
-M::B.superclass.object_id # => 13053950 (same object as before)
638  
-A2.name                   # => "M::A" (name is hard-coded in object)
639  
-</ruby>
640  
-
641  
-WARNING: Removing fundamental classes like +String+ can result in really funky behaviour.
642  
-
643  
-The method +remove_subclasses+ provides a shortcut for removing all descendants of a given class, where "removing" has the meaning explained above:
644  
-
645  
-<ruby>
646  
-class A; end
647  
-class B1 < A; end
648  
-class B2 < A; end
649  
-class C < A; end
650  
-
651  
-A.subclasses        # => ["C", "B2", "B1"]
652  
-A.remove_subclasses
653  
-A.subclasses        # => []
654  
-C                   # => NameError: uninitialized constant C
655  
-</ruby>
656  
-
657  
-See also +Object#remove_subclasses_of+ in "Extensions to All Objects FIX THIS LINK":FIXME.
658  
-
659  
-h3. Extensions to +Symbol+
660  
-
661  
-h4. +to_proc+
662  
-
663  
-The method +to_proc+ turns a symbol into a Proc object so that for example
664  
-
665  
-<ruby>
666  
-emails = users.map {|u| u.email}
667  
-</ruby>
668  
-
669  
-can be written as
670  
-
671  
-<ruby>
672  
-emails = users.map(&:email)
673  
-</ruby>
674  
-
675  
-TIP: If the method that receives the Proc yields more than one value to it the rest are considered to be arguments of the method call.
676  
-
677  
-Symbols from Ruby 1.8.7 on respond to +to_proc+, and Active Support defines it for previous versions.
678  
-
679  
-h3. Extensions to +String+
680  
-
681  
-h4. +bytesize+
682  
-
683  
-Ruby 1.9 introduces +String#bytesize+ to obtain the length of a string in bytes. Ruby 1.8.7 defines this method as an alias for +String#size+ for forward compatibility, and Active Support does so for previous versions.
684  
-
685  
-h4. +squish+
686  
-
687  
-The method +String#squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
688  
-
689  
-<ruby>
690  
-" \n  foo\n\r \t bar \n".squish # => "foo bar"
691  
-</ruby>
692  
-
693  
-There's also the destructive version +String#squish!+.
694  
-
695  
-h4. Key-based Interpolation
696  
-
697  
-In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:
698  
-
699  
-<ruby>
700  
-"Total is %<total>.02f" % {:total => 43.1}  # => Total is 43.10
701  
-"I say %{foo}" % {:foo => "wadus"}          # => "I say wadus"
702  
-"I say %{woo}" % {:foo => "wadus"}          # => KeyError
703  
-</ruby>
704  
-
705  
-Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.
706  
-
707  
-h4. +start_with?+ and +end_width?+
708  
-
709  
-Ruby 1.8.7 and up define the predicates +String#start_with?+ and +String#end_with?+:
710  
-
711  
-<ruby>
712  
-"foo".start_with?("f") # => true
713  
-"foo".start_with?("g") # => false
714  
-"foo".start_with?("")  # => true
715  
-
716  
-"foo".end_with?("o")   # => true
717  
-"foo".end_with?("p")   # => false
718  
-"foo".end_with?("")    # => true
719  
-</ruby>
720  
-
721  
-If strings do not respond to those methods Active Support emulates them, and also defines their 3rd person aliases:
722  
-
723  
-<ruby>
724  
-"foo".starts_with?("f") # => true
725  
-"foo".ends_with?("o")   # => true
726  
-</ruby>
727  
-
728  
-in case you feel more comfortable spelling them that way.
729  
-
730  
-WARNING. Active Support invokes +to_s+ on the argument, but Ruby does not. Since Active Support defines these methods only if strings do not respond to them, this corner of their behaviour depends on the interpreter that runs a given Rails application. You change the interpreter, and +start_with?(1)+ may change its return value. In consequence, it's more portable not to rely on that and pass always strings.
731  
-
732  
-h4. +each_char+
733  
-
734  
-Ruby 1.8.7 and up define the iterator +String#each_char+ that understands UTF8 and yields strings with a single character each, so they have length 1 but may be multibyte. Active Support defines that method for previous versions of Ruby:
735  
-
736  
-<ruby>
737  
-"\xE6\x97\xA5\xE6\x9C\xAC\xE8\xAA\x9E".each_char {|c| print c} # => 日本語
738  
-</ruby>
739  
-
740  
-h4. Access
741  
-
742  
-h5. +at(position)+
743  
-
744  
-Returns the character of the string at position +position+:
745  
-
746  
-<ruby>
747  
-"hello".at(0)  # => "h"
748  
-"hello".at(4)  # => "o"
749  
-"hello".at(-1) # => "o"
750  
-"hello".at(10) # => ERROR if < 1.9, nil in 1.9
751  
-</ruby>
752  
-
753  
-h5. +from(position)+
754  
-
755  
-Returns the substring of the string starting at position +position+:
756  
-
757  
-<ruby>
758  
-"hello".from(0)  # => "hello"
759  
-"hello".from(2)  # => "llo"
760  
-"hello".from(-2) # => "lo"
761  
-"hello".from(10) # => "" if < 1.9, nil in 1.9
762  
-</ruby>
763  
-
764  
-h5. +to(position)+
765  
-
766  
-Returns the substring of the string up to position +position+:
767  
-
768  
-<ruby>
769  
-"hello".to(0)  # => "h"
770  
-"hello".to(2)  # => "hel"
771  
-"hello".to(-2) # => "hell"
772  
-"hello".to(10) # => "hello"
773  
-</ruby>
774  
-
775  
-h5. +first(limit = 1)+
776  
-
777  
-The call +str.first(n)+ is equivalent to +str.to(n-1)+ if +n+ > 0, and returns an empty string for +n+ == 0.
778  
-
779  
-h5. +last(limit = 1)+
780  
-
781  
-The call +str.last(n)+ is equivalent to +str.from(-n)+ if +n+ > 0, and returns an empty string for +n+ == 0.
782  
-
783  
-h3. Extensions to +Numeric+
784  
-
785  
-...
786  
-
787  
-h3. Extensions to +Integer+
788  
-
789  
-h4. +multiple_of?+
790  
-
791  
-The method +multiple_of?+ tests whether an integer is multiple of the argument:
792  
-
793  
-<ruby>
794  
-2.multiple_of?(1) # => true
795  
-1.multiple_of?(2) # => false
796  
-</ruby>
797  
-
798  
-WARNING: Due the way it is implemented the argument must be nonzero, otherwise +ZeroDivisionError+ is raised.
799  
-
800  
-h4. +even?+ and +odd?+
801  
-
802  
-Integers in Ruby 1.8.7 and above respond to +even?+ and +odd?+, Active Support defines them for older versions:
803  
-
804  
-<ruby>
805  
--1.even?  # => false
806  
--1.odd?   # => true
807  
- 0.even?  # => true
808  
- 0.odd?   # => false
809  
- 2.even?  # => true
810  
- 2.odd?   # => false
811  
-</ruby>
812  
-
813  
-h4. +ordinalize+
814  
-
815  
-The method +ordinalize+ returns the ordinal string corresponding to the receiver integer:
816  
-
817  
-<ruby>
818  
-1.ordinalize    # => "1st"
819  
-2.ordinalize    # => "2nd"
820  
-53.ordinalize   # => "53rd"
821  
-2009.ordinalize # => "2009th"
822  
-</ruby>
823  
-
824  
-h3. Extensions to +Float+
825  
-
826  
-...
827  
-
828  
-h3. Extensions to +BigDecimal+
829  
-
830  
-...
831  
-
832  
-h3. Extensions to +Enumerable+
833  
-
834  
-h4. +group_by+
835  
-
836  
-Ruby 1.8.7 and up define +group_by+, and Active Support does it for previous versions.
837  
-
838  
-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:
839  
-
840  
-<ruby>
841  
-entries_by_surname_initial = address_book.group_by do |entry|
842  
-  entry.surname.at(0).upcase
843  
-end
844  
-</ruby>
845  
-
846  
-WARNING. Active Support redefines +group_by+ in Ruby 1.8.7 so that it still returns an ordered hash.
847  
-
848  
-h4. +sum+
849  
-
850  
-The method +sum+ adds the elements of an enumerable:
851  
-
852  
-<ruby>
853  
-[1, 2, 3].sum # => 6
854  
-(1..100).sum  # => 5050
855  
-</ruby>
856  
-
857  
-Addition only assumes the elements respond to <tt>+</tt>:
858  
-
859  
-<ruby>
860  
-[[1, 2], [2, 3], [3, 4]].sum    # => [1, 2, 2, 3, 3, 4]
861  
-%w(foo bar baz).sum             # => "foobarbaz"
862  
-{:a => 1, :b => 2, :c => 3}.sum # => [:b, 2, :c, 3, :a, 1]
863  
-</ruby>
864  
-
865  
-The sum of an empty collection is zero by default, but this is customizable:
866  
-
867  
-<ruby>
868  
-[].sum    # => 0
869  
-[].sum(1) # => 1
870  
-</ruby>
871  
-
872  
-If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:
873  
-
874  
-<ruby>
875  
-(1..5).sum {|n| n * 2 } # => 30
876  
-[2, 4, 6, 8, 10].sum    # => 30
877  
-</ruby>
878  
-
879  
-The sum of an empty receiver can be customized in this form as well:
880  
-
881  
-<ruby>
882  
-[].sum(1) {|n| n**3} # => 1
883  
-</ruby>
884  
-
885  
-The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:
886  
-
887  
-<ruby>
888  
-def observed_subclasses
889  
-  observed_classes.sum([]) { |klass| klass.send(:subclasses) }
890  
-end
891  
-</ruby>
892  
-
893  
-h4. +each_with_object+
894  
-
895  
-The +inject+ method offers iteration with an accumulator:
896  
-
897  
-<ruby>
898  
-[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
899  
-</ruby>
900  
-
901  
-The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:
902  
-
903  
-<ruby>
904  
-[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
905  
-</ruby>
906  
-
907  
-See that spurious "+; h+"?
908  
-
909  
-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:
910  
-
911  
-<ruby>
912  
-[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
913  
-</ruby>
914  
-
915  
-WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+.
916  
-
917  
-h4. +index_by+
918  
-
919  
-The method +index_by+ generates a hash with the elements of an enumerable indexed by some key.
920  
-
921  
-It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:
922  
-
923  
-<ruby>
924  
-invoices.index_by(&:number)
925  
-# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
926  
-</ruby>
927  
-
928  
-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.
929  
-
930  
-h4. +many?+
931  
-
932  
-The method +many?+ is shorthand for +collection.size > 1+:
933  
-
934  
-<erb>
935  
-<% if pages.many? %>
936  
-  <%= pagination_links %>
937  
-<% end %>
938  
-</erb>
939  
-
940  
-If an optional block is given +many?+ only takes into account those elements that return true:
941  
-
942  
-<ruby>
943  
-@see_more = videos.many? {|video| video.category == params[:category]}
944  
-</ruby>
945  
-
946  
-h4. +none?+
947  
-
948  
-The method +none?+ is the negation of +any?+. It yields elements to a block and returns true if none of them matches:
949  
-
950  
-<ruby>
951  
-success = responses.none? {|r| r.status / 100 == 5}
952  
-</ruby>
953  
-
954  
-Ruby 1.8.7 and later already have +none?+, Active Support defines it for previous versions.
955  
-
956  
-h3. Extensions to +Array+
957  
-
958  
-h4. Accessing
959  
-
960  
-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:
961  
-
962  
-<ruby>
963  
-%w(a b c d).to(2) # => %w(a b c)
964  
-[].to(7)          # => []
965  
-</ruby>
966  
-
967  
-Similarly, +from+ returns the tail from the element at the passed index on:
968  
-
969  
-<ruby>
970  
-%w(a b c d).from(2)  # => %w(c d)
971  
-%w(a b c d).from(10) # => nil
972  
-[].from(0)           # => nil
973  
-</ruby>
974  
-
975  
-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.
976  
-
977  
-You can pick a random element with +rand+:
978  
-
979  
-<ruby>
980  
-shape_type = [Circle, Square, Triangle].rand
981  
-</ruby>
982  
-
983  
-h4. Options Extraction
984  
-
985  
-When the last argument in a method call is a hash, except perhaps for a +&block+ argument, Ruby allows you to omit the brackets:
986  
-
987  
-<ruby>
988  
-User.exists?(:email => params[:email])
989  
-</ruby>
990  
-
991  
-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.
992  
-
993  
-If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where kind of loses its role.
994  
-
995  
-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.
996  
-
997  
-Let's see for example the definition of the +caches_action+ controller macro:
998  
-
999  
-<ruby>
1000  
-def caches_action(*actions)
1001  
-  return unless cache_configured?
1002  
-  options = actions.extract_options!
1003  
-  ...
1004  
-end
1005  
-</ruby>
1006  
-
1007  
-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.
1008  
-
1009  
-h4. Conversions
1010  
-
1011  
-h5. +to_sentence+
1012  
-
1013  
-The method +to_sentence+ turns an array into a string containing a sentence that enumerates its items:
1014  
-
1015  
-<ruby>
1016  
-%w().to_sentence                # => ""
1017  
-%w(Earth).to_sentence           # => "Earth"
1018  
-%w(Earth Wind).to_sentence      # => "Earth and Wind"
1019  
-%w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
1020  
-</ruby>
1021  
-
1022  
-This method accepts three options:
1023  
-
1024  
-* <tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".
1025  
-* <tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
1026  
-* <tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
1027  
-
1028  
-The defaults for these options can be localised, their keys are:
1029  
-
1030  
-|_. Option                      |_. I18n key                                 |
1031  
-| <tt>:two_words_connector</tt> | <tt>support.array.two_words_connector</tt> |
1032  
-| <tt>:words_connector</tt>     | <tt>support.array.words_connector</tt>     |
1033  
-| <tt>:last_word_connector</tt> | <tt>support.array.last_word_connector</tt> |
1034  
-
1035  
-Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.
1036  
-
1037  
-h5. +to_formatted_s+
1038  
-
1039  
-The method +to_formatted_s+ acts like +to_s+ by default.
1040  
-
1041  
-If the array contains items that respond to +id+, however, it may be passed the symbol <tt>:db</tt> 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:
1042  
-
1043  
-<ruby>
1044  
-[].to_formatted_s(:db)            # => "null"
1045  
-[user].to_formatted_s(:db)        # => "8456"
1046  
-invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
1047  
-</ruby>
1048  
-
1049  
-Integers in the example above are supposed to come from the respective calls to +id+.
1050  
-
1051  
-h5. +to_xml+
1052  
-
1053  
-The method +to_xml+ returns a string containing an XML representation of its receiver:
1054  
-
1055  
-<ruby>
1056  
-Contributor.all(:limit => 2, :order => 'rank ASC').to_xml
1057  
-# =>
1058  
-# <?xml version="1.0" encoding="UTF-8"?>
1059  
-# <contributors type="array">
1060