This repository was archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathactive_support_core_extensions.html
More file actions
3968 lines (3628 loc) · 173 KB
/
active_support_core_extensions.html
File metadata and controls
3968 lines (3628 loc) · 173 KB
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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Active Support Core Extensions</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></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>By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.</p>
<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-and-present"><tt>blank?</tt> and <tt>present?</tt></a></li> <li><a href="#presence"><tt>presence</tt></a></li> <li><a href="#duplicable"><tt>duplicable?</tt></a></li> <li><a href="#try"><tt>try</tt></a></li> <li><a href="#singleton_class"><tt>singleton_class</tt></a></li> <li><a href="#class_eval-args-block"><tt>class_eval(*args, &block)</tt></a></li> <li><a href="#acts_like-duck"><tt>acts_like?(duck)</tt></a></li> <li><a href="#to_param"><tt>to_param</tt></a></li> <li><a href="#to_query"><tt>to_query</tt></a></li> <li><a href="#with_options"><tt>with_options</tt></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="#require_library_or_gem"><tt>require_library_or_gem</tt></a></li></ul></li><li><a href="#extensions-to-module">Extensions to <tt>Module</tt></a><ul><li><a href="#alias_method_chain"><tt>alias_method_chain</tt></a></li> <li><a href="#attributes">Attributes</a></li> <li><a href="#parents">Parents</a></li> <li><a href="#constants">Constants</a></li> <li><a href="#synchronization">Synchronization</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="#method-names">Method Names</a></li> <li><a href="#redefining-methods">Redefining Methods</a></li></ul></li><li><a href="#extensions-to-class">Extensions to <tt>Class</tt></a><ul><li><a href="#class-attributes">Class Attributes</a></li> <li><a href="#class-inheritable-attributes">Class Inheritable Attributes</a></li> <li><a href="#subclasses-descendants">Subclasses & Descendants</a></li></ul></li><li><a href="#extensions-to-string">Extensions to <tt>String</tt></a><ul><li><a href="#output-safety">Output Safety</a></li> <li><a href="#squish"><tt>squish</tt></a></li> <li><a href="#truncate"><tt>truncate</tt></a></li> <li><a href="#key-based-interpolation">Key-based Interpolation</a></li> <li><a href="#starts_with-and-ends_with"><tt>starts_with?</tt> and <tt>ends_with?</tt></a></li> <li><a href="#strip_heredoc"><tt>strip_heredoc</tt></a></li> <li><a href="#access">Access</a></li> <li><a href="#inflections">Inflections</a></li> <li><a href="#string-conversions">Conversions</a></li></ul></li><li><a href="#extensions-to-numeric">Extensions to <tt>Numeric</tt></a><ul><li><a href="#bytes">Bytes</a></li></ul></li><li><a href="#extensions-to-integer">Extensions to <tt>Integer</tt></a><ul><li><a href="#multiple_of"><tt>multiple_of?</tt></a></li> <li><a href="#ordinalize"><tt>ordinalize</tt></a></li></ul></li><li><a href="#extensions-to-float">Extensions to <tt>Float</tt></a><ul><li><a href="#round"><tt>round</tt></a></li></ul></li><li><a href="#extensions-to-bigdecimal">Extensions to <tt>BigDecimal</tt></a></li><li><a href="#extensions-to-enumerable">Extensions to <tt>Enumerable</tt></a><ul><li><a href="#group_by"><tt>group_by</tt></a></li> <li><a href="#sum"><tt>sum</tt></a></li> <li><a href="#each_with_object"><tt>each_with_object</tt></a></li> <li><a href="#index_by"><tt>index_by</tt></a></li> <li><a href="#many"><tt>many?</tt></a></li> <li><a href="#exclude"><tt>exclude?</tt></a></li></ul></li><li><a href="#extensions-to-array">Extensions to <tt>Array</tt></a><ul><li><a href="#accessing">Accessing</a></li> <li><a href="#random-access">Random Access</a></li> <li><a href="#options-extraction">Options Extraction</a></li> <li><a href="#array-conversions">Conversions</a></li> <li><a href="#wrapping">Wrapping</a></li> <li><a href="#grouping">Grouping</a></li></ul></li><li><a href="#extensions-to-hash">Extensions to <tt>Hash</tt></a><ul><li><a href="#hash-conversions">Conversions</a></li> <li><a href="#merging">Merging</a></li> <li><a href="#diffing">Diffing</a></li> <li><a href="#working-with-keys">Working with Keys</a></li> <li><a href="#slicing">Slicing</a></li> <li><a href="#indifferent-access">Indifferent Access</a></li></ul></li><li><a href="#extensions-to-regexp">Extensions to <tt>Regexp</tt></a><ul><li><a href="#multiline"><tt>multiline?</tt></a></li></ul></li><li><a href="#extensions-to-range">Extensions to <tt>Range</tt></a><ul><li><a href="#to_s"><tt>to_s</tt></a></li> <li><a href="#step"><tt>step</tt></a></li> <li><a href="#include"><tt>include?</tt></a></li> <li><a href="#overlaps"><tt>overlaps?</tt></a></li></ul></li><li><a href="#extensions-to-proc">Extensions to <tt>Proc</tt></a><ul><li><a href="#bind"><tt>bind</tt></a></li></ul></li><li><a href="#extensions-to-date">Extensions to <tt>Date</tt></a><ul><li><a href="#calculations">Calculations</a></li> <li><a href="#date-conversions">Conversions</a></li></ul></li><li><a href="#extensions-to-datetime">Extensions to <tt>DateTime</tt></a><ul><li><a href="#calculations-datetime">Calculations</a></li></ul></li><li><a href="#extensions-to-time">Extensions to <tt>Time</tt></a><ul><li><a href="#time-calculations">Calculations</a></li> <li><a href="#time-constructors">Time Constructors</a></li></ul></li><li><a href="#extensions-to-process">Extensions to <tt>Process</tt></a><ul><li><a href="#daemon"><tt>daemon</tt></a></li></ul></li><li><a href="#extensions-to-file">Extensions to <tt>File</tt></a><ul><li><a href="#atomic_write"><tt>atomic_write</tt></a></li></ul></li><li><a href="#extensions-to-logger">Extensions to <tt>Logger</tt></a><ul><li><a href="#around_-level"><tt>around_[level]</tt></a></li> <li><a href="#silence"><tt>silence</tt></a></li> <li><a href="#datetime_format"><tt>datetime_format=</tt></a></li></ul></li><li><a href="#extensions-to-nameerror">Extensions to <tt>NameError</tt></a></li><li><a href="#extensions-to-loaderror">Extensions to <tt>LoadError</tt></a></li><li><a href="#changelog">Changelog</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 may 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>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support'
</pre>
</div>
</notextile>
<p>objects do not even respond to <tt>blank?</tt>, 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 <tt>blank?</tt> 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 <tt>blank?</tt> the note reads:</p>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
<p>That means that this single call is enough:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support/core_ext/object/blank'
</pre>
</div>
</notextile>
<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 <tt>Object</tt>. As a rule of thumb, extensions to <tt>SomeClass</tt> are available in one shot by loading <tt>active_support/core_ext/some_class</tt>.</p>
<p>Thus, if that would do, to have <tt>blank?</tt> available we could just load all extensions to <tt>Object</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support/core_ext/object'
</pre>
</div>
</notextile>
<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>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support/core_ext'
</pre>
</div>
</notextile>
<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>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require 'active_support/all'
</pre>
</div>
</notextile>
<p>That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via <tt>autoload</tt>, 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 <tt>config.active_support.bare</tt> 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-and-present">2.1 <tt>blank?</tt> and <tt>present?</tt></h4>
<p>The following values are considered to be blank in a Rails application:</p>
<ul>
<li><tt>nil</tt> and <tt>false</tt>,</li>
</ul>
<ul>
<li>strings composed only of whitespace, i.e. matching <tt>/\A\s*\z/</tt>,</li>
</ul>
<ul>
<li>empty arrays and hashes, and</li>
</ul>
<ul>
<li>any other object that responds to <tt>empty?</tt> and it is empty.</li>
</ul>
<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 <tt>ActionDispatch::Session::AbstractStore</tt> uses <tt>blank?</tt> for checking whether a session key is present:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def ensure_session_key!
if @key.blank?
raise ArgumentError, 'A key is required...'
end
end
</pre>
</div>
</notextile>
<p>The method <tt>present?</tt> is equivalent to <tt>!blank?</tt>. This example is taken from <tt>ActionDispatch::Http::Cache::Response</tt>:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
<h4 id="presence">2.2 <tt>presence</tt></h4>
<p>The <tt>presence</tt> method returns its receiver if <tt>present?</tt>, and <tt>nil</tt> otherwise. It is useful for idioms like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
host = config[:host].presence || 'localhost'
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
<h4 id="duplicable">2.3 <tt>duplicable?</tt></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>
<notextile>
<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>
</notextile>
<p>Hence, there’s no way these objects can be duplicated through <tt>dup</tt> or <tt>clone</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
true.dup # => TypeError: can't dup TrueClass
</pre>
</div>
</notextile>
<p>Some numbers which are not singletons are not duplicable either:</p>
<notextile>
<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>
</notextile>
<p>Active Support provides <tt>duplicable?</tt> to programmatically query an object about this property:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"".duplicable? # => true
false.duplicable? # => false
</pre>
</div>
</notextile>
<p>By definition all objects are <tt>duplicable?</tt> except <tt>nil</tt>, <tt>false</tt>, <tt>true</tt>, symbols, numbers, and class and module objects.</p>
<div class='warning'><p>Any class can disallow duplication removing <tt>dup</tt> and <tt>clone</tt> or raising exceptions from them, only <tt>rescue</tt> can tell whether a given arbitrary object is duplicable. <tt>duplicable?</tt> depends on the hard-coded list above, but it is much faster than <tt>rescue</tt>. Use it only if you know the hard-coded list is enough in your use case.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/duplicable.rb</tt>.</p></div>
<h4 id="try">2.4 <tt>try</tt></h4>
<p>Sometimes you want to call a method provided the receiver object is not <tt>nil</tt>, which is something you usually check first. <tt>try</tt> is like <tt>Object#send</tt> except that it returns <tt>nil</tt> if sent to <tt>nil</tt>.</p>
<p>For instance, in this code from <tt>ActiveRecord::ConnectionAdapters::AbstractAdapter</tt> <tt>@logger</tt> could be <tt>nil</tt>, but you save the check and write in an optimistic style:</p>
<notextile>
<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>
</notextile>
<p><tt>try</tt> can also be called without arguments but a block, which will only be executed if the object is not nil:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@person.try { |p| "#{p.first_name} #{p.last_name}" }
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/try.rb</tt>.</p></div>
<h4 id="singleton_class">2.5 <tt>singleton_class</tt></h4>
<p>The method <tt>singleton_class</tt> returns the singleton class of the receiver:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
String.singleton_class # => #<Class:String>
String.new.singleton_class # => #<Class:#<String:0x17a1d1c>>
</pre>
</div>
</notextile>
<div class='warning'><p>Fixnums and symbols have no singleton classes, <tt>singleton_class</tt> raises <tt>TypeError</tt> on them. Moreover, the singleton classes of <tt>nil</tt>, <tt>true</tt>, and <tt>false</tt>, are <tt>NilClass</tt>, <tt>TrueClass</tt>, and <tt>FalseClass</tt>, respectively.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
<h4 id="class_eval-args-block">2.6 <tt>class_eval(*args, &block)</tt></h4>
<p>You can evaluate code in the context of any object’s singleton class using <tt>class_eval</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Proc
def bind(object)
block, time = self, Time.now
object.class_eval do
method_name = "__bind_#{time.to_i}_#{time.usec}"
define_method(method_name, &block)
method = instance_method(method_name)
remove_method(method_name)
method
end.bind(object)
end
end
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
<h4 id="acts_like-duck">2.7 <tt>acts_like?(duck)</tt></h4>
<p>The method <tt>acts_like</tt> 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 <tt>String</tt> defines</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def acts_like_string?
end
</pre>
</div>
</notextile>
<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>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
some_klass.acts_like?(:string)
</pre>
</div>
</notextile>
<p>Rails has classes that act like <tt>Date</tt> or <tt>Time</tt> and follow this contract.</p>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/acts_like.rb</tt>.</p></div>
<h4 id="to_param">2.8 <tt>to_param</tt></h4>
<p>All objects in Rails respond to the method <tt>to_param</tt>, which is meant to return something that represents them as values in a query string, or as <span class="caps">URL</span> fragments.</p>
<p>By default <tt>to_param</tt> just calls <tt>to_s</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
7.to_param # => "7"
</pre>
</div>
</notextile>
<p>The return value of <tt>to_param</tt> should <strong>not</strong> be escaped:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
"Tom & Jerry".to_param # => "Tom & Jerry"
</pre>
</div>
</notextile>
<p>Several classes in Rails overwrite this method.</p>
<p>For example <tt>nil</tt>, <tt>true</tt>, and <tt>false</tt> return themselves. <tt>Array#to_param</tt> calls <tt>to_param</tt> on the elements and joins the result with “/”:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
[0, true, String].to_param # => "0/true/String"
</pre>
</div>
</notextile>
<p>Notably, the Rails routing system calls <tt>to_param</tt> on models to get a value for the <tt>:id</tt> placeholder. <tt>ActiveRecord::Base#to_param</tt> returns the <tt>id</tt> of a model, but you can redefine that method in your models. For example, given</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User
def to_param
"#{id}-#{name.parameterize}"
end
end
</pre>
</div>
</notextile>
<p>we get:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user_path(@user) # => "/users/357-john-smith"
</pre>
</div>
</notextile>
<div class='warning'><p>Controllers need to be aware of any redefinition of <tt>to_param</tt> because when a request like that comes in “357-john-smith” is the value of <tt>params[:id]</tt>.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/to_param.rb</tt>.</p></div>
<h4 id="to_query">2.9 <tt>to_query</tt></h4>
<p>Except for hashes, given an unescaped <tt>key</tt> this method constructs the part of a query string that would map such key to what <tt>to_param</tt> returns. For example, given</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User
def to_param
"#{id}-#{name.parameterize}"
end
end
</pre>
</div>
</notextile>
<p>we get:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
current_user.to_query('user') # => user=357-john-smith
</pre>
</div>
</notextile>
<p>This method escapes whatever is needed, both for the key and the value:</p>
<notextile>
<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>
</notextile>
<p>so its output is ready to be used in a query string.</p>
<p>Arrays return the result of applying <tt>to_query</tt> to each element with <tt><em>key</em>[]</tt> as key, and join the result with “&”:</p>
<notextile>
<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>
</notextile>
<p>Hashes also respond to <tt>to_query</tt> but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling <tt>to_query(key)</tt> on its values. Then it joins the result with “&”:</p>
<notextile>
<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>
</notextile>
<p>The method <tt>Hash#to_query</tt> accepts an optional namespace for the keys:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/to_query.rb</tt>.</p></div>
<h4 id="with_options">2.10 <tt>with_options</tt></h4>
<p>The method <tt>with_options</tt> provides a way to factor out common options in a series of method calls.</p>
<p>Given a default options hash, <tt>with_options</tt> 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>
<notextile>
<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>
</notextile>
<p>this way:</p>
<notextile>
<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>
</notextile>
<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>
<notextile>
<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>
</notextile>
<div class='info'><p>Since <tt>with_options</tt> 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 <tt>active_support/core_ext/object/with_options.rb</tt>.</p></div>
<h4 id="instance-variables">2.11 Instance Variables</h4>
<p>Active Support provides several methods to ease access to instance variables.</p>
<h5 id="instance_variable_names">2.11.1 <tt>instance_variable_names</tt></h5>
<p>Ruby 1.8 and 1.9 have a method called <tt>instance_variables</tt> that returns the names of the defined instance variables. But they behave differently, in 1.8 it returns strings whereas in 1.9 it returns symbols. Active Support defines <tt>instance_variable_names</tt> as a portable way to obtain them as strings:</p>
<notextile>
<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 # => ["@y", "@x"]
</pre>
</div>
</notextile>
<div class='warning'><p>The order in which the names are returned is unspecified, and it indeed depends on the version of the interpreter.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
<h5 id="instance_values">2.11.2 <tt>instance_values</tt></h5>
<p>The method <tt>instance_values</tt> returns a hash that maps instance variable names without “@” to their
corresponding values. Keys are strings both in Ruby 1.8 and 1.9:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
<h4 id="silencing-warnings-streams-and-exceptions">2.12 Silencing Warnings, Streams, and Exceptions</h4>
<p>The methods <tt>silence_warnings</tt> and <tt>enable_warnings</tt> change the value of <tt>$VERBOSE</tt> accordingly for the duration of their block, and reset it afterwards:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
</pre>
</div>
</notextile>
<p>You can silence any stream while a block runs with <tt>silence_stream</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
silence_stream(STDOUT) do
# STDOUT is silent here
end
</pre>
</div>
</notextile>
<p>Silencing exceptions is also possible with <tt>suppress</tt>. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is <tt>kind_of?</tt> any of the arguments, <tt>suppress</tt> captures it and returns silently. Otherwise the exception is reraised:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/kernel/reporting.rb</tt>.</p></div>
<h4 id="require_library_or_gem">2.13 <tt>require_library_or_gem</tt></h4>
<p>The convenience method <tt>require_library_or_gem</tt> tries to load its argument with a regular <tt>require</tt> first. If it fails loads <tt>rubygems</tt> and tries again.</p>
<p>If the first attempt is a failure and <tt>rubygems</tt> can’t be loaded the method raises <tt>LoadError</tt>. On the other hand, if <tt>rubygems</tt> is available but the argument is not loadable as a gem, the method gives up and <tt>LoadError</tt> is also raised.</p>
<p>For example, that’s the way the MySQL adapter loads the MySQL library:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
require_library_or_gem('mysql')
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/kernel/requires.rb</tt>.</p></div>
<h3 id="extensions-to-module">3 Extensions to <tt>Module</tt></h3>
<h4 id="alias_method_chain">3.1 <tt>alias_method_chain</tt></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 <tt>ActionController::TestCase#process</tt> this way in <tt>test/test_helper.rb</tt>:</p>
<notextile>
<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>
</notextile>
<p>That’s the method <tt>get</tt>, <tt>post</tt>, etc., delegate the work to.</p>
<p>That technique has a risk, it could be the case that <tt>:original_process</tt> was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:</p>
<notextile>
<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>
</notextile>
<p>The method <tt>alias_method_chain</tt> provides a shortcut for that pattern:</p>
<notextile>
<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>
</notextile>
<p>Rails uses <tt>alias_method_chain</tt> all over the code base. For example validations are added to <tt>ActiveRecord::Base#save</tt> by wrapping the method that way in a separate module specialised in validations.</p>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
<h4 id="attributes">3.2 Attributes</h4>
<h5 id="alias_attribute">3.2.1 <tt>alias_attribute</tt></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 (my mnemonic is they go in the same order as if you did an assignment):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ActiveRecord::Base
# let me refer to the email column as "login",
# much meaningful for authentication code
alias_attribute :login, :email
end
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
<h5 id="attr_accessor_with_default">3.2.2 <tt>attr_accessor_with_default</tt></h5>
<p>The method <tt>attr_accessor_with_default</tt> serves the same purpose as the Ruby macro <tt>attr_accessor</tt> but allows you to set a default value for the attribute:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Url
attr_accessor_with_default :port, 80
end
Url.new.port # => 80
</pre>
</div>
</notextile>
<p>The default value can be also specified with a block, which is called in the context of the corresponding object:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User
attr_accessor :name, :surname
attr_accessor_with_default(:full_name) {
[name, surname].compact.join(" ")
}
end
u = User.new
u.name = 'Xavier'
u.surname = 'Noria'
u.full_name # => "Xavier Noria"
</pre>
</div>
</notextile>
<p>The result is not cached, the block is invoked in each call to the reader.</p>
<p>You can overwrite the default with the writer:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
url = Url.new
url.host # => 80
url.host = 8080
url.host # => 8080
</pre>
</div>
</notextile>
<p>The default value is returned as long as the attribute is unset. The reader does not rely on the value of the attribute to know whether it has to return the default. It rather monitors the writer: if there’s any assignment the value is no longer considered to be unset.</p>
<p>Active Resource uses this macro to set a default value for the <tt>:primary_key</tt> attribute:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
attr_accessor_with_default :primary_key, 'id'
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/attr_accessor_with_default.rb</tt>.</p></div>
<h5 id="internal-attributes">3.2.3 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 <tt>attr_internal_reader</tt>, <tt>attr_internal_writer</tt>, and <tt>attr_internal_accessor</tt>. They behave like their Ruby built-in <tt>attr_*</tt> counterparts, except they name the underlying instance variable in a way that makes collisions less likely.</p>
<p>The macro <tt>attr_internal</tt> is a synonym for <tt>attr_internal_accessor</tt>:</p>
<notextile>
<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>
</notextile>
<p>In the previous example it could be the case that <tt>:log_level</tt> 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 <tt>:log_level</tt>. Thanks to <tt>attr_internal</tt> there’s no collision.</p>
<p>By default the internal instance variable is named with a leading underscore, <tt>@_log_level</tt> in the example above. That’s configurable via <tt>Module.attr_internal_naming_format</tt> though, you can pass any <tt>sprintf</tt>-like format string with a leading <tt>@</tt> and a <tt>%s</tt> somewhere, which is where the name will be placed. The default is <tt>"@_%s"</tt>.</p>
<p>Rails uses internal attributes in a few spots, for examples for views:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/attr_internal.rb</tt>.</p></div>
<h5 id="module-attributes">3.2.4 Module Attributes</h5>
<p>The macros <tt>mattr_reader</tt>, <tt>mattr_writer</tt>, and <tt>mattr_accessor</tt> are analogous to the <tt>cattr_*</tt> macros defined for class. Check <a href="#class-attributes">Class Attributes</a>.</p>
<p>For example, the dependencies mechanism uses them:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/attribute_accessors.rb</tt>.</p></div>
<h4 id="parents">3.3 Parents</h4>
<h5 id="parent">3.3.1 <tt>parent</tt></h5>
<p>The <tt>parent</tt> method on a nested named module returns the module that contains its corresponding constant:</p>
<notextile>
<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>
</notextile>
<p>If the module is anonymous or belongs to the top-level, <tt>parent</tt> returns <tt>Object</tt>.</p>
<div class='warning'><p>Note that in that case <tt>parent_name</tt> returns <tt>nil</tt>.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
<h5 id="parent_name">3.3.2 <tt>parent_name</tt></h5>
<p>The <tt>parent_name</tt> method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:</p>
<notextile>
<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>
</notextile>
<p>For top-level or anonymous modules <tt>parent_name</tt> returns <tt>nil</tt>.</p>
<div class='warning'><p>Note that in that case <tt>parent</tt> returns <tt>Object</tt>.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
<h5 id="module-parents">3.3.3 <tt>parents</tt></h5>
<p>The method <tt>parents</tt> calls <tt>parent</tt> on the receiver and upwards until <tt>Object</tt> is reached. The chain is returned in an array, from bottom to top:</p>
<notextile>
<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>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
<h4 id="constants">3.4 Constants</h4>
<p>The method <tt>local_constants</tt> returns the names of the constants that have been defined in the receiver module:</p>
<notextile>
<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 # => ["X2", "X1", "Y"], assumes Ruby 1.8
X::Y.local_constants # => ["X1", "Y1"], assumes Ruby 1.8
</pre>
</div>
</notextile>
<p>The names are returned as strings in Ruby 1.8, and as symbols in Ruby 1.9. The method <tt>local_constant_names</tt> returns always strings.</p>
<div class='warning'><p>This method is exact if running under Ruby 1.9. In previous versions it may miss some constants if their value in some ancestor stores the exact same object than in the receiver.</p></div>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
<h4 id="synchronization">3.5 Synchronization</h4>
<p>The <tt>synchronize</tt> macro declares a method to be synchronized:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Counter
@@mutex = Mutex.new
attr_reader :value
def initialize
@value = 0
end
def incr
@value += 1 # non-atomic
end
synchronize :incr, :with => '@@mutex'
end
</pre>
</div>
</notextile>
<p>The method receives the name of an action, and a <tt>:with</tt> option with code. The code is evaluated in the context of the receiver each time the method is invoked, and it should evaluate to a <tt>Mutex</tt> instance or any other object that responds to <tt>synchronize</tt> and accepts a block.</p>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/synchronization.rb</tt>.</p></div>
<h4 id="reachable">3.6 Reachable</h4>
<p>A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.</p>
<p>That is what ordinarily happens, if a module is called “M”, the <tt>M</tt> constant exists and holds it:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
M.reachable? # => true
</pre>
</div>
</notextile>
<p>But since constants and modules are indeed kind of decoupled, module objects can become unreachable:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
orphan = Object.send(:remove_const, :M)
# The module object is orphan now but it still has a name.
orphan.name # => "M"
# You cannot reach it via the constant M because it does not even exist.
orphan.reachable? # => false
# Let's define a module called "M" again.
module M
end
# The constant M exists now again, and it stores a module
# object called "M", but it is a new instance.
orphan.reachable? # => false
</pre>
</div>
</notextile>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/reachable.rb</tt>.</p></div>
<h4 id="anonymous">3.7 Anonymous</h4>
<p>A module may or may not have a name:</p>
<notextile>
<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 # => "" in 1.8, nil in 1.9
</pre>
</div>
</notextile>
<p>You can check whether a module has a name with the predicate <tt>anonymous?</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
M.anonymous? # => false
Module.new.anonymous? # => true
</pre>
</div>
</notextile>
<p>Note that being unreachable does not imply being anonymous:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
module M
end
m = Object.send(:remove_const, :M)
m.reachable? # => false
m.anonymous? # => false
</pre>
</div>
</notextile>
<p>though an anonymous module is unreachable by definition.</p>
<div class='note'><p>Defined in <tt>active_support/core_ext/module/anonymous.rb</tt>.</p></div>
<h4 id="method-delegation">3.8 Method Delegation</h4>
<p>The macro <tt>delegate</tt> offers an easy way to forward methods.</p>
<p>Let’s imagine that users in some application have login information in the <tt>User</tt> model but name and other data in a separate <tt>Profile</tt> model:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class User < ActiveRecord::Base
has_one :profile
end
</pre>