-
Notifications
You must be signed in to change notification settings - Fork 0
/
active_support_core_extensions.html
3049 lines (2686 loc) · 207 KB
/
active_support_core_extensions.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Active Support Core Extensions — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
<meta property="og:title" content="Active Support Core Extensions — Ruby on Rails Guides" />
<meta name="description" content="Active Support Core ExtensionsActive Support is the Ruby on 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 Ruby on Rails itself.After reading this guide, you will know: What Core Extensions are. How to load all extensions. How to cherry-pick just the extensions you want. What extensions Active Support provides." />
<meta property="og:description" content="Active Support Core ExtensionsActive Support is the Ruby on 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 Ruby on Rails itself.After reading this guide, you will know: What Core Extensions are. How to load all extensions. How to cherry-pick just the extensions you want. What extensions Active Support provides." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">GitHub에서 기여하기</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="6_0_release_notes.html">Version 6.0 - August 2019</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Active Support Core Extensions</h2><p>Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.</p><p>It offers a richer bottom-line at the language level, targeted both at the development of Rails applications, and at the development of Ruby on Rails itself.</p><p>After reading this guide, you will know:</p>
<ul>
<li>What Core Extensions are.</li>
<li>How to load all extensions.</li>
<li>How to cherry-pick just the extensions you want.</li>
<li>What extensions Active Support provides.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li>
<a href="#how-to-load-core-extensions">How to Load Core Extensions</a>
<ul>
<li><a href="#stand-alone-active-support">Stand-Alone Active Support</a></li>
<li><a href="#active-support-within-a-ruby-on-rails-application">Active Support Within a Ruby on Rails Application</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-all-objects">Extensions to All Objects</a>
<ul>
<li><a href="#blank-questionmark-and-present-questionmark"><code>blank?</code> and <code>present?</code></a></li>
<li><a href="#presence"><code>presence</code></a></li>
<li><a href="#duplicable-questionmark"><code>duplicable?</code></a></li>
<li><a href="#deep-dup"><code>deep_dup</code></a></li>
<li><a href="#try"><code>try</code></a></li>
<li><a href="#class-eval-args-block"><code>class_eval(*args, &block)</code></a></li>
<li><a href="#acts-like-questionmark-duck"><code>acts_like?(duck)</code></a></li>
<li><a href="#to-param"><code>to_param</code></a></li>
<li><a href="#to-query"><code>to_query</code></a></li>
<li><a href="#with-options"><code>with_options</code></a></li>
<li><a href="#json-support">JSON support</a></li>
<li><a href="#instance-variables">Instance Variables</a></li>
<li><a href="#silencing-warnings-and-exceptions">Silencing Warnings and Exceptions</a></li>
<li><a href="#in-questionmark"><code>in?</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-module">Extensions to <code>Module</code></a>
<ul>
<li><a href="#attributes">Attributes</a></li>
<li><a href="#parents">Parents</a></li>
<li><a href="#anonymous">Anonymous</a></li>
<li><a href="#method-delegation">Method Delegation</a></li>
<li><a href="#redefining-methods">Redefining Methods</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-class">Extensions to <code>Class</code></a>
<ul>
<li><a href="#class-attributes">Class Attributes</a></li>
<li><a href="#subclasses-descendants">Subclasses & Descendants</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-string">Extensions to <code>String</code></a>
<ul>
<li><a href="#output-safety">Output Safety</a></li>
<li><a href="#remove"><code>remove</code></a></li>
<li><a href="#squish"><code>squish</code></a></li>
<li><a href="#truncate"><code>truncate</code></a></li>
<li><a href="#truncate-words"><code>truncate_words</code></a></li>
<li><a href="#inquiry"><code>inquiry</code></a></li>
<li><a href="#starts-with-questionmark-and-ends-with-questionmark"><code>starts_with?</code> and <code>ends_with?</code></a></li>
<li><a href="#strip-heredoc"><code>strip_heredoc</code></a></li>
<li><a href="#indent"><code>indent</code></a></li>
<li><a href="#access">Access</a></li>
<li><a href="#inflections">Inflections</a></li>
<li><a href="#extensions-to-string-conversions">Conversions</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-numeric">Extensions to <code>Numeric</code></a>
<ul>
<li><a href="#bytes">Bytes</a></li>
<li><a href="#extensions-to-numeric-time">Time</a></li>
<li><a href="#formatting">Formatting</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-integer">Extensions to <code>Integer</code></a>
<ul>
<li><a href="#multiple-of-questionmark"><code>multiple_of?</code></a></li>
<li><a href="#ordinal"><code>ordinal</code></a></li>
<li><a href="#ordinalize"><code>ordinalize</code></a></li>
<li><a href="#extensions-to-integer-time">Time</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-bigdecimal">Extensions to <code>BigDecimal</code></a>
<ul>
<li><a href="#extensions-to-bigdecimal-to-s"><code>to_s</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-enumerable">Extensions to <code>Enumerable</code></a>
<ul>
<li><a href="#sum"><code>sum</code></a></li>
<li><a href="#index-by"><code>index_by</code></a></li>
<li><a href="#index-with"><code>index_with</code></a></li>
<li><a href="#many-questionmark"><code>many?</code></a></li>
<li><a href="#exclude-questionmark"><code>exclude?</code></a></li>
<li><a href="#without"><code>without</code></a></li>
<li><a href="#pluck"><code>pluck</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-array">Extensions to <code>Array</code></a>
<ul>
<li><a href="#accessing">Accessing</a></li>
<li><a href="#extensions-to-array-extracting">Extracting</a></li>
<li><a href="#options-extraction">Options Extraction</a></li>
<li><a href="#extensions-to-array-conversions">Conversions</a></li>
<li><a href="#wrapping">Wrapping</a></li>
<li><a href="#duplicating">Duplicating</a></li>
<li><a href="#grouping">Grouping</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-hash">Extensions to <code>Hash</code></a>
<ul>
<li><a href="#extensions-to-hash-conversions">Conversions</a></li>
<li><a href="#merging">Merging</a></li>
<li><a href="#deep-duplicating">Deep duplicating</a></li>
<li><a href="#working-with-keys">Working with Keys</a></li>
<li><a href="#slicing">Slicing</a></li>
<li><a href="#extensions-to-hash-extracting">Extracting</a></li>
<li><a href="#indifferent-access">Indifferent Access</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-regexp">Extensions to <code>Regexp</code></a>
<ul>
<li><a href="#multiline-questionmark"><code>multiline?</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-range">Extensions to <code>Range</code></a>
<ul>
<li><a href="#extensions-to-range-to-s"><code>to_s</code></a></li>
<li><a href="#include-questionmark-and-cover-questionmark"><code>===</code>, <code>include?</code>, and <code>cover?</code></a></li>
<li><a href="#overlaps-questionmark"><code>overlaps?</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-date">Extensions to <code>Date</code></a>
<ul>
<li><a href="#extensions-to-date-calculations">Calculations</a></li>
<li><a href="#extensions-to-date-conversions">Conversions</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-datetime">Extensions to <code>DateTime</code></a>
<ul>
<li><a href="#extensions-to-datetime-calculations">Calculations</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-time">Extensions to <code>Time</code></a>
<ul>
<li><a href="#calculations">Calculations</a></li>
<li><a href="#time-constructors">Time Constructors</a></li>
</ul>
</li>
<li>
<a href="#extensions-to-file">Extensions to <code>File</code></a>
<ul>
<li><a href="#atomic-write"><code>atomic_write</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-marshal">Extensions to <code>Marshal</code></a>
<ul>
<li><a href="#load"><code>load</code></a></li>
</ul>
</li>
<li><a href="#extensions-to-nameerror">Extensions to <code>NameError</code></a></li>
<li><a href="#extensions-to-loaderror">Extensions to <code>LoadError</code></a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="how-to-load-core-extensions"><a class="anchorlink" href="#how-to-load-core-extensions">1 How to Load Core Extensions</a></h3><h4 id="stand-alone-active-support"><a class="anchorlink" href="#stand-alone-active-support">1.1 Stand-Alone Active Support</a></h4><p>In order to have a near-zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.</p><p>Thus, after a simple require like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support'
</pre>
</div>
<p>objects do not even respond to <code>blank?</code>. Let's see how to load its definition.</p><h5 id="cherry-picking-a-definition"><a class="anchorlink" href="#cherry-picking-a-definition">1.1.1 Cherry-picking a Definition</a></h5><p>The most lightweight way to get <code>blank?</code> is to cherry-pick the file that defines it.</p><p>For every single method defined as a core extension this guide has a note that says where such a method is defined. In the case of <code>blank?</code> the note reads:</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/blank.rb">active_support/core_ext/object/blank.rb</a></code>.</p></div><p>That means that you can require it like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support'
require 'active_support/core_ext/object/blank'
</pre>
</div>
<p>Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.</p><h5 id="loading-grouped-core-extensions"><a class="anchorlink" href="#loading-grouped-core-extensions">1.1.2 Loading Grouped Core Extensions</a></h5><p>The next level is to simply load all extensions to <code>Object</code>. As a rule of thumb, extensions to <code>SomeClass</code> are available in one shot by loading <code>active_support/core_ext/some_class</code>.</p><p>Thus, to load all extensions to <code>Object</code> (including <code>blank?</code>):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support'
require 'active_support/core_ext/object'
</pre>
</div>
<h5 id="loading-all-core-extensions"><a class="anchorlink" href="#loading-all-core-extensions">1.1.3 Loading All Core Extensions</a></h5><p>You may prefer just to load all core extensions, there is a file for that:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support'
require 'active_support/core_ext'
</pre>
</div>
<h5 id="loading-all-active-support"><a class="anchorlink" href="#loading-all-active-support">1.1.4 Loading All Active Support</a></h5><p>And finally, if you want to have all Active Support available just issue:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support/all'
</pre>
</div>
<p>That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via <code>autoload</code>, so it is only loaded if used.</p><h4 id="active-support-within-a-ruby-on-rails-application"><a class="anchorlink" href="#active-support-within-a-ruby-on-rails-application">1.2 Active Support Within a Ruby on Rails Application</a></h4><p>A Ruby on Rails application loads all Active Support unless <code>config.active_support.bare</code> is true. In that case, the application will only load what the framework itself cherry-picks for its own needs, and can still cherry-pick itself at any granularity level, as explained in the previous section.</p><h3 id="extensions-to-all-objects"><a class="anchorlink" href="#extensions-to-all-objects">2 Extensions to All Objects</a></h3><h4 id="blank-questionmark-and-present-questionmark"><a class="anchorlink" href="#blank-questionmark-and-present-questionmark">2.1 <code>blank?</code> and <code>present?</code></a></h4><p>The following values are considered to be blank in a Rails application:</p>
<ul>
<li><p><code>nil</code> and <code>false</code>,</p></li>
<li><p>strings composed only of whitespace (see note below),</p></li>
<li><p>empty arrays and hashes, and</p></li>
<li><p>any other object that responds to <code>empty?</code> and is empty.</p></li>
</ul>
<div class="info"><p>The predicate for strings uses the Unicode-aware character class <code>[:space:]</code>, so for example U+2029 (paragraph separator) is considered to be whitespace.</p></div><div class="warning"><p>Note that numbers are not mentioned. In particular, 0 and 0.0 are <strong>not</strong> blank.</p></div><p>For example, this method from <code>ActionController::HttpAuthentication::Token::ControllerMethods</code> uses <code>blank?</code> for checking whether a token is present:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def authenticate(controller, &login_procedure)
token, options = token_and_options(controller.request)
unless token.blank?
login_procedure.call(token, options)
end
end
</pre>
</div>
<p>The method <code>present?</code> is equivalent to <code>!blank?</code>. This example is taken from <code>ActionDispatch::Http::Cache::Response</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def set_conditional_cache_control!
return if self["Cache-Control"].present?
...
end
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/blank.rb">active_support/core_ext/object/blank.rb</a></code>.</p></div><h4 id="presence"><a class="anchorlink" href="#presence">2.2 <code>presence</code></a></h4><p>The <code>presence</code> method returns its receiver if <code>present?</code>, and <code>nil</code> otherwise. It is useful for idioms like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
host = config[:host].presence || 'localhost'
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/blank.rb">active_support/core_ext/object/blank.rb</a></code>.</p></div><h4 id="duplicable-questionmark"><a class="anchorlink" href="#duplicable-questionmark">2.3 <code>duplicable?</code></a></h4><p>As of Ruby 2.5, most objects can be duplicated via <code>dup</code> or <code>clone</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"foo".dup # => "foo"
"".dup # => ""
Rational(1).dup # => (1/1)
Complex(0).dup # => (0+0i)
1.method(:+).dup # => TypeError (allocator undefined for Method)
</pre>
</div>
<p>Active Support provides <code>duplicable?</code> to query an object about this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"foo".duplicable? # => true
"".duplicable? # => true
Rational(1).duplicable? # => true
Complex(1).duplicable? # => true
1.method(:+).duplicable? # => false
</pre>
</div>
<div class="warning"><p>Any class can disallow duplication by removing <code>dup</code> and <code>clone</code> or raising exceptions from them. Thus only <code>rescue</code> can tell whether a given arbitrary object is duplicable. <code>duplicable?</code> depends on the hard-coded list above, but it is much faster than <code>rescue</code>. Use it only if you know the hard-coded list is enough in your use case.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/duplicable.rb">active_support/core_ext/object/duplicable.rb</a></code>.</p></div><h4 id="deep-dup"><a class="anchorlink" href="#deep-dup">2.4 <code>deep_dup</code></a></h4><p>The <code>deep_dup</code> method returns a deep copy of a given object. Normally, when you <code>dup</code> an object that contains other objects, Ruby does not <code>dup</code> them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
array = ['string']
duplicate = array.dup
duplicate.push 'another-string'
# the object was duplicated, so the element was added only to the duplicate
array # => ['string']
duplicate # => ['string', 'another-string']
duplicate.first.gsub!('string', 'foo')
# first element was not duplicated, it will be changed in both arrays
array # => ['foo']
duplicate # => ['foo', 'another-string']
</pre>
</div>
<p>As you can see, after duplicating the <code>Array</code> instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since <code>dup</code> does not make deep copy, the string inside the array is still the same object.</p><p>If you need a deep copy of an object, you should use <code>deep_dup</code>. Here is an example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
array = ['string']
duplicate = array.deep_dup
duplicate.first.gsub!('string', 'foo')
array # => ['string']
duplicate # => ['foo']
</pre>
</div>
<p>If the object is not duplicable, <code>deep_dup</code> will just return it:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
number = 1
duplicate = number.deep_dup
number.object_id == duplicate.object_id # => true
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/deep_dup.rb">active_support/core_ext/object/deep_dup.rb</a></code>.</p></div><h4 id="try"><a class="anchorlink" href="#try">2.5 <code>try</code></a></h4><p>When you want to call a method on an object only if it is not <code>nil</code>, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use <code>try</code>. <code>try</code> is like <code>Object#send</code> except that it returns <code>nil</code> if sent to <code>nil</code>.</p><p>Here is an example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# without try
unless @number.nil?
@number.next
end
# with try
@number.try(:next)
</pre>
</div>
<p>Another example is this code from <code>ActiveRecord::ConnectionAdapters::AbstractAdapter</code> where <code>@logger</code> could be <code>nil</code>. You can see that the code uses <code>try</code> and avoids an unnecessary check.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
<p><code>try</code> can also be called without arguments but a block, which will only be executed if the object is not nil:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@person.try { |p| "#{p.first_name} #{p.last_name}" }
</pre>
</div>
<p>Note that <code>try</code> will swallow no-method errors, returning nil instead. If you want to protect against typos, use <code>try!</code> instead:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@number.try(:nest) # => nil
@number.try!(:nest) # NoMethodError: undefined method `nest' for 1:Integer
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/try.rb">active_support/core_ext/object/try.rb</a></code>.</p></div><h4 id="class-eval-args-block"><a class="anchorlink" href="#class-eval-args-block">2.6 <code>class_eval(*args, &block)</code></a></h4><p>You can evaluate code in the context of any object's singleton class using <code>class_eval</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Proc
def bind(object)
block, time = self, Time.current
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
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/kernel/singleton_class.rb">active_support/core_ext/kernel/singleton_class.rb</a></code>.</p></div><h4 id="acts-like-questionmark-duck"><a class="anchorlink" href="#acts-like-questionmark-duck">2.7 <code>acts_like?(duck)</code></a></h4><p>The method <code>acts_like?</code> 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 <code>String</code> defines</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def acts_like_string?
end
</pre>
</div>
<p>which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
some_klass.acts_like?(:string)
</pre>
</div>
<p>Rails has classes that act like <code>Date</code> or <code>Time</code> and follow this contract.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/acts_like.rb">active_support/core_ext/object/acts_like.rb</a></code>.</p></div><h4 id="to-param"><a class="anchorlink" href="#to-param">2.8 <code>to_param</code></a></h4><p>All objects in Rails respond to the method <code>to_param</code>, which is meant to return something that represents them as values in a query string, or as URL fragments.</p><p>By default <code>to_param</code> just calls <code>to_s</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
7.to_param # => "7"
</pre>
</div>
<p>The return value of <code>to_param</code> should <strong>not</strong> be escaped:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"Tom & Jerry".to_param # => "Tom & Jerry"
</pre>
</div>
<p>Several classes in Rails overwrite this method.</p><p>For example <code>nil</code>, <code>true</code>, and <code>false</code> return themselves. <code>Array#to_param</code> calls <code>to_param</code> on the elements and joins the result with "/":</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
[0, true, String].to_param # => "0/true/String"
</pre>
</div>
<p>Notably, the Rails routing system calls <code>to_param</code> on models to get a value for the <code>:id</code> placeholder. <code>ActiveRecord::Base#to_param</code> returns the <code>id</code> of a model, but you can redefine that method in your models. For example, given</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User
def to_param
"#{id}-#{name.parameterize}"
end
end
</pre>
</div>
<p>we get:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user_path(@user) # => "/users/357-john-smith"
</pre>
</div>
<div class="warning"><p>Controllers need to be aware of any redefinition of <code>to_param</code> because when a request like that comes in "357-john-smith" is the value of <code>params[:id]</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/to_param.rb">active_support/core_ext/object/to_param.rb</a></code>.</p></div><h4 id="to-query"><a class="anchorlink" href="#to-query">2.9 <code>to_query</code></a></h4><p>Except for hashes, given an unescaped <code>key</code> this method constructs the part of a query string that would map such key to what <code>to_param</code> returns. For example, given</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User
def to_param
"#{id}-#{name.parameterize}"
end
end
</pre>
</div>
<p>we get:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
current_user.to_query('user') # => "user=357-john-smith"
</pre>
</div>
<p>This method escapes whatever is needed, both for the key and the value:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
account.to_query('company[name]')
# => "company%5Bname%5D=Johnson+%26+Johnson"
</pre>
</div>
<p>so its output is ready to be used in a query string.</p><p>Arrays return the result of applying <code>to_query</code> to each element with <code>key[]</code> as key, and join the result with "&":</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
[3.4, -45.6].to_query('sample')
# => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
</pre>
</div>
<p>Hashes also respond to <code>to_query</code> but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling <code>to_query(key)</code> on its values. Then it joins the result with "&":</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
</pre>
</div>
<p>The method <code>Hash#to_query</code> accepts an optional namespace for the keys:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{id: 89, name: "John Smith"}.to_query('user')
# => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/to_query.rb">active_support/core_ext/object/to_query.rb</a></code>.</p></div><h4 id="with-options"><a class="anchorlink" href="#with-options">2.10 <code>with_options</code></a></h4><p>The method <code>with_options</code> provides a way to factor out common options in a series of method calls.</p><p>Given a default options hash, <code>with_options</code> 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:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Account < ApplicationRecord
has_many :customers, dependent: :destroy
has_many :products, dependent: :destroy
has_many :invoices, dependent: :destroy
has_many :expenses, dependent: :destroy
end
</pre>
</div>
<p>this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Account < ApplicationRecord
with_options dependent: :destroy do |assoc|
assoc.has_many :customers
assoc.has_many :products
assoc.has_many :invoices
assoc.has_many :expenses
end
end
</pre>
</div>
<p>That idiom may convey <em>grouping</em> 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:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
subject i18n.t :subject
body i18n.t :body, user_name: user.name
end
</pre>
</div>
<div class="info"><p>Since <code>with_options</code> forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/with_options.rb">active_support/core_ext/object/with_options.rb</a></code>.</p></div><h4 id="json-support"><a class="anchorlink" href="#json-support">2.11 JSON support</a></h4><p>Active Support provides a better implementation of <code>to_json</code> than the <code>json</code> gem ordinarily provides for Ruby objects. This is because some classes, like <code>Hash</code>, <code>OrderedHash</code> and <code>Process::Status</code> need special handling in order to provide a proper JSON representation.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/json.rb">active_support/core_ext/object/json.rb</a></code>.</p></div><h4 id="instance-variables"><a class="anchorlink" href="#instance-variables">2.12 Instance Variables</a></h4><p>Active Support provides several methods to ease access to instance variables.</p><h5 id="instance-values"><a class="anchorlink" href="#instance-values">2.12.1 <code>instance_values</code></a></h5><p>The method <code>instance_values</code> returns a hash that maps instance variable names without "@" to their
corresponding values. Keys are strings:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/instance_variables.rb">active_support/core_ext/object/instance_variables.rb</a></code>.</p></div><h5 id="instance-variable-names"><a class="anchorlink" href="#instance-variable-names">2.12.2 <code>instance_variable_names</code></a></h5><p>The method <code>instance_variable_names</code> returns an array. Each name includes the "@" sign.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class C
def initialize(x, y)
@x, @y = x, y
end
end
C.new(0, 1).instance_variable_names # => ["@x", "@y"]
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/instance_variables.rb">active_support/core_ext/object/instance_variables.rb</a></code>.</p></div><h4 id="silencing-warnings-and-exceptions"><a class="anchorlink" href="#silencing-warnings-and-exceptions">2.13 Silencing Warnings and Exceptions</a></h4><p>The methods <code>silence_warnings</code> and <code>enable_warnings</code> change the value of <code>$VERBOSE</code> accordingly for the duration of their block, and reset it afterwards:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
</pre>
</div>
<p>Silencing exceptions is also possible with <code>suppress</code>. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is <code>kind_of?</code> any of the arguments, <code>suppress</code> captures it and returns silently. Otherwise the exception is not captured:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# If the user is locked, the increment is lost, no big deal.
suppress(ActiveRecord::StaleObjectError) do
current_user.increment! :visits
end
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/kernel/reporting.rb">active_support/core_ext/kernel/reporting.rb</a></code>.</p></div><h4 id="in-questionmark"><a class="anchorlink" href="#in-questionmark">2.14 <code>in?</code></a></h4><p>The predicate <code>in?</code> tests if an object is included in another object. An <code>ArgumentError</code> exception will be raised if the argument passed does not respond to <code>include?</code>.</p><p>Examples of <code>in?</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
1.in?([1,2]) # => true
"lo".in?("hello") # => true
25.in?(30..50) # => false
1.in?(1) # => ArgumentError
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/object/inclusion.rb">active_support/core_ext/object/inclusion.rb</a></code>.</p></div><h3 id="extensions-to-module"><a class="anchorlink" href="#extensions-to-module">3 Extensions to <code>Module</code></a></h3><h4 id="attributes"><a class="anchorlink" href="#attributes">3.1 Attributes</a></h4><h5 id="alias-attribute"><a class="anchorlink" href="#alias-attribute">3.1.1 <code>alias_attribute</code></a></h5><p>Model attributes have a reader, a writer, and a predicate. You can alias 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 (one mnemonic is that they go in the same order as if you did an assignment):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
# You can refer to the email column as "login".
# This can be meaningful for authentication code.
alias_attribute :login, :email
end
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/aliasing.rb">active_support/core_ext/module/aliasing.rb</a></code>.</p></div><h5 id="internal-attributes"><a class="anchorlink" href="#internal-attributes">3.1.2 Internal Attributes</a></h5><p>When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.</p><p>Active Support defines the macros <code>attr_internal_reader</code>, <code>attr_internal_writer</code>, and <code>attr_internal_accessor</code>. They behave like their Ruby built-in <code>attr_*</code> counterparts, except they name the underlying instance variable in a way that makes collisions less likely.</p><p>The macro <code>attr_internal</code> is a synonym for <code>attr_internal_accessor</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# library
class ThirdPartyLibrary::Crawler
attr_internal :log_level
end
# client code
class MyCrawler < ThirdPartyLibrary::Crawler
attr_accessor :log_level
end
</pre>
</div>
<p>In the previous example it could be the case that <code>:log_level</code> does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own <code>:log_level</code>. Thanks to <code>attr_internal</code> there's no collision.</p><p>By default the internal instance variable is named with a leading underscore, <code>@_log_level</code> in the example above. That's configurable via <code>Module.attr_internal_naming_format</code> though, you can pass any <code>sprintf</code>-like format string with a leading <code>@</code> and a <code>%s</code> somewhere, which is where the name will be placed. The default is <code>"@_%s"</code>.</p><p>Rails uses internal attributes in a few spots, for examples for views:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module ActionView
class Base
attr_internal :captures
attr_internal :request, :layout
attr_internal :controller, :template
end
end
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/attr_internal.rb">active_support/core_ext/module/attr_internal.rb</a></code>.</p></div><h5 id="module-attributes"><a class="anchorlink" href="#module-attributes">3.1.3 Module Attributes</a></h5><p>The macros <code>mattr_reader</code>, <code>mattr_writer</code>, and <code>mattr_accessor</code> are the same as the <code>cattr_*</code> macros defined for class. In fact, the <code>cattr_*</code> macros are just aliases for the <code>mattr_*</code> macros. Check <a href="#class-attributes">Class Attributes</a>.</p><p>For example, the dependencies mechanism uses them:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module ActiveSupport
module Dependencies
mattr_accessor :warnings_on_first_load
mattr_accessor :history
mattr_accessor :loaded
mattr_accessor :mechanism
mattr_accessor :load_paths
mattr_accessor :load_once_paths
mattr_accessor :autoloaded_constants
mattr_accessor :explicitly_unloadable_constants
mattr_accessor :constant_watch_stack
mattr_accessor :constant_watch_stack_mutex
end
end
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb">active_support/core_ext/module/attribute_accessors.rb</a></code>.</p></div><h4 id="parents"><a class="anchorlink" href="#parents">3.2 Parents</a></h4><h5 id="module-parent"><a class="anchorlink" href="#module-parent">3.2.1 <code>module_parent</code></a></h5><p>The <code>module_parent</code> method on a nested named module returns the module that contains its corresponding constant:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module X
module Y
module Z
end
end
end
M = X::Y::Z
X::Y::Z.module_parent # => X::Y
M.module_parent # => X::Y
</pre>
</div>
<p>If the module is anonymous or belongs to the top-level, <code>module_parent</code> returns <code>Object</code>.</p><div class="warning"><p>Note that in that case <code>module_parent_name</code> returns <code>nil</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h5 id="module-parent-name"><a class="anchorlink" href="#module-parent-name">3.2.2 <code>module_parent_name</code></a></h5><p>The <code>module_parent_name</code> method on a nested named module returns the fully qualified name of the module that contains its corresponding constant:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module X
module Y
module Z
end
end
end
M = X::Y::Z
X::Y::Z.module_parent_name # => "X::Y"
M.module_parent_name # => "X::Y"
</pre>
</div>
<p>For top-level or anonymous modules <code>module_parent_name</code> returns <code>nil</code>.</p><div class="warning"><p>Note that in that case <code>module_parent</code> returns <code>Object</code>.</p></div><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h5 id="module-parents"><a class="anchorlink" href="#module-parents">3.2.3 <code>module_parents</code></a></h5><p>The method <code>module_parents</code> calls <code>module_parent</code> on the receiver and upwards until <code>Object</code> is reached. The chain is returned in an array, from bottom to top:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module X
module Y
module Z
end
end
end
M = X::Y::Z
X::Y::Z.module_parents # => [X::Y, X, Object]
M.module_parents # => [X::Y, X, Object]
</pre>
</div>
<div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/introspection.rb">active_support/core_ext/module/introspection.rb</a></code>.</p></div><h4 id="anonymous"><a class="anchorlink" href="#anonymous">3.3 Anonymous</a></h4><p>A module may or may not have a name:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
M.name # => "M"
N = Module.new
N.name # => "N"
Module.new.name # => nil
</pre>
</div>
<p>You can check whether a module has a name with the predicate <code>anonymous?</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
M.anonymous? # => false
Module.new.anonymous? # => true
</pre>
</div>
<p>Note that being unreachable does not imply being anonymous:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
m = Object.send(:remove_const, :M)
m.anonymous? # => false
</pre>
</div>
<p>though an anonymous module is unreachable by definition.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/anonymous.rb">active_support/core_ext/module/anonymous.rb</a></code>.</p></div><h4 id="method-delegation"><a class="anchorlink" href="#method-delegation">3.4 Method Delegation</a></h4><h5 id="delegate"><a class="anchorlink" href="#delegate">3.4.1 <code>delegate</code></a></h5><p>The macro <code>delegate</code> offers an easy way to forward methods.</p><p>Let's imagine that users in some application have login information in the <code>User</code> model but name and other data in a separate <code>Profile</code> model:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_one :profile
end
</pre>
</div>
<p>With that configuration you get a user's name via their profile, <code>user.profile.name</code>, but it could be handy to still be able to access such attribute directly:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_one :profile
def name
profile.name
end
end
</pre>
</div>
<p>That is what <code>delegate</code> does for you:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_one :profile
delegate :name, to: :profile
end
</pre>
</div>
<p>It is shorter, and the intention more obvious.</p><p>The method must be public in the target.</p><p>The <code>delegate</code> macro accepts several methods:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
delegate :name, :age, :address, :twitter, to: :profile
</pre>
</div>
<p>When interpolated into a string, the <code>:to</code> option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# delegates to the Rails constant
delegate :logger, to: :Rails
# delegates to the receiver's class
delegate :table_name, to: :class
</pre>
</div>
<div class="warning"><p>If the <code>:prefix</code> option is <code>true</code> this is less generic, see below.</p></div><p>By default, if the delegation raises <code>NoMethodError</code> and the target is <code>nil</code> the exception is propagated. You can ask that <code>nil</code> is returned instead with the <code>:allow_nil</code> option:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
delegate :name, to: :profile, allow_nil: true
</pre>
</div>
<p>With <code>:allow_nil</code> the call <code>user.name</code> returns <code>nil</code> if the user has no profile.</p><p>The option <code>:prefix</code> adds a prefix to the name of the generated method. This may be handy for example to get a better name:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
delegate :street, to: :address, prefix: true
</pre>
</div>
<p>The previous example generates <code>address_street</code> rather than <code>street</code>.</p><div class="warning"><p>Since in this case the name of the generated method is composed of the target object and target method names, the <code>:to</code> option must be a method name.</p></div><p>A custom prefix may also be configured:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
delegate :size, to: :attachment, prefix: :avatar
</pre>
</div>
<p>In the previous example the macro generates <code>avatar_size</code> rather than <code>size</code>.</p><p>The option <code>:private</code> changes methods scope:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
delegate :date_of_birth, to: :profile, private: true
</pre>
</div>
<p>The delegated methods are public by default. Pass <code>private: true</code> to change that.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/delegation.rb">active_support/core_ext/module/delegation.rb</a></code>.</p></div><h5 id="delegate-missing-to"><a class="anchorlink" href="#delegate-missing-to">3.4.2 <code>delegate_missing_to</code></a></h5><p>Imagine you would like to delegate everything missing from the <code>User</code> object,
to the <code>Profile</code> one. The <code>delegate_missing_to</code> macro lets you implement this
in a breeze:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ApplicationRecord
has_one :profile
delegate_missing_to :profile
end
</pre>
</div>
<p>The target can be anything callable within the object, e.g. instance variables,
methods, constants, etc. Only the public methods of the target are delegated.</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/delegation.rb">active_support/core_ext/module/delegation.rb</a></code>.</p></div><h4 id="redefining-methods"><a class="anchorlink" href="#redefining-methods">3.5 Redefining Methods</a></h4><p>There are cases where you need to define a method with <code>define_method</code>, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.</p><p>The method <code>redefine_method</code> prevents such a potential warning, removing the existing method before if needed.</p><p>You can also use <code>silence_redefinition_of_method</code> if you need to define
the replacement method yourself (because you're using <code>delegate</code>, for
example).</p><div class="note"><p>Defined in <code><a href="https://github.com/rails/rails/tree/6-0-stable/activesupport/lib/active_support/core_ext/module/redefine_method.rb">active_support/core_ext/module/redefine_method.rb</a></code>.</p></div><h3 id="extensions-to-class"><a class="anchorlink" href="#extensions-to-class">4 Extensions to <code>Class</code></a></h3><h4 id="class-attributes"><a class="anchorlink" href="#class-attributes">4.1 Class Attributes</a></h4><h5 id="class-attribute"><a class="anchorlink" href="#class-attribute">4.1.1 <code>class_attribute</code></a></h5><p>The method <code>class_attribute</code> declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class A
class_attribute :x
end
class B < A; end
class C < B; end
A.x = :a
B.x # => :a
C.x # => :a