-
Notifications
You must be signed in to change notification settings - Fork 0
/
active_support_core_extensions.html
3483 lines (3078 loc) · 189 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="zh-TW">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Active Support Core Extensions — Ruby on Rails 指南</title>
<meta name="description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)" >
<meta name="keywords" content="Ruby on Rails Guides 指南 中文 學習 免費 網路 Web 開發" >
<meta name="author" content="http://git.io/G_R1sA">
<meta property="fb:admins" content="1340181291">
<meta property="og:title" content="Active Support Core Extensions — Ruby on Rails 指南" >
<meta property="og:site_name" content="Ruby on Rails 指南">
<meta property="og:image" content="http://rails.ruby.tw/images/rails_guides_cover.jpg">
<meta property="og:url" content="http://rails.ruby.tw/">
<meta property="og:type" content="article">
<meta property="og:description" content="Ruby on Rails 指南:系統學習 Rails(Rails 4.2 版本)">
<link rel="stylesheet" href="stylesheets/application.css">
<link href="http://fonts.googleapis.com/css?family=Noto+Sans:400,700|Noto+Serif:700|Source+Code+Pro" rel="stylesheet">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
</head>
<body class="guide">
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/zh-TW/sdk.js#xfbml=1&appId=837401439623727&version=v2.0";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<script type="text/javascript">
window.twttr=(function(d,s,id){var t,js,fjs=d.getElementsByTagName(s)[0];if(d.getElementById(id)){return}js=d.createElement(s);js.id=id;js.src="https://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);return window.twttr||(t={_e:[],ready:function(f){t._e.push(f)}})}(document,"script","twitter-wjs"));
</script>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">更多內容 <a href="http://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="http://rubyonrails.org/">綜覽</a></li>
<li class="more-info"><a href="http://rubyonrails.org/download">下載</a></li>
<li class="more-info"><a href="http://rubyonrails.org/deploy">部署</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">原始碼</a></li>
<li class="more-info"><a href="http://rubyonrails.org/screencasts">影片</a></li>
<li class="more-info"><a href="http://rubyonrails.org/documentation">文件</a></li>
<li class="more-info"><a href="http://rubyonrails.org/community">社群</a></li>
<li class="more-info"><a href="http://weblog.rubyonrails.org/">Blog</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="回首頁">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>
<dl class="L">
<dt>起步走</dt>
<dd><a href="getting_started.html">Rails 起步走</a></dd>
<dt>Models</dt>
<dd><a href="active_record_basics.html">Active Record 基礎</a></dd>
<dd><a href="active_record_migrations.html">Active Record 遷移</a></dd>
<dd><a href="active_record_validations.html">Active Record 驗證</a></dd>
<dd><a href="active_record_callbacks.html">Active Record 回呼</a></dd>
<dd><a href="association_basics.html">Active Record 關聯</a></dd>
<dd><a href="active_record_querying.html">Active Record 查詢</a></dd>
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Rails 算繪與版型</a></dd>
<dd><a href="form_helpers.html">Action View 表單輔助方法</a></dd>
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller 綜覽</a></dd>
<dd><a href="routing.html">Rails 路由:深入淺出</a></dd>
</dl>
<dl class="R">
<dt>深入了解</dt>
<dd><a href="active_support_core_extensions.html">Active Support 核心擴展</a></dd>
<dd><a href="i18n.html">Rails 國際化 API</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer 基礎</a></dd>
<dd><a href="active_job_basics.html">Active Job 基礎</a></dd>
<dd><a href="security.html">Rails 安全指南</a></dd>
<dd><a href="debugging_rails_applications.html">除錯 Rails 應用程式</a></dd>
<dd><a href="configuring.html">Rails 應用程式設定</a></dd>
<dd><a href="command_line.html">Rake 任務與 Rails 命令列工具</a></dd>
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</a></dd>
<dd><a href="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</a></dd>
<dt>擴充 Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">客製與新建 Rails 產生器</a></dd>
<dd><a href="rails_application_templates.html">Rails 應用程式模版</a></dd>
<dt>貢獻 Ruby on Rails</dt>
<dd><a href="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API 文件準則</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</a></dd>
<dt>維護方針</dt>
<dd><a href="maintenance_policy.html">維護方針</a></dd>
<dt>發佈記</dt>
<dd><a href="upgrading_ruby_on_rails.html">升級 Ruby on Rails</a></dd>
<dd><a href="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</a></dd>
<dd><a href="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</a></dd>
<dd><a href="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</a></dd>
<dd><a href="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</a></dd>
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</a></dd>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</a></dd>
<dt>Rails 指南翻譯術語</dt>
<dd><a href="translation_terms.html">翻譯術語</a></dd>
</dl>
</div>
</li>
<li><a class="nav-item" href="//github.com/docrails-tw/guides">貢獻翻譯</a></li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">貢獻</a></li>
<li><a class="nav-item" href="credits.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">Rails 起步走</option>
</optgroup>
<optgroup label="Models">
<option value="active_record_basics.html">Active Record 基礎</option>
<option value="active_record_migrations.html">Active Record 遷移</option>
<option value="active_record_validations.html">Active Record 驗證</option>
<option value="active_record_callbacks.html">Active Record 回呼</option>
<option value="association_basics.html">Active Record 關聯</option>
<option value="active_record_querying.html">Active Record 查詢</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Rails 算繪與版型</option>
<option value="form_helpers.html">Action View 表單輔助方法</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller 綜覽</option>
<option value="routing.html">Rails 路由:深入淺出</option>
</optgroup>
<optgroup label="深入了解">
<option value="active_support_core_extensions.html">Active Support 核心擴展</option>
<option value="i18n.html">Rails 國際化 API</option>
<option value="action_mailer_basics.html">Action Mailer 基礎</option>
<option value="active_job_basics.html">Active Job 基礎</option>
<option value="security.html">Rails 安全指南</option>
<option value="debugging_rails_applications.html">除錯 Rails 應用程式</option>
<option value="configuring.html">Rails 應用程式設定</option>
<option value="command_line.html">Rake 任務與 Rails 命令列工具</option>
<option value="asset_pipeline.html">Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">在 Rails 使用 JavaScript</option>
<option value="constant_autoloading_and_reloading.html">Constant Autoloading and Reloading</option>
</optgroup>
<optgroup label="擴充 Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">客製與新建 Rails 產生器</option>
<option value="rails_application_templates.html">Rails 應用程式模版</option>
</optgroup>
<optgroup label="貢獻 Ruby on Rails">
<option value="contributing_to_ruby_on_rails.html">貢獻 Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API 文件準則</option>
<option value="ruby_on_rails_guides_guidelines.html">Ruby on Rails 指南準則</option>
</optgroup>
<optgroup label="維護方針">
<option value="maintenance_policy.html">維護方針</option>
</optgroup>
<optgroup label="發佈記">
<option value="upgrading_ruby_on_rails.html">升級 Ruby on Rails</option>
<option value="4_2_release_notes.html">Ruby on Rails 4.2 發佈記</option>
<option value="4_1_release_notes.html">Ruby on Rails 4.1 發佈記</option>
<option value="4_0_release_notes.html">Ruby on Rails 4.0 發佈記</option>
<option value="3_2_release_notes.html">Ruby on Rails 3.2 發佈記</option>
<option value="3_1_release_notes.html">Ruby on Rails 3.1 發佈記</option>
<option value="3_0_release_notes.html">Ruby on Rails 3.0 發佈記</option>
<option value="2_3_release_notes.html">Ruby on Rails 2.3 發佈記</option>
<option value="2_2_release_notes.html">Ruby on Rails 2.2 發佈記</option>
</optgroup>
<optgroup label="Rails 指南翻譯術語">
<option value="translation_terms.html">翻譯術語</option>
</optgroup>
</select>
</li>
</ul>
</div>
</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-streams-and-exceptions">Silencing Warnings, Streams, 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="#alias-method-chain"><code>alias_method_chain</code></a></li>
<li><a href="#attributes">Attributes</a></li>
<li><a href="#extensions-to-module-parents">Parents</a></li>
<li><a href="#constants">Constants</a></li>
<li><a href="#reachable">Reachable</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="#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="#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>
</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>
<li><a href="#extensions-to-bigdecimal-to-formatted-s"><code>to_formatted_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="#many-questionmark"><code>many?</code></a></li>
<li><a href="#exclude-questionmark"><code>exclude?</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="#adding-elements">Adding Elements</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="#extracting">Extracting</a></li>
<li><a href="#indifferent-access">Indifferent Access</a></li>
<li><a href="#compacting">Compacting</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"><code>include?</code></a></li>
<li><a href="#overlaps-questionmark"><code>overlaps?</code></a></li>
</ul>
</li>
<li>
<a href="#extensions-to-proc">Extensions to <code>Proc</code></a>
<ul>
<li><a href="#bind"><code>bind</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-logger">Extensions to <code>Logger</code></a>
<ul>
<li><a href="#around-level"><code>around_[level]</code></a></li>
<li><a href="#silence"><code>silence</code></a></li>
<li><a href="#datetime-format"><code>datetime_format=</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">1 How to Load Core Extensions</h3><h4 id="stand-alone-active-support">1.1 Stand-Alone Active Support</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">1.1.1 Cherry-picking a Definition</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>active_support/core_ext/object/blank.rb</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">1.1.2 Loading Grouped Core Extensions</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">1.1.3 Loading All Core Extensions</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">1.1.4 Loading All Active Support</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">1.2 Active Support Within a Ruby on Rails Application</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">2 Extensions to All Objects</h3><h4 id="blank-questionmark-and-present-questionmark">2.1 <code>blank?</code> and <code>present?</code>
</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>active_support/core_ext/object/blank.rb</code>.</p></div><h4 id="presence">2.2 <code>presence</code>
</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>active_support/core_ext/object/blank.rb</code>.</p></div><h4 id="duplicable-questionmark">2.3 <code>duplicable?</code>
</h4><p>A few fundamental objects in Ruby are singletons. For example, in the whole life of a program the integer 1 refers always to the same instance:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
1.object_id # => 3
Math.cos(0).to_i.object_id # => 3
</pre>
</div>
<p>Hence, there's no way these objects can be duplicated through <code>dup</code> or <code>clone</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
true.dup # => TypeError: can't dup TrueClass
</pre>
</div>
<p>Some numbers which are not singletons are not duplicable either:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
0.0.clone # => allocator undefined for Float
(2**1024).clone # => allocator undefined for Bignum
</pre>
</div>
<p>Active Support provides <code>duplicable?</code> to programmatically query an object about this property:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"foo".duplicable? # => true
"".duplicable? # => true
0.0.duplicable? # => false
false.duplicable? # => false
</pre>
</div>
<p>By definition all objects are <code>duplicable?</code> except <code>nil</code>, <code>false</code>, <code>true</code>, symbols, numbers, class, and module objects.</p><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>active_support/core_ext/object/duplicable.rb</code>.</p></div><h4 id="deep-dup">2.4 <code>deep_dup</code>
</h4><p>The <code>deep_dup</code> method returns 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>active_support/core_ext/object/deep_dup.rb</code>.</p></div><h4 id="try">2.5 <code>try</code>
</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>
<div class="note"><p>Defined in <code>active_support/core_ext/object/try.rb</code>.</p></div><h4 id="class-eval-args-block">2.6 <code>class_eval(*args, &block)</code>
</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>active_support/core_ext/kernel/singleton_class.rb</code>.</p></div><h4 id="acts-like-questionmark-duck">2.7 <code>acts_like?(duck)</code>
</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>active_support/core_ext/object/acts_like.rb</code>.</p></div><h4 id="to-param">2.8 <code>to_param</code>
</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>active_support/core_ext/object/to_param.rb</code>.</p></div><h4 id="to-query">2.9 <code>to_query</code>
</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>active_support/core_ext/object/to_query.rb</code>.</p></div><h4 id="with-options">2.10 <code>with_options</code>
</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 < ActiveRecord::Base
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 < 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
</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>active_support/core_ext/object/with_options.rb</code>.</p></div><h4 id="json-support">2.11 JSON support</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>active_support/core_ext/object/json.rb</code>.</p></div><h4 id="instance-variables">2.12 Instance Variables</h4><p>Active Support provides several methods to ease access to instance variables.</p><h5 id="instance-values">2.12.1 <code>instance_values</code>
</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>active_support/core_ext/object/instance_variables.rb</code>.</p></div><h5 id="instance-variable-names">2.12.2 <code>instance_variable_names</code>
</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>active_support/core_ext/object/instance_variables.rb</code>.</p></div><h4 id="silencing-warnings-streams-and-exceptions">2.13 Silencing Warnings, Streams, and Exceptions</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>You can silence any stream while a block runs with <code>silence_stream</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
silence_stream(STDOUT) do
# STDOUT is silent here
end
</pre>
</div>
<p>The <code>quietly</code> method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
quietly { system 'bundle install' }
</pre>
</div>
<p>For example, the railties test suite uses that one in a few places to prevent command messages from being echoed intermixed with the progress status.</p><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 reraised:</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>active_support/core_ext/kernel/reporting.rb</code>.</p></div><h4 id="in-questionmark">2.14 <code>in?</code>
</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>active_support/core_ext/object/inclusion.rb</code>.</p></div><h3 id="extensions-to-module">3 Extensions to <code>Module</code>
</h3><h4 id="alias-method-chain">3.1 <code>alias_method_chain</code>
</h4><p>Using plain Ruby you can wrap methods with other methods, that's called <em>alias chaining</em>.</p><p>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 <code>ActionController::TestCase#process</code> this way in <code>test/test_helper.rb</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
<p>That's the method <code>get</code>, <code>post</code>, etc., delegate the work to.</p><p>That technique has a risk, it could be the case that <code>:original_process</code> was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
<p>The method <code>alias_method_chain</code> provides a shortcut for that pattern:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
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
</pre>
</div>
<p>Rails uses <code>alias_method_chain</code> all over the code base. For example validations are added to <code>ActiveRecord::Base#save</code> by wrapping the method that way in a separate module specialized in validations.</p><div class="note"><p>Defined in <code>active_support/core_ext/module/aliasing.rb</code>.</p></div><h4 id="attributes">3.2 Attributes</h4><h5 id="alias-attribute">3.2.1 <code>alias_attribute</code>
</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 < ActiveRecord::Base
# 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>active_support/core_ext/module/aliasing.rb</code>.</p></div><h5 id="internal-attributes">3.2.2 Internal Attributes</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>active_support/core_ext/module/attr_internal.rb</code>.</p></div><h5 id="module-attributes">3.2.3 Module Attributes</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 :logger
mattr_accessor :log_activity
mattr_accessor :constant_watch_stack
mattr_accessor :constant_watch_stack_mutex
end
end
</pre>
</div>
<div class="note"><p>Defined in <code>active_support/core_ext/module/attribute_accessors.rb</code>.</p></div><h4 id="extensions-to-module-parents">3.3 Parents</h4><h5 id="parent">3.3.1 <code>parent</code>
</h5><p>The <code>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.parent # => X::Y
M.parent # => X::Y
</pre>
</div>
<p>If the module is anonymous or belongs to the top-level, <code>parent</code> returns <code>Object</code>.</p><div class="warning"><p>Note that in that case <code>parent_name</code> returns <code>nil</code>.</p></div><div class="note"><p>Defined in <code>active_support/core_ext/module/introspection.rb</code>.</p></div><h5 id="parent-name">3.3.2 <code>parent_name</code>
</h5><p>The <code>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.parent_name # => "X::Y"
M.parent_name # => "X::Y"
</pre>
</div>
<p>For top-level or anonymous modules <code>parent_name</code> returns <code>nil</code>.</p><div class="warning"><p>Note that in that case <code>parent</code> returns <code>Object</code>.</p></div><div class="note"><p>Defined in <code>active_support/core_ext/module/introspection.rb</code>.</p></div><h5 id="extensions-to-module-parents-parents">3.3.3 <code>parents</code>
</h5><p>The method <code>parents</code> calls <code>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.parents # => [X::Y, X, Object]
M.parents # => [X::Y, X, Object]
</pre>
</div>
<div class="note"><p>Defined in <code>active_support/core_ext/module/introspection.rb</code>.</p></div><h4 id="constants">3.4 Constants</h4><p>The method <code>local_constants</code> returns the names of the constants that have been
defined in the receiver module:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module X
X1 = 1
X2 = 2
module Y
Y1 = :y1
X1 = :overrides_X1_above
end
end
X.local_constants # => [:X1, :X2, :Y]
X::Y.local_constants # => [:Y1, :X1]
</pre>
</div>
<p>The names are returned as symbols.</p><div class="note"><p>Defined in <code>active_support/core_ext/module/introspection.rb</code>.</p></div><h5 id="qualified-constant-names">3.4.1 Qualified Constant Names</h5><p>The standard methods <code>const_defined?</code>, <code>const_get</code> , and <code>const_set</code> accept
bare constant names. Active Support extends this API to be able to pass
relative qualified constant names.</p><p>The new methods are <code>qualified_const_defined?</code>, <code>qualified_const_get</code>, and
<code>qualified_const_set</code>. Their arguments are assumed to be qualified constant
names relative to their receiver:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Object.qualified_const_defined?("Math::PI") # => true
Object.qualified_const_get("Math::PI") # => 3.141592653589793
Object.qualified_const_set("Math::Phi", 1.618034) # => 1.618034
</pre>
</div>
<p>Arguments may be bare constant names:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Math.qualified_const_get("E") # => 2.718281828459045
</pre>
</div>
<p>These methods are analogous to their built-in counterparts. In particular,
<code>qualified_constant_defined?</code> accepts an optional second argument to be
able to say whether you want the predicate to look in the ancestors.
This flag is taken into account for each constant in the expression while
walking down the path.</p><p>For example, given</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
X = 1
end
module N
class C
include M
end
end
</pre>
</div>
<p><code>qualified_const_defined?</code> behaves this way:</p><div class="code_container">