aboutsummaryrefslogtreecommitdiffstats
path: root/railties/guides/source/active_support_core_extensions.textile
blob: 0e4f1da7b20b840eb9a63a82bd9bdbd98e221489 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
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. 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:

<ruby>
def charset
  charset = String(headers["Content-Type"] || headers["type"]).split(";")[1]
  charset.blank? ? nil : charset.strip.split("=")[1]
end
</ruby>

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:

<ruby>
def instantiate_observers
  return if @observers.blank?
  # ...
end
</ruby>

The method +present?+ is equivalent to +!blank?+:

<ruby>
assert @response.body.present? # same as !@response.body.blank?
</ruby>

h4. +presence+

The +presence+ method returns its receiver if +present?+, and +nil+ otherwise. It is useful for idioms like this:

<ruby>
host = config[:host].presence || 'localhost'
</ruby>

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:

<ruby>
1.object_id                 # => 3
Math.cos(0).to_i.object_id  # => 3
</ruby>

Hence, there's no way these objects can be duplicated through +dup+ or +clone+:

<ruby>
true.dup  # => TypeError: can't dup TrueClass
</ruby>

Some numbers which are not singletons are not duplicable either:

<ruby>
0.0.clone        # => allocator undefined for Float
(2**1024).clone  # => allocator undefined for Bignum
</ruby>

Active Support provides +duplicable?+ to programmatically query an object about this property:

<ruby>
"".duplicable?     # => true
false.duplicable?  # => false
</ruby>

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.

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:

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

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

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

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:

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

h4. +metaclass+

The method +metaclass+ returns the singleton class on any object:

<ruby>
String.metaclass     # => #<Class:String>
String.new.metaclass # => #<Class:#<String:0x17a1d1c>>
</ruby>

h4. +class_eval(*args, &block)+

You can evaluate code in the context of any object's singleton class using +class_eval+:

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

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

<ruby>
def acts_like_string?
end
</ruby>

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

<ruby>
some_klass.acts_like?(:string)
</ruby>

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

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

<ruby>
7.to_param # => "7"
</ruby>

The return value of +to_param+ should *not* be escaped:

<ruby>
"Tom & Jerry".to_param # => "Tom & Jerry"
</ruby>

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

<ruby>
[0, true, String].to_param # => "0/true/String"
</ruby>

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

<ruby>
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
</ruby>

we get:

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

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

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

<ruby>
class User
  def to_param
    "#{id}-#{name.parameterize}"
  end
end
</ruby>

we get:

<ruby>
current_user.to_query('user') # => user=357-john-smith
</ruby>

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

<ruby>
account.to_query('company[name]')
# => "company%5Bname%5D=Johnson+%26+Johnson"
</ruby>

so its output is ready to be used in a query string.

Arrays return the result of applying +to_query+ to each element with <tt>_key_[]</tt> as key, and join the result with "&":

<ruby>
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
</ruby>

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

<ruby>
{:c => 3, :b => 2, :a => 1}.to_query # => "a=1&b=2&c=3"
</ruby>

The method +Hash#to_query+ accepts an optional namespace for the keys:

<ruby>
{:id => 89, :name => "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
</ruby>

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:

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

this way:

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

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:

<ruby>
I18n.with_options :locale => user.locale, :scope => "newsletter" do |i18n|
  subject i18n.t :subject
  body    i18n.t :body, :user_name => user.name 
end
</ruby>

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.

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:

<ruby>
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

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

WARNING: The order in which the names are returned is unespecified, and it indeed depends on the version of the interpreter.

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:

<ruby>
class C
  def initialize(x, y)
    @x, @y = x, y
  end
end

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

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.

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

In the example +object+ and +self+ are of the same type, but they don't need to.

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:

<ruby>
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
</ruby>

You can silence any stream while a block runs with +silence_stream+:

<ruby>
silence_stream(STDOUT) do
  # STDOUT is silent here
end
</ruby>

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:

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

h3. Extensions to +Module+

h4. Aliasing

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

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

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:

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

The method +alias_method_chain+ provides a shortcut for that pattern:

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

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.

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

<ruby>
class User < ActiveRecord::Base
  # let me refer to the email column as "login",
  # much meaningful for authentication code
  alias_attribute :login, :email
end
</ruby>

h4. Delegation

The class method +delegate+

h3. Extensions to +Class+

h4. Class Attribute Accessors

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:

<ruby>
class MysqlAdapter < AbstractAdapter
  # Generates class methods to access @@emulate_booleans.
  cattr_accessor :emulate_booleans
  self.emulate_booleans = true
end
</ruby>

Instance methods are created as well for convenience. For example given

<ruby>
module ActionController
  class Base
    cattr_accessor :logger
  end
end
</ruby>

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+):

<ruby>
module ActiveRecord
  class Base
    # No pluralize_table_names= instance writer is generated.
    cattr_accessor :pluralize_table_names, :instance_writer => false
  end
end
</ruby>

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:

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

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:

<ruby>
class_inheritable_array
class_inheritable_hash
</ruby>

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+):

<ruby>
module ActiveRecord
  class Base
    class_inheritable_accessor :default_scoping, :instance_writer => false
  end
end
</ruby>

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. 

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:

<ruby>
module ActionMailer
  class Base
    superclass_delegating_accessor :delivery_method
    self.delivery_method = :smtp
  end
end
</ruby>

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.

h4. Subclasses

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:

<ruby>
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"]
</ruby>

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.

h4. Class Removal

Roughly speaking, the +remove_class+ method removes the class objects passed as arguments:

<ruby>
Class.remove_class(Hash, Dir) # => [Hash, Dir]
Hash # => NameError: uninitialized constant Hash
Dir  # => NameError: uninitialized constant Dir
</ruby>

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:

<ruby>
module M
  class A; end
  class B < A; end
end

A2 = M::A

M::A.object_id            # => 13053950
Class.remove_class(M::A)

M::B.superclass.object_id # => 13053950 (same object as before)
A2.name                   # => "M::A" (name is hard-coded in object)
</ruby>

WARNING: Removing fundamental classes like +String+ can result in really funky behaviour.

The method +remove_subclasses+ provides a shortcut for removing all descendants of a given class, where "removing" has the meaning explained above:

<ruby>
class A; end
class B1 < A; end
class B2 < A; end
class C < A; end

A.subclasses        # => ["C", "B2", "B1"]
A.remove_subclasses
A.subclasses        # => []
C                   # => NameError: uninitialized constant C
</ruby>

See also +Object#remove_subclasses_of+ in "Extensions to All Objects FIX THIS LINK":FIXME.

h3. Extensions to +String+

h4. +squish+

The method +String#squish+ strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:

<ruby>
" \n  foo\n\r \t bar \n".squish # => "foo bar"
</ruby>

There's also the destructive version +String#squish!+.

h4. Key-based Interpolation

In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:

<ruby>
"Total is %<total>.02f" % {:total => 43.1}  # => Total is 43.10
"I say %{foo}" % {:foo => "wadus"}          # => "I say wadus"
"I say %{woo}" % {:foo => "wadus"}          # => KeyError
</ruby>

Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.

h4. +starts_with?+ and +ends_width?+

Active Support defines 3rd person aliases of +String#start_with?+ and +String#end_with?+:

<ruby>
"foo".starts_with?("f") # => true
"foo".ends_with?("o")   # => true
</ruby>

h4. Access

h5. +at(position)+

Returns the character of the string at position +position+:

<ruby>
"hello".at(0)  # => "h"
"hello".at(4)  # => "o"
"hello".at(-1) # => "o"
"hello".at(10) # => ERROR if < 1.9, nil in 1.9
</ruby>

h5. +from(position)+

Returns the substring of the string starting at position +position+:

<ruby>
"hello".from(0)  # => "hello"
"hello".from(2)  # => "llo"
"hello".from(-2) # => "lo"
"hello".from(10) # => "" if < 1.9, nil in 1.9
</ruby>

h5. +to(position)+

Returns the substring of the string up to position +position+:

<ruby>
"hello".to(0)  # => "h"
"hello".to(2)  # => "hel"
"hello".to(-2) # => "hell"
"hello".to(10) # => "hello"
</ruby>

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.

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.

h3. Extensions to +Numeric+

h4. Bytes

All numbers respond to these methods:

<ruby>
bytes
kilobytes
megabytes
gigabytes
terabytes
petabytes
exabytes
</ruby>

They return the corresponding amount of bytes, using a conversion factor of 1024:

<ruby>
2.kilobytes   # => 2048
3.megabytes   # => 3145728
3.5.gigabytes # => 3758096384
-4.exabytes   # => -4611686018427387904
</ruby>

Singular forms are aliased so you are able to say:

<ruby>
1.megabyte # => 1048576
</ruby>

h3. Extensions to +Integer+

h4. +multiple_of?+

The method +multiple_of?+ tests whether an integer is multiple of the argument:

<ruby>
2.multiple_of?(1) # => true
1.multiple_of?(2) # => false
</ruby>

WARNING: Due the way it is implemented the argument must be nonzero, otherwise +ZeroDivisionError+ is raised.

h4. +ordinalize+

The method +ordinalize+ returns the ordinal string corresponding to the receiver integer:

<ruby>
1.ordinalize    # => "1st"
2.ordinalize    # => "2nd"
53.ordinalize   # => "53rd"
2009.ordinalize # => "2009th"
</ruby>

h3. Extensions to +Float+

...

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:

<ruby>
entries_by_surname_initial = address_book.group_by do |entry|
  entry.surname.at(0).upcase
end
</ruby>

WARNING. Active Support redefines +group_by+ in Ruby 1.8.7 so that it still returns an ordered hash.

h4. +sum+

The method +sum+ adds the elements of an enumerable:

<ruby>
[1, 2, 3].sum # => 6
(1..100).sum  # => 5050
</ruby>

Addition only assumes the elements respond to <tt>+</tt>:

<ruby>
[[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]
</ruby>

The sum of an empty collection is zero by default, but this is customizable:

<ruby>
[].sum    # => 0
[].sum(1) # => 1
</ruby>

If a block is given +sum+ becomes an iterator that yields the elements of the collection and sums the returned values:

<ruby>
(1..5).sum {|n| n * 2 } # => 30
[2, 4, 6, 8, 10].sum    # => 30
</ruby>

The sum of an empty receiver can be customized in this form as well:

<ruby>
[].sum(1) {|n| n**3} # => 1
</ruby>

The method +ActiveRecord::Observer#observed_subclasses+ for example is implemented this way:

<ruby>
def observed_subclasses
  observed_classes.sum([]) { |klass| klass.send(:subclasses) }
end
</ruby>

h4. +each_with_object+

The +inject+ method offers iteration with an accumulator:

<ruby>
[2, 3, 4].inject(1) {|acc, i| product*i } # => 24
</ruby>

The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:

<ruby>
[1, 2].inject({}) {|h, i| h[i] = i**2; h} # => {1 => 1, 2 => 4}
</ruby>

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:

<ruby>
[1, 2].each_with_object({}) {|i, h| h[i] = i**2} # => {1 => 1, 2 => 4}
</ruby>

WARNING. Note that the item of the collection and the accumulator come in different order in +inject+ and +each_with_object+.

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:

<ruby>
invoices.index_by(&:number)
# => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
</ruby>

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.

h4. +many?+

The method +many?+ is shorthand for +collection.size > 1+:

<erb>
<% if pages.many? %>
  <%= pagination_links %>
<% end %>
</erb>

If an optional block is given +many?+ only takes into account those elements that return true:

<ruby>
@see_more = videos.many? {|video| video.category == params[:category]}
</ruby>

h4. +exclude?+

The predicate +exclude?+ tests whether a given object does *not* belong to the collection. It is the negation of the builtin +include?+:

<ruby>
to_visit << node if visited.exclude?(node)
</ruby>

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:

<ruby>
%w(a b c d).to(2) # => %w(a b c)
[].to(7)          # => []
</ruby>

Similarly, +from+ returns the tail from the element at the passed index on:

<ruby>
%w(a b c d).from(2)  # => %w(c d)
%w(a b c d).from(10) # => nil
[].from(0)           # => []
</ruby>

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

<ruby>
shape_type = [Circle, Square, Triangle].rand
</ruby>

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:

<ruby>
User.exists?(:email => params[:email])
</ruby>

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

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:

<ruby>
def caches_action(*actions)
  return unless cache_configured?
  options = actions.extract_options!
  ...
end
</ruby>

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.

h4. Conversions

h5. +to_sentence+

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

<ruby>
%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"
</ruby>

This method accepts three options:

* <tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is " and ".
* <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 ", ".
* <tt>:last_word_connector</tt>: 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                                 |
| <tt>:two_words_connector</tt> | <tt>support.array.two_words_connector</tt> |
| <tt>:words_connector</tt>     | <tt>support.array.words_connector</tt>     |
| <tt>:last_word_connector</tt> | <tt>support.array.last_word_connector</tt> |

Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.

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

<ruby>
[].to_formatted_s(:db)            # => "null"
[user].to_formatted_s(:db)        # => "8456"
invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
</ruby>

Integers in the example above are supposed to come from the respective calls to +id+.

h5. +to_xml+

The method +to_xml+ returns a string containing an XML representation of its receiver:

<ruby>
Contributor.all(:limit => 2, :order => 'rank ASC').to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors type="array">
#   <contributor>
#     <id type="integer">4356</id>
#     <name>Jeremy Kemper</name>
#     <rank type="integer">1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id type="integer">4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank type="integer">2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
</ruby>

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 <tt>is_a?</tt>) 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":

<ruby>
[Contributor.first, Commit.first].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <records type="array">
#   <record>
#     <id type="integer">4583</id>
#     <name>Aaron Batalion</name>
#     <rank type="integer">53</rank>
#     <url-id>aaron-batalion</url-id>
#   </record>
#   <record>
#     <author>Joshua Peek</author>
#     <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
#     <branch>origin/master</branch>
#     <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
#     <committer>Joshua Peek</committer>
#     <git-show nil="true"></git-show>
#     <id type="integer">190316</id>
#     <imported-from-svn type="boolean">false</imported-from-svn>
#     <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
#     <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
#   </record>
# </records>
</ruby>

If the receiver is an array of hashes the root element is by default also "records":

<ruby>
[{:a => 1, :b => 2}, {:c => 3}].to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <records type="array">
#   <record>
#     <b type="integer">2</b>
#     <a type="integer">1</a>
#   </record>
#   <record>
#     <c type="integer">3</c>
#   </record>
# </records>
</ruby>

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 <tt>:root</tt> 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 <tt>:children</tt> allows you to set these node names.

The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder via the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder:

<ruby>
Contributor.all(:limit => 2, :order => 'rank ASC').to_xml(:skip_types => true)
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <contributors>
#   <contributor>
#     <id>4356</id>
#     <name>Jeremy Kemper</name>
#     <rank>1</rank>
#     <url-id>jeremy-kemper</url-id>
#   </contributor>
#   <contributor>
#     <id>4404</id>
#     <name>David Heinemeier Hansson</name>
#     <rank>2</rank>
#     <url-id>david-heinemeier-hansson</url-id>
#   </contributor>
# </contributors>
</ruby>

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:

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

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:

<ruby>
[1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
</ruby>

or yields them in turn if a block is passed:

<ruby>
<% sample.in_groups_of(3) do |a, b, c| %>
  <tr>
    <td><%=h a %></td>
    <td><%=h b %></td>
    <td><%=h c %></td>
  </tr>
<% end %>
</ruby>

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:

<ruby>
[1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
</ruby>

And you can tell the method not to fill the last group passing +false+:

<ruby>
[1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
</ruby>

As a consequence +false+ can't be a used as a padding value.

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:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3)
# => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
</ruby>

or yields them in turn if a block is passed:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
["1", "2", "3"]
["4", "5", nil]
["6", "7", nil]
</ruby>

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:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3, "0")
# => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
</ruby>

And you can tell the method not to fill the smaller groups passing +false+:

<ruby>
%w(1 2 3 4 5 6 7).in_groups(3, false)
# => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
</ruby>

As a consequence +false+ can't be a used as a padding value.

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:

<ruby>
(-5..5).to_a.split { |i| i.multiple_of?(4) }
# => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
</ruby>

Otherwise, the value received as argument, which defaults to +nil+, is the separator:

<ruby>
[0, 1, -5, 1, 1, "foo", "bar"].split(1)
# => [[0], [-5], [], ["foo", "bar"]]
</ruby>

NOTE: Observe in the previous example that consecutive separators result in empty arrays.

h3. Extensions to +Hash+

h4. Conversions

h5. +to_xml+

The method +to_xml+ returns a string containing an XML representation of its receiver:

<ruby>
{"foo" => 1, "bar" => 2}.to_xml
# =>
# <?xml version="1.0" encoding="UTF-8"?>
# <hash>
#   <foo type="integer">1</foo>
#   <bar type="integer">2</bar>
# </hash>
</ruby>

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 <tt>:root</tt>.

* If +value+ is an array there's a recursive call with +key+ as <tt>:root</tt>, and +key+ singularized as <tt>:children</tt>.

* 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 <tt>:root</tt>, 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 <tt>:root</tt>.

* 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 <tt>:skip_types</tt> exists and is true, an attribute "type" is added as well according to the following mapping:
<ruby>
XML_TYPE_NAMES = {
  "Symbol"     => "symbol",
  "Fixnum"     => "integer",
  "Bignum"     => "integer",
  "BigDecimal" => "decimal",
  "Float"      => "float",
  "TrueClass"  => "boolean",
  "FalseClass" => "boolean",
  "Date"       => "date",
  "DateTime"   => "datetime",
  "Time"       => "datetime"
}
</ruby>

By default the root node is "hash", but that's configurable via the <tt>:root</tt> option.

The default XML builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.

h4. Merging

Ruby has a builtin method +Hash#merge+ that merges two hashes:

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

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:

<ruby>
options = {:length => 30, :omission => "..."}.merge(options)
</ruby>

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

<ruby>
options = options.reverse_merge(:length => 30, :omission => "...")
</ruby>

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

<ruby>
options.reverse_merge!(:length => 30, :omission => "...")
</ruby>

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

h5. +reverse_update+

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

WARNING. Note that +reverse_update+ has no bang.

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:

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

The method +deep_merge!+ performs a deep merge in place.

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.

<ruby>
{: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}
</ruby>

An important property of this diff hash is that you can retrieve the original hash by applying +diff+ twice:

<ruby>
hash.diff(hash2).diff(hash2) == hash
</ruby>

Diffing hashes may be useful for error messages related to expected option hashes for example.

h4. Working with Keys

h5. +except+ and +except!+

The method +except+ returns a hash with the keys in the argument list removed, if present:

<ruby>
{:a => 1, :b => 2}.except(:a) # => {:b => 2}
</ruby>

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:

<ruby>
{:a => 1}.with_indifferent_access.except(:a)  # => {}
{:a => 1}.with_indifferent_access.except("a") # => {}
</ruby>

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

<ruby>
params[:account] = params[:account].except(:plan_id) unless admin?
@account.update_attributes(params[:account])
</ruby>

There's also the bang variant +except!+ that removes keys in the very receiver.

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:

<ruby>
{nil => nil, 1 => 1, :a => :a}.stringify_keys
# => {"" => nil, "a" => :a, "1" => 1}
</ruby>

The result in case of collision is undefined:

<ruby>
{"a" => 1, :a => 2}.stringify_keys
# => {"a" => 2}, in my test, can't rely on this result though
</ruby>

This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionView::Helpers::FormHelper+ defines:

<ruby>
def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
  options = options.stringify_keys
  options["type"] = "checkbox"
  ...
end
</ruby>

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.

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:

<ruby>
{nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
# => {1 => 1, nil => nil, :a => "a"}
</ruby>

WARNING. Note in the previous example only one key was symbolized.

The result in case of collision is undefined:

<ruby>
{"a" => 1, :a => 2}.symbolize_keys
# => {:a => 2}, in my test, can't rely on this result though
</ruby>

This method may be useful for example to easily accept both symbols and strings as options. For instance +ActionController::UrlRewriter+ defines

<ruby>
def rewrite_path(options)
  options = options.symbolize_keys
  options.update(options[:params].symbolize_keys) if options[:params]
  ...
end
</ruby>

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.

h5. +to_options+ and +to_options!+

The methods +to_options+ and +to_options!+ are respectively aliases of +symbolize_keys+ and +symbolize_keys!+.

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.

<ruby>
{:a => 1}.assert_valid_keys(:a)  # passes
{:a => 1}.assert_valid_keys("a") # ArgumentError
</ruby>

Active Record does not accept unknown options when building associations for example. It implements that control via +assert_valid_keys+:

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

h4. Slicing

Ruby has builtin support for taking slices out of strings and arrays. Active Support extends slicing to hashes:

<ruby>
{: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
</ruby>

If the receiver responds to +convert_key+ keys are normalized:

<ruby>
{:a => 1, :b => 2}.with_indifferent_access.slice("a")
# => {:a => 1}
</ruby>

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:

<ruby>
hash = {:a => 1, :b => 2}
rest = hash.slice!(:a) # => {:b => 2}
hash                   # => {:a => 1}
</ruby>

h4. Indifferent Access

The method +with_indifferent_access+ returns an +ActiveSupport::HashWithIndifferentAccess+ out of its receiver:

<ruby>
{:a => 1}.with_indifferent_access["a"] # => 1
</ruby>

h3. Extensions to +Regexp+

h4. +number_of_captures+

The method +number_of_captures+ returns the number of capturing groups in a given regexp:

<ruby>
%r{}.number_of_captures                   # => 0
%r{.(.).}.number_of_captures              # => 1
%r{\A((#)(\w+|\s+))\z}.number_of_captures # => 3
</ruby>

Routing code for example uses that method to generate path recognizers:

<ruby>
def recognition_extraction
  next_capture = 1
  extraction = segments.collect do |segment|
    x = segment.match_extraction(next_capture)
    next_capture += segment.number_of_captures
    x
  end
  extraction.compact
end
</ruby>

h4. +multiline?+

The method +multiline?+ says whether a regexp has the +/m+ flag set, that is, whether the dot matches newlines.

<ruby>
%r{.}.multiline?  # => false
%r{.}m.multiline? # => true

Regexp.new('.').multiline?                    # => false
Regexp.new('.', Regexp::MULTILINE).multiline? # => true
</ruby>

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.

<ruby>
def assign_route_options(segments, defaults, requirements)
  ...
  if requirement.multiline?
    raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
  end
  ...
end
</ruby>

h4. +optionalize(pattern)+

The class method +optionalize+ builds a regexp where the pattern argument is optional. That roughly means it gets a question mark appended with a non-capturing group if needed:

<ruby>
Regexp.optionalize('')    # => ''
Regexp.optionalize('.')   # => '.?'
Regexp.optionalize('...') # => '(?:...)?'
</ruby>

This method is also used by the routing system, it helps in building optional regexp segments.

h4. +unoptionalize(pattern)+

The class method +unoptionalize+ is the inverse of +optionalize+ for optional regexps, and the identity for the rest:

<ruby>
Regexp.unoptionalize('')         # => ''
Regexp.unoptionalize('.?')       # => '.'
Regexp.unoptionalize('(?:...)?') # => '...'
Regexp.unoptionalize('\A\w+\z')  # => '\A\w+\z'
</ruby>

This method is also used in the routes code for building regexps.

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

<ruby>
(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'"
</ruby>

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.

h4. +step+

Active Support extends the method +Range#step+ so that it can be invoked without a block:

<ruby>
(1..10).step(2) # => [1, 3, 5, 7, 9]
</ruby>

As the example shows, in that case the method returns and array with the corresponding elements.

h4. +include?+

The method +Range#include?+ says whether some value falls between the ends of a given instance:

<ruby>
(2..3).include?(Math::E) # => true
</ruby>

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:

<ruby>
(1..10).include?(3..7)  # => true
(1..10).include?(0..7)  # => false
(1..10).include?(3..11) # => false
(1...9).include?(3..9)  # => false
</ruby>

WARNING: The orginal +Range#include?+ is still the one aliased to +Range#===+.

h4. +overlaps?+

The method +Range#overlaps?+ says whether any two given ranges have non-void intersection:

<ruby>
(1..10).overlaps?(7..11)  # => true
(1..10).overlaps?(0..7)   # => true
(1..10).overlaps?(11..27) # => false
</ruby>

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:

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

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

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

Active Support defines +Proc#bind+ with an analogous purpose:

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

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:

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

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

<ruby>
File.atomic_write(joined_asset_path) do |cache|
  cache.write(join_asset_file_contents(asset_paths))
end
</ruby>

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

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:

<ruby>
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
</ruby>
 
h3. Extensions to +LoadError+

Rails hijacks +LoadError.new+ to return a +MissingSourceFile+ exception:

<shell>
$ ruby -e 'require "nonexistent"'
...: no such file to load -- nonexistent (LoadError)
...
$ script/runner 'require "nonexistent"'
...: no such file to load -- nonexistent (MissingSourceFile)
...
</shell>

The class +MissingSourceFile+ is a subclass of +LoadError+, so any code that rescues +LoadError+ as usual still works as expected. Point is these exception objects respond to +is_missing?+, which given a path name 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, but it 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:

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

h3. Changelog

"Lighthouse ticket":https://rails.lighthouseapp.com/projects/16213/tickets/67

* April 18, 2009: Initial version by "Xavier Noria":credits.html#fxn