railties 3.0.11 → 3.0.12.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (166) hide show
  1. data/lib/rails/version.rb +2 -2
  2. metadata +305 -461
  3. data/guides/output/2_2_release_notes.html +0 -565
  4. data/guides/output/2_3_release_notes.html +0 -713
  5. data/guides/output/3_0_release_notes.html +0 -652
  6. data/guides/output/3_1_release_notes.html +0 -670
  7. data/guides/output/action_controller_overview.html +0 -925
  8. data/guides/output/action_mailer_basics.html +0 -658
  9. data/guides/output/action_view_overview.html +0 -1471
  10. data/guides/output/active_model_basics.html +0 -349
  11. data/guides/output/active_record_basics.html +0 -364
  12. data/guides/output/active_record_querying.html +0 -1272
  13. data/guides/output/active_record_validations_callbacks.html +0 -1292
  14. data/guides/output/active_resource_basics.html +0 -252
  15. data/guides/output/active_support_core_extensions.html +0 -3374
  16. data/guides/output/ajax_on_rails.html +0 -412
  17. data/guides/output/api_documentation_guidelines.html +0 -317
  18. data/guides/output/asset_pipeline.html +0 -691
  19. data/guides/output/association_basics.html +0 -1742
  20. data/guides/output/caching_with_rails.html +0 -533
  21. data/guides/output/command_line.html +0 -662
  22. data/guides/output/configuring.html +0 -811
  23. data/guides/output/contribute.html +0 -216
  24. data/guides/output/contributing_to_ruby_on_rails.html +0 -465
  25. data/guides/output/credits.html +0 -210
  26. data/guides/output/debugging_rails_applications.html +0 -791
  27. data/guides/output/engines.html +0 -673
  28. data/guides/output/form_helpers.html +0 -850
  29. data/guides/output/generators.html +0 -725
  30. data/guides/output/getting_started.html +0 -1980
  31. data/guides/output/i18n.html +0 -1054
  32. data/guides/output/images/belongs_to.png +0 -0
  33. data/guides/output/images/book_icon.gif +0 -0
  34. data/guides/output/images/bullet.gif +0 -0
  35. data/guides/output/images/challenge.png +0 -0
  36. data/guides/output/images/chapters_icon.gif +0 -0
  37. data/guides/output/images/check_bullet.gif +0 -0
  38. data/guides/output/images/credits_pic_blank.gif +0 -0
  39. data/guides/output/images/csrf.png +0 -0
  40. data/guides/output/images/customized_error_messages.png +0 -0
  41. data/guides/output/images/edge_badge.png +0 -0
  42. data/guides/output/images/error_messages.png +0 -0
  43. data/guides/output/images/feature_tile.gif +0 -0
  44. data/guides/output/images/footer_tile.gif +0 -0
  45. data/guides/output/images/fxn.png +0 -0
  46. data/guides/output/images/grey_bullet.gif +0 -0
  47. data/guides/output/images/habtm.png +0 -0
  48. data/guides/output/images/has_many.png +0 -0
  49. data/guides/output/images/has_many_through.png +0 -0
  50. data/guides/output/images/has_one.png +0 -0
  51. data/guides/output/images/has_one_through.png +0 -0
  52. data/guides/output/images/header_backdrop.png +0 -0
  53. data/guides/output/images/header_tile.gif +0 -0
  54. data/guides/output/images/i18n/demo_html_safe.png +0 -0
  55. data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
  56. data/guides/output/images/i18n/demo_translated_en.png +0 -0
  57. data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
  58. data/guides/output/images/i18n/demo_translation_missing.png +0 -0
  59. data/guides/output/images/i18n/demo_untranslated.png +0 -0
  60. data/guides/output/images/icons/README +0 -5
  61. data/guides/output/images/icons/callouts/1.png +0 -0
  62. data/guides/output/images/icons/callouts/10.png +0 -0
  63. data/guides/output/images/icons/callouts/11.png +0 -0
  64. data/guides/output/images/icons/callouts/12.png +0 -0
  65. data/guides/output/images/icons/callouts/13.png +0 -0
  66. data/guides/output/images/icons/callouts/14.png +0 -0
  67. data/guides/output/images/icons/callouts/15.png +0 -0
  68. data/guides/output/images/icons/callouts/2.png +0 -0
  69. data/guides/output/images/icons/callouts/3.png +0 -0
  70. data/guides/output/images/icons/callouts/4.png +0 -0
  71. data/guides/output/images/icons/callouts/5.png +0 -0
  72. data/guides/output/images/icons/callouts/6.png +0 -0
  73. data/guides/output/images/icons/callouts/7.png +0 -0
  74. data/guides/output/images/icons/callouts/8.png +0 -0
  75. data/guides/output/images/icons/callouts/9.png +0 -0
  76. data/guides/output/images/icons/caution.png +0 -0
  77. data/guides/output/images/icons/example.png +0 -0
  78. data/guides/output/images/icons/home.png +0 -0
  79. data/guides/output/images/icons/important.png +0 -0
  80. data/guides/output/images/icons/next.png +0 -0
  81. data/guides/output/images/icons/note.png +0 -0
  82. data/guides/output/images/icons/prev.png +0 -0
  83. data/guides/output/images/icons/tip.png +0 -0
  84. data/guides/output/images/icons/up.png +0 -0
  85. data/guides/output/images/icons/warning.png +0 -0
  86. data/guides/output/images/jaimeiniesta.jpg +0 -0
  87. data/guides/output/images/nav_arrow.gif +0 -0
  88. data/guides/output/images/polymorphic.png +0 -0
  89. data/guides/output/images/posts_index.png +0 -0
  90. data/guides/output/images/radar.png +0 -0
  91. data/guides/output/images/rails_guides_logo.gif +0 -0
  92. data/guides/output/images/rails_logo_remix.gif +0 -0
  93. data/guides/output/images/rails_welcome.png +0 -0
  94. data/guides/output/images/session_fixation.png +0 -0
  95. data/guides/output/images/tab_grey.gif +0 -0
  96. data/guides/output/images/tab_info.gif +0 -0
  97. data/guides/output/images/tab_note.gif +0 -0
  98. data/guides/output/images/tab_red.gif +0 -0
  99. data/guides/output/images/tab_yellow.gif +0 -0
  100. data/guides/output/images/tab_yellow.png +0 -0
  101. data/guides/output/images/validation_error_messages.png +0 -0
  102. data/guides/output/images/vijaydev.jpg +0 -0
  103. data/guides/output/index.html +0 -300
  104. data/guides/output/initialization.html +0 -1087
  105. data/guides/output/javascripts/guides.js +0 -7
  106. data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  107. data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  108. data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  109. data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  110. data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  111. data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  112. data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  113. data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  114. data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  115. data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  116. data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  117. data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  118. data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  119. data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  120. data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  121. data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  122. data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  123. data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  124. data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  125. data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  126. data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  127. data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  128. data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  129. data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  130. data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  131. data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
  132. data/guides/output/layout.html +0 -312
  133. data/guides/output/layouts_and_rendering.html +0 -1257
  134. data/guides/output/migrations.html +0 -751
  135. data/guides/output/nested_model_forms.html +0 -350
  136. data/guides/output/performance_testing.html +0 -858
  137. data/guides/output/plugins.html +0 -590
  138. data/guides/output/rails_application_templates.html +0 -368
  139. data/guides/output/rails_on_rack.html +0 -408
  140. data/guides/output/routing.html +0 -1246
  141. data/guides/output/ruby_on_rails_guides_guidelines.html +0 -218
  142. data/guides/output/security.html +0 -968
  143. data/guides/output/stylesheets/fixes.css +0 -16
  144. data/guides/output/stylesheets/main.css +0 -445
  145. data/guides/output/stylesheets/print.css +0 -52
  146. data/guides/output/stylesheets/reset.css +0 -43
  147. data/guides/output/stylesheets/style.css +0 -13
  148. data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
  149. data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  150. data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  151. data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  152. data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  153. data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  154. data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  155. data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  156. data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  157. data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  158. data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  159. data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  160. data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  161. data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  162. data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  163. data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  164. data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  165. data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  166. data/guides/output/testing.html +0 -1182
@@ -1,252 +0,0 @@
1
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
-
4
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5
- <head>
6
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
7
-
8
- <title>Ruby on Rails Guides: Active Resource Basics</title>
9
-
10
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
11
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
12
-
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
14
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
15
-
16
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
17
- </head>
18
- <body class="guide">
19
- <div id="topNav">
20
- <div class="wrapper">
21
- <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
22
- <a href="http://rubyonrails.org/">Overview</a> |
23
- <a href="http://rubyonrails.org/download">Download</a> |
24
- <a href="http://rubyonrails.org/deploy">Deploy</a> |
25
- <a href="https://github.com/rails/rails">Code</a> |
26
- <a href="http://rubyonrails.org/screencasts">Screencasts</a> |
27
- <a href="http://rubyonrails.org/documentation">Documentation</a> |
28
- <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
29
- <a href="http://rubyonrails.org/community">Community</a> |
30
- <a href="http://weblog.rubyonrails.org/">Blog</a>
31
- </div>
32
- </div>
33
- <div id="header">
34
- <div class="wrapper clearfix">
35
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
36
- <p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
37
- <ul class="nav">
38
- <li><a href="index.html">Home</a></li>
39
- <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
40
- <div id="guides" class="clearfix" style="display: none;">
41
- <hr />
42
- <dl class="L">
43
- <dt>Start Here</dt>
44
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
45
- <dt>Models</dt>
46
- <dd><a href="migrations.html">Rails Database Migrations</a></dd>
47
- <dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
48
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
49
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
50
- <dt>Views</dt>
51
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
52
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
53
- <dt>Controllers</dt>
54
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
55
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
56
- </dl>
57
- <dl class="R">
58
- <dt>Digging Deeper</dt>
59
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
60
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
61
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
62
- <dd><a href="testing.html">Testing Rails Applications</a></dd>
63
- <dd><a href="security.html">Securing Rails Applications</a></dd>
64
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
65
- <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
66
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
67
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
68
- <dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
69
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
70
-
71
- <dt>Extending Rails</dt>
72
- <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
73
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
74
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
75
-
76
- <dt>Contributing to Ruby on Rails</dt>
77
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
78
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
79
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
80
-
81
- <dt>Release Notes</dt>
82
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
83
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
84
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
85
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
86
- </dl>
87
- </div>
88
- </li>
89
- <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
90
- <li><a href="credits.html">Credits</a></li>
91
- </ul>
92
- </div>
93
- </div>
94
- <hr class="hide" />
95
-
96
- <div id="feature">
97
- <div class="wrapper">
98
- <h2>Active Resource Basics</h2>
99
- <p>This guide should provide you with all you need to get started managing the connection between business objects and RESTful web services. It implements a way to map web-based resources to local objects with <span class="caps">CRUD</span> semantics.</p>
100
-
101
- <div id="subCol">
102
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
103
- <ol class="chapters">
104
- <li><a href="#introduction">Introduction</a></li><li><a href="#configuration-and-usage">Configuration and Usage</a></li><li><a href="#reading-and-writing-data">Reading and Writing Data</a><ul><li><a href="#read">Read</a></li> <li><a href="#create">Create</a></li> <li><a href="#update">Update</a></li> <li><a href="#delete">Delete</a></li></ul></li><li><a href="#validations">Validations</a><ul><li><a href="#validating-client-side-resources-by-overriding-validation-methods-in-base-class">Validating client side resources by overriding validation methods in base class</a></li> <li><a href="#validating-client-side-resources">Validating client side resources</a></li> <li><a href="#public-instance-methods">Public instance methods</a></li></ul></li></ol></div>
105
- </div>
106
- </div>
107
-
108
- <div id="container">
109
- <div class="wrapper">
110
- <div id="mainCol">
111
- <div class="warning"><p>This Guide is based on Rails 3.0. Some of the code shown here will not work in earlier versions of Rails.</p></div>
112
- <h3 id="introduction">1 Introduction</h3>
113
- <p>Active Resource allows you to connect with RESTful web services. So, in Rails, Resource classes inherited from <tt>ActiveResource::Base</tt> and live in <tt>app/models</tt>.</p>
114
- <h3 id="configuration-and-usage">2 Configuration and Usage</h3>
115
- <p>Putting Active Resource to use is very similar to Active Record. It&#8217;s as simple as creating a model class
116
- that inherits from ActiveResource::Base and providing a <tt>site</tt> class variable to it:</p>
117
- <div class="code_container">
118
- <pre class="brush: ruby; gutter: false; toolbar: false">
119
- class Person &lt; ActiveResource::Base
120
- self.site = &quot;http://api.people.com:3000/&quot;
121
- end
122
- </pre>
123
- </div>
124
- <p>Now the Person class is <span class="caps">REST</span> enabled and can invoke <span class="caps">REST</span> services very similarly to how Active Record invokes
125
- life cycle methods that operate against a persistent store.</p>
126
- <h3 id="reading-and-writing-data">3 Reading and Writing Data</h3>
127
- <p>Active Resource make request over <span class="caps">HTTP</span> using a standard <span class="caps">JSON</span> format. It mirrors the RESTful routing built into Action Controller but will also work with any other <span class="caps">REST</span> service that properly implements the protocol.</p>
128
- <h4 id="read">3.1 Read</h4>
129
- <p>Read requests use the <span class="caps">GET</span> method and expect the <span class="caps">JSON</span> form of whatever resource/resources is/are being requested.</p>
130
- <div class="code_container">
131
- <pre class="brush: ruby; gutter: false; toolbar: false">
132
- # Find a person with id = 1
133
- person = Person.find(1)
134
- # Check if a person exists with id = 1
135
- Person.exists?(1) # =&gt; true
136
- # Get all resources of Person class
137
- Person.all
138
- </pre>
139
- </div>
140
- <h4 id="create">3.2 Create</h4>
141
- <p>Creating a new resource submits the <span class="caps">JSON</span> form of the resource as the body of the request with <span class="caps">HTTP</span> <span class="caps">POST</span> method and parse the response into Active Resource object.</p>
142
- <div class="code_container">
143
- <pre class="brush: ruby; gutter: false; toolbar: false">
144
- person = Person.create(:name =&gt; 'Vishnu')
145
- person.id # =&gt; 1
146
- </pre>
147
- </div>
148
- <h4 id="update">3.3 Update</h4>
149
- <p>To update an existing resource, &#8216;save&#8217; method is used. This method make a <span class="caps">HTTP</span> <span class="caps">PUT</span> request in <span class="caps">JSON</span> format.</p>
150
- <div class="code_container">
151
- <pre class="brush: ruby; gutter: false; toolbar: false">
152
- person = Person.find(1)
153
- person.name = 'Atrai'
154
- person.save
155
- </pre>
156
- </div>
157
- <h4 id="delete">3.4 Delete</h4>
158
- <p>&#8216;destroy&#8217; method makes a <span class="caps">HTTP</span> <span class="caps">DELETE</span> request for an existing resource in <span class="caps">JSON</span> format to delete that resource.</p>
159
- <div class="code_container">
160
- <pre class="brush: ruby; gutter: false; toolbar: false">
161
- person = Person.find(1)
162
- person.destroy
163
- </pre>
164
- </div>
165
- <h3 id="validations">4 Validations</h3>
166
- <p>Module to support validation and errors with Active Resource objects. The module overrides Base#save to rescue ActiveResource::ResourceInvalid exceptions and parse the errors returned in the web service response. The module also adds an errors collection that mimics the interface of the errors provided by ActiveRecord::Errors.</p>
167
- <h4 id="validating-client-side-resources-by-overriding-validation-methods-in-base-class">4.1 Validating client side resources by overriding validation methods in base class</h4>
168
- <div class="code_container">
169
- <pre class="brush: ruby; gutter: false; toolbar: false">
170
- class Person &lt; ActiveResource::Base
171
- self.site = &quot;http://api.people.com:3000/&quot;
172
-
173
- protected
174
-
175
- def validate
176
- errors.add(&quot;last&quot;, &quot;has invalid characters&quot;) unless last =~ /[a-zA-Z]*/
177
- end
178
- end
179
- </pre>
180
- </div>
181
- <h4 id="validating-client-side-resources">4.2 Validating client side resources</h4>
182
- <p>Consider a Person resource on the server requiring both a first_name and a last_name with a validates_presence_of :first_name, :last_name declaration in the model:</p>
183
- <div class="code_container">
184
- <pre class="brush: ruby; gutter: false; toolbar: false">
185
- person = Person.new(:first_name =&gt; &quot;Jim&quot;, :last_name =&gt; &quot;&quot;)
186
- person.save # =&gt; false (server returns an HTTP 422 status code and errors)
187
- person.valid? # =&gt; false
188
- person.errors.empty? # =&gt; false
189
- person.errors.count # =&gt; 1
190
- person.errors.full_messages # =&gt; [&quot;Last name can't be empty&quot;]
191
- person.errors[:last_name] # =&gt; [&quot;can't be empty&quot;]
192
- person.last_name = &quot;Halpert&quot;
193
- person.save # =&gt; true (and person is now saved to the remote service)
194
- </pre>
195
- </div>
196
- <h4 id="public-instance-methods">4.3 Public instance methods</h4>
197
- <p>ActiveResource::Validations have three public instance methods</p>
198
- <h5 id="errors">4.3.1 errors()</h5>
199
- <p>This will return errors object that holds all information about attribute error messages</p>
200
- <h5 id="save_with_validation-options-nil">4.3.2 save_with_validation(options=nil)</h5>
201
- <p>This validates the resource with any local validations written in base class and then it will try to <span class="caps">POST</span> if there are no errors.</p>
202
- <h5 id="valid">4.3.3 valid?</h5>
203
- <p>Runs all the local validations and will return true if no errors.</p>
204
-
205
- <h3>Feedback</h3>
206
- <p>
207
- You're encouraged to help improve the quality of this guide.
208
- </p>
209
- <p>
210
- If you see any typos or factual errors you are confident to
211
- patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
212
- and push the change yourself. That branch of Rails has public write access.
213
- Commits are still reviewed, but that happens after you've submitted your
214
- contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
215
- cross-merged with master periodically.
216
- </p>
217
- <p>
218
- You may also find incomplete content, or stuff that is not up to date.
219
- Please do add any missing documentation for master. Check the
220
- <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
221
- for style and conventions.
222
- </p>
223
- <p>
224
- If for whatever reason you spot something to fix but cannot patch it yourself, please
225
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
226
- </p>
227
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
228
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
229
- </p>
230
- </div>
231
- </div>
232
- </div>
233
-
234
- <hr class="hide" />
235
- <div id="footer">
236
- <div class="wrapper">
237
- <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
238
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
239
- </div>
240
- </div>
241
-
242
- <script type="text/javascript" src="javascripts/guides.js"></script>
243
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
244
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
245
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
246
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
247
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
248
- <script type="text/javascript">
249
- SyntaxHighlighter.all()
250
- </script>
251
- </body>
252
- </html>
@@ -1,3374 +0,0 @@
1
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
2
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
3
-
4
- <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
5
- <head>
6
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
7
-
8
- <title>Ruby on Rails Guides: Active Support Core Extensions</title>
9
-
10
- <link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
11
- <link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
12
-
13
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
14
- <link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
15
-
16
- <link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
17
- </head>
18
- <body class="guide">
19
- <div id="topNav">
20
- <div class="wrapper">
21
- <strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
22
- <a href="http://rubyonrails.org/">Overview</a> |
23
- <a href="http://rubyonrails.org/download">Download</a> |
24
- <a href="http://rubyonrails.org/deploy">Deploy</a> |
25
- <a href="https://github.com/rails/rails">Code</a> |
26
- <a href="http://rubyonrails.org/screencasts">Screencasts</a> |
27
- <a href="http://rubyonrails.org/documentation">Documentation</a> |
28
- <a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
29
- <a href="http://rubyonrails.org/community">Community</a> |
30
- <a href="http://weblog.rubyonrails.org/">Blog</a>
31
- </div>
32
- </div>
33
- <div id="header">
34
- <div class="wrapper clearfix">
35
- <h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
36
- <p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
37
- <ul class="nav">
38
- <li><a href="index.html">Home</a></li>
39
- <li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
40
- <div id="guides" class="clearfix" style="display: none;">
41
- <hr />
42
- <dl class="L">
43
- <dt>Start Here</dt>
44
- <dd><a href="getting_started.html">Getting Started with Rails</a></dd>
45
- <dt>Models</dt>
46
- <dd><a href="migrations.html">Rails Database Migrations</a></dd>
47
- <dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
48
- <dd><a href="association_basics.html">Active Record Associations</a></dd>
49
- <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
50
- <dt>Views</dt>
51
- <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
52
- <dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
53
- <dt>Controllers</dt>
54
- <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
55
- <dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
56
- </dl>
57
- <dl class="R">
58
- <dt>Digging Deeper</dt>
59
- <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
60
- <dd><a href="i18n.html">Rails Internationalization API</a></dd>
61
- <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
62
- <dd><a href="testing.html">Testing Rails Applications</a></dd>
63
- <dd><a href="security.html">Securing Rails Applications</a></dd>
64
- <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
65
- <dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
66
- <dd><a href="configuring.html">Configuring Rails Applications</a></dd>
67
- <dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
68
- <dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
69
- <dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
70
-
71
- <dt>Extending Rails</dt>
72
- <dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
73
- <dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
74
- <dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
75
-
76
- <dt>Contributing to Ruby on Rails</dt>
77
- <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
78
- <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
79
- <dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
80
-
81
- <dt>Release Notes</dt>
82
- <dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
83
- <dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
84
- <dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
85
- <dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
86
- </dl>
87
- </div>
88
- </li>
89
- <li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
90
- <li><a href="credits.html">Credits</a></li>
91
- </ul>
92
- </div>
93
- </div>
94
- <hr class="hide" />
95
-
96
- <div id="feature">
97
- <div class="wrapper">
98
- <h2>Active Support Core Extensions</h2>
99
- <p>Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.</p>
100
- <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>
101
- <p>By referring to this guide you will learn the extensions to the Ruby core classes and modules provided by Active Support.</p>
102
-
103
- <div id="subCol">
104
- <h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
105
- <ol class="chapters">
106
- <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="#in"><tt>in?</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 &amp; 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="#inquiry"><tt>inquiry</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="#adding-elements">Adding Elements</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="#extracting">Extracting</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="#cover"><tt>cover?</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></ol></div>
107
- </div>
108
- </div>
109
-
110
- <div id="container">
111
- <div class="wrapper">
112
- <div id="mainCol">
113
- <h3 id="how-to-load-core-extensions">1 How to Load Core Extensions</h3>
114
- <h4 id="stand-alone-active-support">1.1 Stand-Alone Active Support</h4>
115
- <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>
116
- <p>Thus, after a simple require like:</p>
117
- <div class="code_container">
118
- <pre class="brush: ruby; gutter: false; toolbar: false">
119
- require 'active_support'
120
- </pre>
121
- </div>
122
- <p>objects do not even respond to <tt>blank?</tt>. Let&#8217;s see how to load its definition.</p>
123
- <h5 id="cherry-picking-a-definition">1.1.1 Cherry-picking a Definition</h5>
124
- <p>The most lightweight way to get <tt>blank?</tt> is to cherry-pick the file that defines it.</p>
125
- <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>
126
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
127
- <p>That means that this single call is enough:</p>
128
- <div class="code_container">
129
- <pre class="brush: ruby; gutter: false; toolbar: false">
130
- require 'active_support/core_ext/object/blank'
131
- </pre>
132
- </div>
133
- <p>Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.</p>
134
- <h5 id="loading-grouped-core-extensions">1.1.2 Loading Grouped Core Extensions</h5>
135
- <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>
136
- <p>Thus, to load all extensions to <tt>Object</tt> (including <tt>blank?</tt>):</p>
137
- <div class="code_container">
138
- <pre class="brush: ruby; gutter: false; toolbar: false">
139
- require 'active_support/core_ext/object'
140
- </pre>
141
- </div>
142
- <h5 id="loading-all-core-extensions">1.1.3 Loading All Core Extensions</h5>
143
- <p>You may prefer just to load all core extensions, there is a file for that:</p>
144
- <div class="code_container">
145
- <pre class="brush: ruby; gutter: false; toolbar: false">
146
- require 'active_support/core_ext'
147
- </pre>
148
- </div>
149
- <h5 id="loading-all-active-support">1.1.4 Loading All Active Support</h5>
150
- <p>And finally, if you want to have all Active Support available just issue:</p>
151
- <div class="code_container">
152
- <pre class="brush: ruby; gutter: false; toolbar: false">
153
- require 'active_support/all'
154
- </pre>
155
- </div>
156
- <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>
157
- <h4 id="active-support-within-a-ruby-on-rails-application">1.2 Active Support Within a Ruby on Rails Application</h4>
158
- <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>
159
- <h3 id="extensions-to-all-objects">2 Extensions to All Objects</h3>
160
- <h4 id="blank-and-present">2.1 <tt>blank?</tt> and <tt>present?</tt></h4>
161
- <p>The following values are considered to be blank in a Rails application:</p>
162
- <ul>
163
- <li><tt>nil</tt> and <tt>false</tt>,</li>
164
- </ul>
165
- <ul>
166
- <li>strings composed only of whitespace (see note below),</li>
167
- </ul>
168
- <ul>
169
- <li>empty arrays and hashes, and</li>
170
- </ul>
171
- <ul>
172
- <li>any other object that responds to <tt>empty?</tt> and it is empty.</li>
173
- </ul>
174
- <div class="info"><p>In Ruby 1.9 the predicate for strings uses the Unicode-aware character class <tt>[:space:]</tt>, so for example U<tt>2029 (paragraph separator) is considered to be whitespace. In Ruby 1.8 whitespace is considered to be <tt>\s</tt> together with the ideographic space U</tt>3000.</p></div>
175
- <div class="warning"><p>Note that numbers are not mentioned, in particular 0 and 0.0 are <strong>not</strong> blank.</p></div>
176
- <p>For example, this method from <tt>ActionDispatch::Session::AbstractStore</tt> uses <tt>blank?</tt> for checking whether a session key is present:</p>
177
- <div class="code_container">
178
- <pre class="brush: ruby; gutter: false; toolbar: false">
179
- def ensure_session_key!
180
- if @key.blank?
181
- raise ArgumentError, 'A key is required...'
182
- end
183
- end
184
- </pre>
185
- </div>
186
- <p>The method <tt>present?</tt> is equivalent to <tt>!blank?</tt>. This example is taken from <tt>ActionDispatch::Http::Cache::Response</tt>:</p>
187
- <div class="code_container">
188
- <pre class="brush: ruby; gutter: false; toolbar: false">
189
- def set_conditional_cache_control!
190
- return if self[&quot;Cache-Control&quot;].present?
191
- ...
192
- end
193
- </pre>
194
- </div>
195
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
196
- <h4 id="presence">2.2 <tt>presence</tt></h4>
197
- <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>
198
- <div class="code_container">
199
- <pre class="brush: ruby; gutter: false; toolbar: false">
200
- host = config[:host].presence || 'localhost'
201
- </pre>
202
- </div>
203
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/blank.rb</tt>.</p></div>
204
- <h4 id="duplicable">2.3 <tt>duplicable?</tt></h4>
205
- <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>
206
- <div class="code_container">
207
- <pre class="brush: ruby; gutter: false; toolbar: false">
208
- 1.object_id # =&gt; 3
209
- Math.cos(0).to_i.object_id # =&gt; 3
210
- </pre>
211
- </div>
212
- <p>Hence, there&#8217;s no way these objects can be duplicated through <tt>dup</tt> or <tt>clone</tt>:</p>
213
- <div class="code_container">
214
- <pre class="brush: ruby; gutter: false; toolbar: false">
215
- true.dup # =&gt; TypeError: can't dup TrueClass
216
- </pre>
217
- </div>
218
- <p>Some numbers which are not singletons are not duplicable either:</p>
219
- <div class="code_container">
220
- <pre class="brush: ruby; gutter: false; toolbar: false">
221
- 0.0.clone # =&gt; allocator undefined for Float
222
- (2**1024).clone # =&gt; allocator undefined for Bignum
223
- </pre>
224
- </div>
225
- <p>Active Support provides <tt>duplicable?</tt> to programmatically query an object about this property:</p>
226
- <div class="code_container">
227
- <pre class="brush: ruby; gutter: false; toolbar: false">
228
- &quot;&quot;.duplicable? # =&gt; true
229
- false.duplicable? # =&gt; false
230
- </pre>
231
- </div>
232
- <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>
233
- <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>
234
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/duplicable.rb</tt>.</p></div>
235
- <h4 id="try">2.4 <tt>try</tt></h4>
236
- <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>
237
- <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>
238
- <div class="code_container">
239
- <pre class="brush: ruby; gutter: false; toolbar: false">
240
- def log_info(sql, name, ms)
241
- if @logger.try(:debug?)
242
- name = '%s (%.1fms)' % [name || 'SQL', ms]
243
- @logger.debug(format_log_entry(name, sql.squeeze(' ')))
244
- end
245
- end
246
- </pre>
247
- </div>
248
- <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>
249
- <div class="code_container">
250
- <pre class="brush: ruby; gutter: false; toolbar: false">
251
- @person.try { |p| &quot;#{p.first_name} #{p.last_name}&quot; }
252
- </pre>
253
- </div>
254
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/try.rb</tt>.</p></div>
255
- <h4 id="singleton_class">2.5 <tt>singleton_class</tt></h4>
256
- <p>The method <tt>singleton_class</tt> returns the singleton class of the receiver:</p>
257
- <div class="code_container">
258
- <pre class="brush: ruby; gutter: false; toolbar: false">
259
- String.singleton_class # =&gt; #&lt;Class:String&gt;
260
- String.new.singleton_class # =&gt; #&lt;Class:#&lt;String:0x17a1d1c&gt;&gt;
261
- </pre>
262
- </div>
263
- <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>
264
- <div class="note"><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
265
- <h4 id="class_eval-args-block">2.6 <tt>class_eval(*args, &block)</tt></h4>
266
- <p>You can evaluate code in the context of any object&#8217;s singleton class using <tt>class_eval</tt>:</p>
267
- <div class="code_container">
268
- <pre class="brush: ruby; gutter: false; toolbar: false">
269
- class Proc
270
- def bind(object)
271
- block, time = self, Time.now
272
- object.class_eval do
273
- method_name = &quot;__bind_#{time.to_i}_#{time.usec}&quot;
274
- define_method(method_name, &amp;block)
275
- method = instance_method(method_name)
276
- remove_method(method_name)
277
- method
278
- end.bind(object)
279
- end
280
- end
281
- </pre>
282
- </div>
283
- <div class="note"><p>Defined in <tt>active_support/core_ext/kernel/singleton_class.rb</tt>.</p></div>
284
- <h4 id="acts_like-duck">2.7 <tt>acts_like?(duck)</tt></h4>
285
- <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>
286
- <div class="code_container">
287
- <pre class="brush: ruby; gutter: false; toolbar: false">
288
- def acts_like_string?
289
- end
290
- </pre>
291
- </div>
292
- <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>
293
- <div class="code_container">
294
- <pre class="brush: ruby; gutter: false; toolbar: false">
295
- some_klass.acts_like?(:string)
296
- </pre>
297
- </div>
298
- <p>Rails has classes that act like <tt>Date</tt> or <tt>Time</tt> and follow this contract.</p>
299
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/acts_like.rb</tt>.</p></div>
300
- <h4 id="to_param">2.8 <tt>to_param</tt></h4>
301
- <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>
302
- <p>By default <tt>to_param</tt> just calls <tt>to_s</tt>:</p>
303
- <div class="code_container">
304
- <pre class="brush: ruby; gutter: false; toolbar: false">
305
- 7.to_param # =&gt; &quot;7&quot;
306
- </pre>
307
- </div>
308
- <p>The return value of <tt>to_param</tt> should <strong>not</strong> be escaped:</p>
309
- <div class="code_container">
310
- <pre class="brush: ruby; gutter: false; toolbar: false">
311
- &quot;Tom &amp; Jerry&quot;.to_param # =&gt; &quot;Tom &amp; Jerry&quot;
312
- </pre>
313
- </div>
314
- <p>Several classes in Rails overwrite this method.</p>
315
- <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 &#8220;/&#8221;:</p>
316
- <div class="code_container">
317
- <pre class="brush: ruby; gutter: false; toolbar: false">
318
- [0, true, String].to_param # =&gt; &quot;0/true/String&quot;
319
- </pre>
320
- </div>
321
- <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>
322
- <div class="code_container">
323
- <pre class="brush: ruby; gutter: false; toolbar: false">
324
- class User
325
- def to_param
326
- &quot;#{id}-#{name.parameterize}&quot;
327
- end
328
- end
329
- </pre>
330
- </div>
331
- <p>we get:</p>
332
- <div class="code_container">
333
- <pre class="brush: ruby; gutter: false; toolbar: false">
334
- user_path(@user) # =&gt; &quot;/users/357-john-smith&quot;
335
- </pre>
336
- </div>
337
- <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 &#8220;357-john-smith&#8221; is the value of <tt>params[:id]</tt>.</p></div>
338
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/to_param.rb</tt>.</p></div>
339
- <h4 id="to_query">2.9 <tt>to_query</tt></h4>
340
- <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>
341
- <div class="code_container">
342
- <pre class="brush: ruby; gutter: false; toolbar: false">
343
- class User
344
- def to_param
345
- &quot;#{id}-#{name.parameterize}&quot;
346
- end
347
- end
348
- </pre>
349
- </div>
350
- <p>we get:</p>
351
- <div class="code_container">
352
- <pre class="brush: ruby; gutter: false; toolbar: false">
353
- current_user.to_query('user') # =&gt; user=357-john-smith
354
- </pre>
355
- </div>
356
- <p>This method escapes whatever is needed, both for the key and the value:</p>
357
- <div class="code_container">
358
- <pre class="brush: ruby; gutter: false; toolbar: false">
359
- account.to_query('company[name]')
360
- # =&gt; &quot;company%5Bname%5D=Johnson+%26+Johnson&quot;
361
- </pre>
362
- </div>
363
- <p>so its output is ready to be used in a query string.</p>
364
- <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 &#8220;&amp;&#8221;:</p>
365
- <div class="code_container">
366
- <pre class="brush: ruby; gutter: false; toolbar: false">
367
- [3.4, -45.6].to_query('sample')
368
- # =&gt; &quot;sample%5B%5D=3.4&amp;sample%5B%5D=-45.6&quot;
369
- </pre>
370
- </div>
371
- <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 &#8220;&amp;&#8221;:</p>
372
- <div class="code_container">
373
- <pre class="brush: ruby; gutter: false; toolbar: false">
374
- {:c =&gt; 3, :b =&gt; 2, :a =&gt; 1}.to_query # =&gt; &quot;a=1&amp;b=2&amp;c=3&quot;
375
- </pre>
376
- </div>
377
- <p>The method <tt>Hash#to_query</tt> accepts an optional namespace for the keys:</p>
378
- <div class="code_container">
379
- <pre class="brush: ruby; gutter: false; toolbar: false">
380
- {:id =&gt; 89, :name =&gt; &quot;John Smith&quot;}.to_query('user')
381
- # =&gt; &quot;user%5Bid%5D=89&amp;user%5Bname%5D=John+Smith&quot;
382
- </pre>
383
- </div>
384
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/to_query.rb</tt>.</p></div>
385
- <h4 id="with_options">2.10 <tt>with_options</tt></h4>
386
- <p>The method <tt>with_options</tt> provides a way to factor out common options in a series of method calls.</p>
387
- <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>
388
- <div class="code_container">
389
- <pre class="brush: ruby; gutter: false; toolbar: false">
390
- class Account &lt; ActiveRecord::Base
391
- has_many :customers, :dependent =&gt; :destroy
392
- has_many :products, :dependent =&gt; :destroy
393
- has_many :invoices, :dependent =&gt; :destroy
394
- has_many :expenses, :dependent =&gt; :destroy
395
- end
396
- </pre>
397
- </div>
398
- <p>this way:</p>
399
- <div class="code_container">
400
- <pre class="brush: ruby; gutter: false; toolbar: false">
401
- class Account &lt; ActiveRecord::Base
402
- with_options :dependent =&gt; :destroy do |assoc|
403
- assoc.has_many :customers
404
- assoc.has_many :products
405
- assoc.has_many :invoices
406
- assoc.has_many :expenses
407
- end
408
- end
409
- </pre>
410
- </div>
411
- <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>
412
- <div class="code_container">
413
- <pre class="brush: ruby; gutter: false; toolbar: false">
414
- I18n.with_options :locale =&gt; user.locale, :scope =&gt; &quot;newsletter&quot; do |i18n|
415
- subject i18n.t :subject
416
- body i18n.t :body, :user_name =&gt; user.name
417
- end
418
- </pre>
419
- </div>
420
- <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>
421
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/with_options.rb</tt>.</p></div>
422
- <h4 id="instance-variables">2.11 Instance Variables</h4>
423
- <p>Active Support provides several methods to ease access to instance variables.</p>
424
- <h5 id="instance_variable_names">2.11.1 <tt>instance_variable_names</tt></h5>
425
- <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>
426
- <div class="code_container">
427
- <pre class="brush: ruby; gutter: false; toolbar: false">
428
- class C
429
- def initialize(x, y)
430
- @x, @y = x, y
431
- end
432
- end
433
-
434
- C.new(0, 1).instance_variable_names # =&gt; [&quot;@y&quot;, &quot;@x&quot;]
435
- </pre>
436
- </div>
437
- <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>
438
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
439
- <h5 id="instance_values">2.11.2 <tt>instance_values</tt></h5>
440
- <p>The method <tt>instance_values</tt> returns a hash that maps instance variable names without &#8220;@&#8221; to their
441
- corresponding values. Keys are strings both in Ruby 1.8 and 1.9:</p>
442
- <div class="code_container">
443
- <pre class="brush: ruby; gutter: false; toolbar: false">
444
- class C
445
- def initialize(x, y)
446
- @x, @y = x, y
447
- end
448
- end
449
-
450
- C.new(0, 1).instance_values # =&gt; {&quot;x&quot; =&gt; 0, &quot;y&quot; =&gt; 1}
451
- </pre>
452
- </div>
453
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/instance_variables.rb</tt>.</p></div>
454
- <h4 id="silencing-warnings-streams-and-exceptions">2.12 Silencing Warnings, Streams, and Exceptions</h4>
455
- <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>
456
- <div class="code_container">
457
- <pre class="brush: ruby; gutter: false; toolbar: false">
458
- silence_warnings { Object.const_set &quot;RAILS_DEFAULT_LOGGER&quot;, logger }
459
- </pre>
460
- </div>
461
- <p>You can silence any stream while a block runs with <tt>silence_stream</tt>:</p>
462
- <div class="code_container">
463
- <pre class="brush: ruby; gutter: false; toolbar: false">
464
- silence_stream(STDOUT) do
465
- # STDOUT is silent here
466
- end
467
- </pre>
468
- </div>
469
- <p>The <tt>quietly</tt> method addresses the common use case where you want to silence <span class="caps">STDOUT</span> and <span class="caps">STDERR</span>, even in subprocesses:</p>
470
- <div class="code_container">
471
- <pre class="brush: ruby; gutter: false; toolbar: false">
472
- quietly { system 'bundle install' }
473
- </pre>
474
- </div>
475
- <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>
476
- <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>
477
- <div class="code_container">
478
- <pre class="brush: ruby; gutter: false; toolbar: false">
479
- # If the user is locked the increment is lost, no big deal.
480
- suppress(ActiveRecord::StaleObjectError) do
481
- current_user.increment! :visits
482
- end
483
- </pre>
484
- </div>
485
- <div class="note"><p>Defined in <tt>active_support/core_ext/kernel/reporting.rb</tt>.</p></div>
486
- <h4 id="in">2.13 <tt>in?</tt></h4>
487
- <p>The predicate <tt>in?</tt> tests if an object is included in another object. An <tt>ArgumentError</tt> exception will be raised if the argument passed does not respond to <tt>include?</tt>.</p>
488
- <p>Examples of <tt>in?</tt>:</p>
489
- <div class="code_container">
490
- <pre class="brush: ruby; gutter: false; toolbar: false">
491
- 1.in?([1,2]) # =&gt; true
492
- &quot;lo&quot;.in?(&quot;hello&quot;) # =&gt; true
493
- 25.in?(30..50) # =&gt; false
494
- </pre>
495
- </div>
496
- <div class="note"><p>Defined in <tt>active_support/core_ext/object/inclusion.rb</tt>.</p></div>
497
- <h3 id="extensions-to-module">3 Extensions to <tt>Module</tt></h3>
498
- <h4 id="alias_method_chain">3.1 <tt>alias_method_chain</tt></h4>
499
- <p>Using plain Ruby you can wrap methods with other methods, that&#8217;s called <em>alias chaining</em>.</p>
500
- <p>For example, let&#8217;s say you&#8217;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>
501
- <div class="code_container">
502
- <pre class="brush: ruby; gutter: false; toolbar: false">
503
- ActionController::TestCase.class_eval do
504
- # save a reference to the original process method
505
- alias_method :original_process, :process
506
-
507
- # now redefine process and delegate to original_process
508
- def process(action, params=nil, session=nil, flash=nil, http_method='GET')
509
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
510
- original_process(action, params, session, flash, http_method)
511
- end
512
- end
513
- </pre>
514
- </div>
515
- <p>That&#8217;s the method <tt>get</tt>, <tt>post</tt>, etc., delegate the work to.</p>
516
- <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>
517
- <div class="code_container">
518
- <pre class="brush: ruby; gutter: false; toolbar: false">
519
- ActionController::TestCase.class_eval do
520
- def process_with_stringified_params(...)
521
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
522
- process_without_stringified_params(action, params, session, flash, http_method)
523
- end
524
- alias_method :process_without_stringified_params, :process
525
- alias_method :process, :process_with_stringified_params
526
- end
527
- </pre>
528
- </div>
529
- <p>The method <tt>alias_method_chain</tt> provides a shortcut for that pattern:</p>
530
- <div class="code_container">
531
- <pre class="brush: ruby; gutter: false; toolbar: false">
532
- ActionController::TestCase.class_eval do
533
- def process_with_stringified_params(...)
534
- params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
535
- process_without_stringified_params(action, params, session, flash, http_method)
536
- end
537
- alias_method_chain :process, :stringified_params
538
- end
539
- </pre>
540
- </div>
541
- <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 specialized in validations.</p>
542
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
543
- <h4 id="attributes">3.2 Attributes</h4>
544
- <h5 id="alias_attribute">3.2.1 <tt>alias_attribute</tt></h5>
545
- <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>
546
- <div class="code_container">
547
- <pre class="brush: ruby; gutter: false; toolbar: false">
548
- class User &lt; ActiveRecord::Base
549
- # let me refer to the email column as &quot;login&quot;,
550
- # possibly meaningful for authentication code
551
- alias_attribute :login, :email
552
- end
553
- </pre>
554
- </div>
555
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/aliasing.rb</tt>.</p></div>
556
- <h5 id="attr_accessor_with_default">3.2.2 <tt>attr_accessor_with_default</tt></h5>
557
- <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>
558
- <div class="code_container">
559
- <pre class="brush: ruby; gutter: false; toolbar: false">
560
- class Url
561
- attr_accessor_with_default :port, 80
562
- end
563
-
564
- Url.new.port # =&gt; 80
565
- </pre>
566
- </div>
567
- <p>The default value can be also specified with a block, which is called in the context of the corresponding object:</p>
568
- <div class="code_container">
569
- <pre class="brush: ruby; gutter: false; toolbar: false">
570
- class User
571
- attr_accessor :name, :surname
572
- attr_accessor_with_default(:full_name) do
573
- [name, surname].compact.join(&quot; &quot;)
574
- end
575
- end
576
-
577
- u = User.new
578
- u.name = 'Xavier'
579
- u.surname = 'Noria'
580
- u.full_name # =&gt; &quot;Xavier Noria&quot;
581
- </pre>
582
- </div>
583
- <p>The result is not cached, the block is invoked in each call to the reader.</p>
584
- <p>You can overwrite the default with the writer:</p>
585
- <div class="code_container">
586
- <pre class="brush: ruby; gutter: false; toolbar: false">
587
- url = Url.new
588
- url.host # =&gt; 80
589
- url.host = 8080
590
- url.host # =&gt; 8080
591
- </pre>
592
- </div>
593
- <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&#8217;s any assignment the value is no longer considered to be unset.</p>
594
- <p>Active Resource uses this macro to set a default value for the <tt>:primary_key</tt> attribute:</p>
595
- <div class="code_container">
596
- <pre class="brush: ruby; gutter: false; toolbar: false">
597
- attr_accessor_with_default :primary_key, 'id'
598
- </pre>
599
- </div>
600
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/attr_accessor_with_default.rb</tt>.</p></div>
601
- <h5 id="internal-attributes">3.2.3 Internal Attributes</h5>
602
- <p>When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That&#8217;s remarkably important for libraries.</p>
603
- <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>
604
- <p>The macro <tt>attr_internal</tt> is a synonym for <tt>attr_internal_accessor</tt>:</p>
605
- <div class="code_container">
606
- <pre class="brush: ruby; gutter: false; toolbar: false">
607
- # library
608
- class ThirdPartyLibrary::Crawler
609
- attr_internal :log_level
610
- end
611
-
612
- # client code
613
- class MyCrawler &lt; ThirdPartyLibrary::Crawler
614
- attr_accessor :log_level
615
- end
616
- </pre>
617
- </div>
618
- <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&#8217;s no collision.</p>
619
- <p>By default the internal instance variable is named with a leading underscore, <tt>@_log_level</tt> in the example above. That&#8217;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>
620
- <p>Rails uses internal attributes in a few spots, for examples for views:</p>
621
- <div class="code_container">
622
- <pre class="brush: ruby; gutter: false; toolbar: false">
623
- module ActionView
624
- class Base
625
- attr_internal :captures
626
- attr_internal :request, :layout
627
- attr_internal :controller, :template
628
- end
629
- end
630
- </pre>
631
- </div>
632
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/attr_internal.rb</tt>.</p></div>
633
- <h5 id="module-attributes">3.2.4 Module Attributes</h5>
634
- <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>
635
- <p>For example, the dependencies mechanism uses them:</p>
636
- <div class="code_container">
637
- <pre class="brush: ruby; gutter: false; toolbar: false">
638
- module ActiveSupport
639
- module Dependencies
640
- mattr_accessor :warnings_on_first_load
641
- mattr_accessor :history
642
- mattr_accessor :loaded
643
- mattr_accessor :mechanism
644
- mattr_accessor :load_paths
645
- mattr_accessor :load_once_paths
646
- mattr_accessor :autoloaded_constants
647
- mattr_accessor :explicitly_unloadable_constants
648
- mattr_accessor :logger
649
- mattr_accessor :log_activity
650
- mattr_accessor :constant_watch_stack
651
- mattr_accessor :constant_watch_stack_mutex
652
- end
653
- end
654
- </pre>
655
- </div>
656
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/attribute_accessors.rb</tt>.</p></div>
657
- <h4 id="parents">3.3 Parents</h4>
658
- <h5 id="parent">3.3.1 <tt>parent</tt></h5>
659
- <p>The <tt>parent</tt> method on a nested named module returns the module that contains its corresponding constant:</p>
660
- <div class="code_container">
661
- <pre class="brush: ruby; gutter: false; toolbar: false">
662
- module X
663
- module Y
664
- module Z
665
- end
666
- end
667
- end
668
- M = X::Y::Z
669
-
670
- X::Y::Z.parent # =&gt; X::Y
671
- M.parent # =&gt; X::Y
672
- </pre>
673
- </div>
674
- <p>If the module is anonymous or belongs to the top-level, <tt>parent</tt> returns <tt>Object</tt>.</p>
675
- <div class="warning"><p>Note that in that case <tt>parent_name</tt> returns <tt>nil</tt>.</p></div>
676
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
677
- <h5 id="parent_name">3.3.2 <tt>parent_name</tt></h5>
678
- <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>
679
- <div class="code_container">
680
- <pre class="brush: ruby; gutter: false; toolbar: false">
681
- module X
682
- module Y
683
- module Z
684
- end
685
- end
686
- end
687
- M = X::Y::Z
688
-
689
- X::Y::Z.parent_name # =&gt; &quot;X::Y&quot;
690
- M.parent_name # =&gt; &quot;X::Y&quot;
691
- </pre>
692
- </div>
693
- <p>For top-level or anonymous modules <tt>parent_name</tt> returns <tt>nil</tt>.</p>
694
- <div class="warning"><p>Note that in that case <tt>parent</tt> returns <tt>Object</tt>.</p></div>
695
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
696
- <h5 id="module-parents">3.3.3 <tt>parents</tt></h5>
697
- <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>
698
- <div class="code_container">
699
- <pre class="brush: ruby; gutter: false; toolbar: false">
700
- module X
701
- module Y
702
- module Z
703
- end
704
- end
705
- end
706
- M = X::Y::Z
707
-
708
- X::Y::Z.parents # =&gt; [X::Y, X, Object]
709
- M.parents # =&gt; [X::Y, X, Object]
710
- </pre>
711
- </div>
712
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
713
- <h4 id="constants">3.4 Constants</h4>
714
- <p>The method <tt>local_constants</tt> returns the names of the constants that have been defined in the receiver module:</p>
715
- <div class="code_container">
716
- <pre class="brush: ruby; gutter: false; toolbar: false">
717
- module X
718
- X1 = 1
719
- X2 = 2
720
- module Y
721
- Y1 = :y1
722
- X1 = :overrides_X1_above
723
- end
724
- end
725
-
726
- X.local_constants # =&gt; [&quot;X2&quot;, &quot;X1&quot;, &quot;Y&quot;], assumes Ruby 1.8
727
- X::Y.local_constants # =&gt; [&quot;X1&quot;, &quot;Y1&quot;], assumes Ruby 1.8
728
- </pre>
729
- </div>
730
- <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> always returns strings.</p>
731
- <div class="warning"><p>This method returns precise results in Ruby 1.9. In older versions of Ruby, however, it may miss some constants in case the same constant exists in the receiver module as well as in any of its ancestors and both constants point to the same object (objects are compared using <tt>Object#object_id</tt>).</p></div>
732
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/introspection.rb</tt>.</p></div>
733
- <h5 id="qualified-constant-names">3.4.1 Qualified Constant Names</h5>
734
- <p>The standard methods <tt>const_defined?</tt>, <tt>const_get</tt> , and <tt>const_set</tt> accept
735
- bare constant names. Active Support extends this <span class="caps">API</span> to be able to pass
736
- relative qualified constant names.</p>
737
- <p>The new methods are <tt>qualified_const_defined?</tt>, <tt>qualified_const_get</tt>, and
738
- <tt>qualified_const_set</tt>. Their arguments are assumed to be qualified constant
739
- names relative to their receiver:</p>
740
- <div class="code_container">
741
- <pre class="brush: ruby; gutter: false; toolbar: false">
742
- Object.qualified_const_defined?(&quot;Math::PI&quot;) # =&gt; true
743
- Object.qualified_const_get(&quot;Math::PI&quot;) # =&gt; 3.141592653589793
744
- Object.qualified_const_set(&quot;Math::Phi&quot;, 1.618034) # =&gt; 1.618034
745
- </pre>
746
- </div>
747
- <p>Arguments may be bare constant names:</p>
748
- <div class="code_container">
749
- <pre class="brush: ruby; gutter: false; toolbar: false">
750
- Math.qualified_const_get(&quot;E&quot;) # =&gt; 2.718281828459045
751
- </pre>
752
- </div>
753
- <p>These methods are analogous to their builtin counterparts. In particular,
754
- <tt>qualified_constant_defined?</tt> accepts an optional second argument in 1.9
755
- to be able to say whether you want the predicate to look in the ancestors.
756
- This flag is taken into account for each constant in the expression while
757
- walking down the path.</p>
758
- <p>For example, given</p>
759
- <div class="code_container">
760
- <pre class="brush: ruby; gutter: false; toolbar: false">
761
- module M
762
- X = 1
763
- end
764
-
765
- module N
766
- class C
767
- include M
768
- end
769
- end
770
- </pre>
771
- </div>
772
- <p><tt>qualified_const_defined?</tt> behaves this way:</p>
773
- <div class="code_container">
774
- <pre class="brush: ruby; gutter: false; toolbar: false">
775
- N.qualified_const_defined?(&quot;C::X&quot;, false) # =&gt; false (1.9 only)
776
- N.qualified_const_defined?(&quot;C::X&quot;, true) # =&gt; true (1.9 only)
777
- N.qualified_const_defined?(&quot;C::X&quot;) # =&gt; false in 1.8, true in 1.9
778
- </pre>
779
- </div>
780
- <p>As the last example implies, in 1.9 the second argument defaults to true,
781
- as in <tt>const_defined?</tt>.</p>
782
- <p>For coherence with the builtin methods only relative paths are accepted.
783
- Absolute qualified constant names like <tt>::Math::PI</tt> raise <tt>NameError</tt>.</p>
784
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/qualified_const.rb</tt>.</p></div>
785
- <h4 id="synchronization">3.5 Synchronization</h4>
786
- <p>The <tt>synchronize</tt> macro declares a method to be synchronized:</p>
787
- <div class="code_container">
788
- <pre class="brush: ruby; gutter: false; toolbar: false">
789
- class Counter
790
- @@mutex = Mutex.new
791
- attr_reader :value
792
-
793
- def initialize
794
- @value = 0
795
- end
796
-
797
- def incr
798
- @value += 1 # non-atomic
799
- end
800
- synchronize :incr, :with =&gt; '@@mutex'
801
- end
802
- </pre>
803
- </div>
804
- <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>
805
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/synchronization.rb</tt>.</p></div>
806
- <h4 id="reachable">3.6 Reachable</h4>
807
- <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>
808
- <p>That is what ordinarily happens, if a module is called &#8220;M&#8221;, the <tt>M</tt> constant exists and holds it:</p>
809
- <div class="code_container">
810
- <pre class="brush: ruby; gutter: false; toolbar: false">
811
- module M
812
- end
813
-
814
- M.reachable? # =&gt; true
815
- </pre>
816
- </div>
817
- <p>But since constants and modules are indeed kind of decoupled, module objects can become unreachable:</p>
818
- <div class="code_container">
819
- <pre class="brush: ruby; gutter: false; toolbar: false">
820
- module M
821
- end
822
-
823
- orphan = Object.send(:remove_const, :M)
824
-
825
- # The module object is orphan now but it still has a name.
826
- orphan.name # =&gt; &quot;M&quot;
827
-
828
- # You cannot reach it via the constant M because it does not even exist.
829
- orphan.reachable? # =&gt; false
830
-
831
- # Let's define a module called &quot;M&quot; again.
832
- module M
833
- end
834
-
835
- # The constant M exists now again, and it stores a module
836
- # object called &quot;M&quot;, but it is a new instance.
837
- orphan.reachable? # =&gt; false
838
- </pre>
839
- </div>
840
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/reachable.rb</tt>.</p></div>
841
- <h4 id="anonymous">3.7 Anonymous</h4>
842
- <p>A module may or may not have a name:</p>
843
- <div class="code_container">
844
- <pre class="brush: ruby; gutter: false; toolbar: false">
845
- module M
846
- end
847
- M.name # =&gt; &quot;M&quot;
848
-
849
- N = Module.new
850
- N.name # =&gt; &quot;N&quot;
851
-
852
- Module.new.name # =&gt; &quot;&quot; in 1.8, nil in 1.9
853
- </pre>
854
- </div>
855
- <p>You can check whether a module has a name with the predicate <tt>anonymous?</tt>:</p>
856
- <div class="code_container">
857
- <pre class="brush: ruby; gutter: false; toolbar: false">
858
- module M
859
- end
860
- M.anonymous? # =&gt; false
861
-
862
- Module.new.anonymous? # =&gt; true
863
- </pre>
864
- </div>
865
- <p>Note that being unreachable does not imply being anonymous:</p>
866
- <div class="code_container">
867
- <pre class="brush: ruby; gutter: false; toolbar: false">
868
- module M
869
- end
870
-
871
- m = Object.send(:remove_const, :M)
872
-
873
- m.reachable? # =&gt; false
874
- m.anonymous? # =&gt; false
875
- </pre>
876
- </div>
877
- <p>though an anonymous module is unreachable by definition.</p>
878
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/anonymous.rb</tt>.</p></div>
879
- <h4 id="method-delegation">3.8 Method Delegation</h4>
880
- <p>The macro <tt>delegate</tt> offers an easy way to forward methods.</p>
881
- <p>Let&#8217;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>
882
- <div class="code_container">
883
- <pre class="brush: ruby; gutter: false; toolbar: false">
884
- class User &lt; ActiveRecord::Base
885
- has_one :profile
886
- end
887
- </pre>
888
- </div>
889
- <p>With that configuration you get a user&#8217;s name via his profile, <tt>user.profile.name</tt>, but it could be handy to still be able to access such attribute directly:</p>
890
- <div class="code_container">
891
- <pre class="brush: ruby; gutter: false; toolbar: false">
892
- class User &lt; ActiveRecord::Base
893
- has_one :profile
894
-
895
- def name
896
- profile.name
897
- end
898
- end
899
- </pre>
900
- </div>
901
- <p>That is what <tt>delegate</tt> does for you:</p>
902
- <div class="code_container">
903
- <pre class="brush: ruby; gutter: false; toolbar: false">
904
- class User &lt; ActiveRecord::Base
905
- has_one :profile
906
-
907
- delegate :name, :to =&gt; :profile
908
- end
909
- </pre>
910
- </div>
911
- <p>It is shorter, and the intention more obvious.</p>
912
- <p>The method must be public in the target.</p>
913
- <p>The <tt>delegate</tt> macro accepts several methods:</p>
914
- <div class="code_container">
915
- <pre class="brush: ruby; gutter: false; toolbar: false">
916
- delegate :name, :age, :address, :twitter, :to =&gt; :profile
917
- </pre>
918
- </div>
919
- <p>When interpolated into a string, the <tt>:to</tt> option should become an expression that evaluates to the object the method is delegated to. Typically a string or symbol. Such an expression is evaluated in the context of the receiver:</p>
920
- <div class="code_container">
921
- <pre class="brush: ruby; gutter: false; toolbar: false">
922
- # delegates to the Rails constant
923
- delegate :logger, :to =&gt; :Rails
924
-
925
- # delegates to the receiver's class
926
- delegate :table_name, :to =&gt; 'self.class'
927
- </pre>
928
- </div>
929
- <div class="warning"><p>If the <tt>:prefix</tt> option is <tt>true</tt> this is less generic, see below.</p></div>
930
- <p>By default, if the delegation raises <tt>NoMethodError</tt> and the target is <tt>nil</tt> the exception is propagated. You can ask that <tt>nil</tt> is returned instead with the <tt>:allow_nil</tt> option:</p>
931
- <div class="code_container">
932
- <pre class="brush: ruby; gutter: false; toolbar: false">
933
- delegate :name, :to =&gt; :profile, :allow_nil =&gt; true
934
- </pre>
935
- </div>
936
- <p>With <tt>:allow_nil</tt> the call <tt>user.name</tt> returns <tt>nil</tt> if the user has no profile.</p>
937
- <p>The option <tt>:prefix</tt> adds a prefix to the name of the generated method. This may be handy for example to get a better name:</p>
938
- <div class="code_container">
939
- <pre class="brush: ruby; gutter: false; toolbar: false">
940
- delegate :street, :to =&gt; :address, :prefix =&gt; true
941
- </pre>
942
- </div>
943
- <p>The previous example generates <tt>address_street</tt> rather than <tt>street</tt>.</p>
944
- <div class="warning"><p>Since in this case the name of the generated method is composed of the target object and target method names, the <tt>:to</tt> option must be a method name.</p></div>
945
- <p>A custom prefix may also be configured:</p>
946
- <div class="code_container">
947
- <pre class="brush: ruby; gutter: false; toolbar: false">
948
- delegate :size, :to =&gt; :attachment, :prefix =&gt; :avatar
949
- </pre>
950
- </div>
951
- <p>In the previous example the macro generates <tt>avatar_size</tt> rather than <tt>size</tt>.</p>
952
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/delegation.rb</tt></p></div>
953
- <h4 id="method-names">3.9 Method Names</h4>
954
- <p>The builtin methods <tt>instance_methods</tt> and <tt>methods</tt> return method names as strings or symbols depending on the Ruby version. Active Support defines <tt>instance_method_names</tt> and <tt>method_names</tt> to be equivalent to them, respectively, but always getting strings back.</p>
955
- <p>For example, <tt>ActionView::Helpers::FormBuilder</tt> knows this array difference is going to work no matter the Ruby version:</p>
956
- <div class="code_container">
957
- <pre class="brush: ruby; gutter: false; toolbar: false">
958
- self.field_helpers = (FormHelper.instance_method_names - ['form_for'])
959
- </pre>
960
- </div>
961
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/method_names.rb</tt></p></div>
962
- <h4 id="redefining-methods">3.10 Redefining Methods</h4>
963
- <p>There are cases where you need to define a method with <tt>define_method</tt>, but don&#8217;t know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.</p>
964
- <p>The method <tt>redefine_method</tt> prevents such a potential warning, removing the existing method before if needed. Rails uses it in a few places, for instance when it generates an association&#8217;s <span class="caps">API</span>:</p>
965
- <div class="code_container">
966
- <pre class="brush: ruby; gutter: false; toolbar: false">
967
- redefine_method(&quot;#{reflection.name}=&quot;) do |new_value|
968
- association = association_instance_get(reflection.name)
969
-
970
- if association.nil? || association.target != new_value
971
- association = association_proxy_class.new(self, reflection)
972
- end
973
-
974
- association.replace(new_value)
975
- association_instance_set(reflection.name, new_value.nil? ? nil : association)
976
- end
977
- </pre>
978
- </div>
979
- <div class="note"><p>Defined in <tt>active_support/core_ext/module/remove_method.rb</tt></p></div>
980
- <h3 id="extensions-to-class">4 Extensions to <tt>Class</tt></h3>
981
- <h4 id="class-attributes">4.1 Class Attributes</h4>
982
- <h5 id="class_attribute">4.1.1 <tt>class_attribute</tt></h5>
983
- <p>The method <tt>class_attribute</tt> declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.</p>
984
- <div class="code_container">
985
- <pre class="brush: ruby; gutter: false; toolbar: false">
986
- class A
987
- class_attribute :x
988
- end
989
-
990
- class B &lt; A; end
991
-
992
- class C &lt; B; end
993
-
994
- A.x = :a
995
- B.x # =&gt; :a
996
- C.x # =&gt; :a
997
-
998
- B.x = :b
999
- A.x # =&gt; :a
1000
- C.x # =&gt; :b
1001
-
1002
- C.x = :c
1003
- A.x # =&gt; :a
1004
- B.x # =&gt; :b
1005
- </pre>
1006
- </div>
1007
- <p>For example <tt>ActionMailer::Base</tt> defines:</p>
1008
- <div class="code_container">
1009
- <pre class="brush: ruby; gutter: false; toolbar: false">
1010
- class_attribute :default_params
1011
- self.default_params = {
1012
- :mime_version =&gt; &quot;1.0&quot;,
1013
- :charset =&gt; &quot;UTF-8&quot;,
1014
- :content_type =&gt; &quot;text/plain&quot;,
1015
- :parts_order =&gt; [ &quot;text/plain&quot;, &quot;text/enriched&quot;, &quot;text/html&quot; ]
1016
- }.freeze
1017
- </pre>
1018
- </div>
1019
- <p>They can be also accessed and overridden at the instance level.</p>
1020
- <div class="code_container">
1021
- <pre class="brush: ruby; gutter: false; toolbar: false">
1022
- A.x = 1
1023
-
1024
- a1 = A.new
1025
- a2 = A.new
1026
- a2.x = 2
1027
-
1028
- a1.x # =&gt; 1, comes from A
1029
- a2.x # =&gt; 2, overridden in a2
1030
- </pre>
1031
- </div>
1032
- <p>The generation of the writer instance method can be prevented by setting the option <tt>:instance_writer</tt> to <tt>false</tt>.</p>
1033
- <div class="code_container">
1034
- <pre class="brush: ruby; gutter: false; toolbar: false">
1035
- module ActiveRecord
1036
- class Base
1037
- class_attribute :table_name_prefix, :instance_writer =&gt; false
1038
- self.table_name_prefix = &quot;&quot;
1039
- end
1040
- end
1041
- </pre>
1042
- </div>
1043
- <p>A model may find that option useful as a way to prevent mass-assignment from setting the attribute.</p>
1044
- <p>The generation of the reader instance method can be prevented by setting the option <tt>:instance_reader</tt> to <tt>false</tt>.</p>
1045
- <div class="code_container">
1046
- <pre class="brush: ruby; gutter: false; toolbar: false">
1047
- class A
1048
- class_attribute :x, :instance_reader =&gt; false
1049
- end
1050
-
1051
- A.new.x = 1 # NoMethodError
1052
- </pre>
1053
- </div>
1054
- <p>For convenience <tt>class_attribute</tt> also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called <tt>x?</tt>.</p>
1055
- <p>When <tt>:instance_reader</tt> is <tt>false</tt>, the instance predicate returns a <tt>NoMethodError</tt> just like the reader method.</p>
1056
- <div class="note"><p>Defined in <tt>active_support/core_ext/class/attribute.rb</tt></p></div>
1057
- <h5 id="cattr_reader-cattr_writer-and-cattr_accessor">4.1.2 <tt>cattr_reader</tt>, <tt>cattr_writer</tt>, and <tt>cattr_accessor</tt></h5>
1058
- <p>The macros <tt>cattr_reader</tt>, <tt>cattr_writer</tt>, and <tt>cattr_accessor</tt> are analogous to their <tt>attr_*</tt> counterparts but for classes. They initialize a class variable to <tt>nil</tt> unless it already exists, and generate the corresponding class methods to access it:</p>
1059
- <div class="code_container">
1060
- <pre class="brush: ruby; gutter: false; toolbar: false">
1061
- class MysqlAdapter &lt; AbstractAdapter
1062
- # Generates class methods to access @@emulate_booleans.
1063
- cattr_accessor :emulate_booleans
1064
- self.emulate_booleans = true
1065
- end
1066
- </pre>
1067
- </div>
1068
- <p>Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with <tt>class_attribute</tt> (see above). For example given</p>
1069
- <div class="code_container">
1070
- <pre class="brush: ruby; gutter: false; toolbar: false">
1071
- module ActionView
1072
- class Base
1073
- cattr_accessor :field_error_proc
1074
- @@field_error_proc = Proc.new{ ... }
1075
- end
1076
- end
1077
- </pre>
1078
- </div>
1079
- <p>we can access <tt>field_error_proc</tt> in views.</p>
1080
- <p>The generation of the reader instance method can be prevented by setting <tt>:instance_reader</tt> to <tt>false</tt> and the generation of the writer instance method can be prevented by setting <tt>:instance_writer</tt> to <tt>false</tt>. Generation of both methods can be prevented by setting <tt>:instance_accessor</tt> to <tt>false</tt>. In all cases, the value must be exactly <tt>false</tt> and not any false value.</p>
1081
- <div class="code_container">
1082
- <pre class="brush: ruby; gutter: false; toolbar: false">
1083
- module A
1084
- class B
1085
- # No first_name instance reader is generated.
1086
- cattr_accessor :first_name, :instance_reader =&gt; false
1087
- # No last_name= instance writer is generated.
1088
- cattr_accessor :last_name, :instance_writer =&gt; false
1089
- # No surname instance reader or surname= writer is generated.
1090
- cattr_accessor :surname, :instance_accessor =&gt; false
1091
- end
1092
- end
1093
- </pre>
1094
- </div>
1095
- <p>A model may find it useful to set <tt>:instance_accessor</tt> to <tt>false</tt> as a way to prevent mass-assignment from setting the attribute.</p>
1096
- <div class="note"><p>Defined in <tt>active_support/core_ext/class/attribute_accessors.rb</tt>.</p></div>
1097
- <h4 id="class-inheritable-attributes">4.2 Class Inheritable Attributes</h4>
1098
- <div class="warning"><p>Class Inheritable Attributes are deprecated. It&#8217;s recommended that you use <tt>Class#class_attribute</tt> instead.</p></div>
1099
- <p>Class variables are shared down the inheritance tree. Class instance variables are not shared, but they are not inherited either. The macros <tt>class_inheritable_reader</tt>, <tt>class_inheritable_writer</tt>, and <tt>class_inheritable_accessor</tt> provide accessors for class-level data which is inherited but not shared with children:</p>
1100
- <div class="code_container">
1101
- <pre class="brush: ruby; gutter: false; toolbar: false">
1102
- module ActionController
1103
- class Base
1104
- # FIXME: REVISE/SIMPLIFY THIS COMMENT.
1105
- # The value of allow_forgery_protection is inherited,
1106
- # but its value in a particular class does not affect
1107
- # the value in the rest of the controllers hierarchy.
1108
- class_inheritable_accessor :allow_forgery_protection
1109
- end
1110
- end
1111
- </pre>
1112
- </div>
1113
- <p>They accomplish this with class instance variables and cloning on subclassing, there are no class variables involved. Cloning is performed with <tt>dup</tt> as long as the value is duplicable.</p>
1114
- <p>There are some variants specialised in arrays and hashes:</p>
1115
- <div class="code_container">
1116
- <pre class="brush: ruby; gutter: false; toolbar: false">
1117
- class_inheritable_array
1118
- class_inheritable_hash
1119
- </pre>
1120
- </div>
1121
- <p>Those writers take any inherited array or hash into account and extend them rather than overwrite them.</p>
1122
- <p>As with vanilla class attribute accessors these macros create convenience instance methods for reading and writing. The generation of the writer instance method can be prevented setting <tt>:instance_writer</tt> to <tt>false</tt> (not any false value, but exactly <tt>false</tt>):</p>
1123
- <div class="code_container">
1124
- <pre class="brush: ruby; gutter: false; toolbar: false">
1125
- module ActiveRecord
1126
- class Base
1127
- class_inheritable_accessor :default_scoping, :instance_writer =&gt; false
1128
- end
1129
- end
1130
- </pre>
1131
- </div>
1132
- <p>Since values are copied when a subclass is defined, if the base class changes the attribute after that, the subclass does not see the new value. That&#8217;s the point.</p>
1133
- <div class="note"><p>Defined in <tt>active_support/core_ext/class/inheritable_attributes.rb</tt>.</p></div>
1134
- <h4 id="subclasses-descendants">4.3 Subclasses &amp; Descendants</h4>
1135
- <h5 id="subclasses">4.3.1 <tt>subclasses</tt></h5>
1136
- <p>The <tt>subclasses</tt> method returns the subclasses of the receiver:</p>
1137
- <div class="code_container">
1138
- <pre class="brush: ruby; gutter: false; toolbar: false">
1139
- class C; end
1140
- C.subclasses # =&gt; []
1141
-
1142
- class B &lt; C; end
1143
- C.subclasses # =&gt; [B]
1144
-
1145
- class A &lt; B; end
1146
- C.subclasses # =&gt; [B]
1147
-
1148
- class D &lt; C; end
1149
- C.subclasses # =&gt; [B, D]
1150
- </pre>
1151
- </div>
1152
- <p>The order in which these classes are returned is unspecified.</p>
1153
- <div class="warning"><p>This method is redefined in some Rails core classes but should be all compatible in Rails 3.1.</p></div>
1154
- <div class="note"><p>Defined in <tt>active_support/core_ext/class/subclasses.rb</tt>.</p></div>
1155
- <h5 id="descendants">4.3.2 <tt>descendants</tt></h5>
1156
- <p>The <tt>descendants</tt> method returns all classes that are <tt>&lt;</tt> than its receiver:</p>
1157
- <div class="code_container">
1158
- <pre class="brush: ruby; gutter: false; toolbar: false">
1159
- class C; end
1160
- C.descendants # =&gt; []
1161
-
1162
- class B &lt; C; end
1163
- C.descendants # =&gt; [B]
1164
-
1165
- class A &lt; B; end
1166
- C.descendants # =&gt; [B, A]
1167
-
1168
- class D &lt; C; end
1169
- C.descendants # =&gt; [B, A, D]
1170
- </pre>
1171
- </div>
1172
- <p>The order in which these classes are returned is unspecified.</p>
1173
- <div class="note"><p>Defined in <tt>active_support/core_ext/class/subclasses.rb</tt>.</p></div>
1174
- <h3 id="extensions-to-string">5 Extensions to <tt>String</tt></h3>
1175
- <h4 id="output-safety">5.1 Output Safety</h4>
1176
- <h5 id="motivation">5.1.1 Motivation</h5>
1177
- <p>Inserting data into <span class="caps">HTML</span> templates needs extra care. For example you can&#8217;t just interpolate <tt>@review.title</tt> verbatim into an <span class="caps">HTML</span> page. On one hand if the review title is &#8220;Flanagan &amp; Matz rules!&#8221; the output won&#8217;t be well-formed because an ampersand has to be escaped as &#8220;&amp;amp;&#8221;. On the other hand, depending on the application that may be a big security hole because users can inject malicious <span class="caps">HTML</span> setting a hand-crafted review title. Check out the <a href="security.html#cross-site-scripting-xss">section about cross-site scripting in the Security guide</a> for further information about the risks.</p>
1178
- <h5 id="safe-strings">5.1.2 Safe Strings</h5>
1179
- <p>Active Support has the concept of <i>(html) safe</i> strings since Rails 3. A safe string is one that is marked as being insertable into <span class="caps">HTML</span> as is. It is trusted, no matter whether it has been escaped or not.</p>
1180
- <p>Strings are considered to be <i>unsafe</i> by default:</p>
1181
- <div class="code_container">
1182
- <pre class="brush: ruby; gutter: false; toolbar: false">
1183
- &quot;&quot;.html_safe? # =&gt; false
1184
- </pre>
1185
- </div>
1186
- <p>You can obtain a safe string from a given one with the <tt>html_safe</tt> method:</p>
1187
- <div class="code_container">
1188
- <pre class="brush: ruby; gutter: false; toolbar: false">
1189
- s = &quot;&quot;.html_safe
1190
- s.html_safe? # =&gt; true
1191
- </pre>
1192
- </div>
1193
- <p>It is important to understand that <tt>html_safe</tt> performs no escaping whatsoever, it is just an assertion:</p>
1194
- <div class="code_container">
1195
- <pre class="brush: ruby; gutter: false; toolbar: false">
1196
- s = &quot;&lt;script&gt;...&lt;/script&gt;&quot;.html_safe
1197
- s.html_safe? # =&gt; true
1198
- s # =&gt; &quot;&lt;script&gt;...&lt;/script&gt;&quot;
1199
- </pre>
1200
- </div>
1201
- <p>It is your responsibility to ensure calling <tt>html_safe</tt> on a particular string is fine.</p>
1202
- <p>If you append onto a safe string, either in-place with <tt>concat</tt>/<tt>&lt;&lt;</tt>, or with <tt>+</tt>, the result is a safe string. Unsafe arguments are escaped:</p>
1203
- <div class="code_container">
1204
- <pre class="brush: ruby; gutter: false; toolbar: false">
1205
- &quot;&quot;.html_safe + &quot;&lt;&quot; # =&gt; &quot;&amp;lt;&quot;
1206
- </pre>
1207
- </div>
1208
- <p>Safe arguments are directly appended:</p>
1209
- <div class="code_container">
1210
- <pre class="brush: ruby; gutter: false; toolbar: false">
1211
- &quot;&quot;.html_safe + &quot;&lt;&quot;.html_safe # =&gt; &quot;&lt;&quot;
1212
- </pre>
1213
- </div>
1214
- <p>These methods should not be used in ordinary views. In Rails 3 unsafe values are automatically escaped:</p>
1215
- <div class="code_container">
1216
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
1217
- &lt;%= @review.title %&gt; &lt;%# fine in Rails 3, escaped if needed %&gt;
1218
- </pre>
1219
- </div>
1220
- <p>To insert something verbatim use the <tt>raw</tt> helper rather than calling <tt>html_safe</tt>:</p>
1221
- <div class="code_container">
1222
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
1223
- &lt;%= raw @cms.current_template %&gt; &lt;%# inserts @cms.current_template as is %&gt;
1224
- </pre>
1225
- </div>
1226
- <p>or, equivalently, use <tt>&lt;%==</tt>:</p>
1227
- <div class="code_container">
1228
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
1229
- &lt;%== @cms.current_template %&gt; &lt;%# inserts @cms.current_template as is %&gt;
1230
- </pre>
1231
- </div>
1232
- <p>The <tt>raw</tt> helper calls <tt>html_safe</tt> for you:</p>
1233
- <div class="code_container">
1234
- <pre class="brush: ruby; gutter: false; toolbar: false">
1235
- def raw(stringish)
1236
- stringish.to_s.html_safe
1237
- end
1238
- </pre>
1239
- </div>
1240
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/output_safety.rb</tt>.</p></div>
1241
- <h5 id="transformation">5.1.3 Transformation</h5>
1242
- <p>As a rule of thumb, except perhaps for concatenation as explained above, any method that may change a string gives you an unsafe string. These are <tt>donwcase</tt>, <tt>gsub</tt>, <tt>strip</tt>, <tt>chomp</tt>, <tt>underscore</tt>, etc.</p>
1243
- <p>In the case of in-place transformations like <tt>gsub!</tt> the receiver itself becomes unsafe.</p>
1244
- <div class="info"><p>The safety bit is lost always, no matter whether the transformation actually changed something.</p></div>
1245
- <h5 id="conversion-and-coercion">5.1.4 Conversion and Coercion</h5>
1246
- <p>Calling <tt>to_s</tt> on a safe string returns a safe string, but coercion with <tt>to_str</tt> returns an unsafe string.</p>
1247
- <h5 id="copying">5.1.5 Copying</h5>
1248
- <p>Calling <tt>dup</tt> or <tt>clone</tt> on safe strings yields safe strings.</p>
1249
- <h4 id="squish">5.2 <tt>squish</tt></h4>
1250
- <p>The method <tt>squish</tt> strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:</p>
1251
- <div class="code_container">
1252
- <pre class="brush: ruby; gutter: false; toolbar: false">
1253
- &quot; \n foo\n\r \t bar \n&quot;.squish # =&gt; &quot;foo bar&quot;
1254
- </pre>
1255
- </div>
1256
- <p>There&#8217;s also the destructive version <tt>String#squish!</tt>.</p>
1257
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/filters.rb</tt>.</p></div>
1258
- <h4 id="truncate">5.3 <tt>truncate</tt></h4>
1259
- <p>The method <tt>truncate</tt> returns a copy of its receiver truncated after a given <tt>length</tt>:</p>
1260
- <div class="code_container">
1261
- <pre class="brush: ruby; gutter: false; toolbar: false">
1262
- &quot;Oh dear! Oh dear! I shall be late!&quot;.truncate(20)
1263
- # =&gt; &quot;Oh dear! Oh dear!...&quot;
1264
- </pre>
1265
- </div>
1266
- <p>Ellipsis can be customized with the <tt>:omission</tt> option:</p>
1267
- <div class="code_container">
1268
- <pre class="brush: ruby; gutter: false; toolbar: false">
1269
- &quot;Oh dear! Oh dear! I shall be late!&quot;.truncate(20, :omission =&gt; '&amp;hellip;')
1270
- # =&gt; &quot;Oh dear! Oh &amp;hellip;&quot;
1271
- </pre>
1272
- </div>
1273
- <p>Note in particular that truncation takes into account the length of the omission string.</p>
1274
- <p>Pass a <tt>:separator</tt> to truncate the string at a natural break:</p>
1275
- <div class="code_container">
1276
- <pre class="brush: ruby; gutter: false; toolbar: false">
1277
- &quot;Oh dear! Oh dear! I shall be late!&quot;.truncate(18)
1278
- # =&gt; &quot;Oh dear! Oh dea...&quot;
1279
- &quot;Oh dear! Oh dear! I shall be late!&quot;.truncate(18, :separator =&gt; ' ')
1280
- # =&gt; &quot;Oh dear! Oh...&quot;
1281
- </pre>
1282
- </div>
1283
- <p>In the above example &#8220;dear&#8221; gets cut first, but then <tt>:separator</tt> prevents it.</p>
1284
- <div class="warning"><p>The option <tt>:separator</tt> can&#8217;t be a regexp.</p></div>
1285
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/filters.rb</tt>.</p></div>
1286
- <h4 id="inquiry">5.4 <tt>inquiry</tt></h4>
1287
- <p>The <tt>inquiry</tt> method converts a string into a <tt>StringInquirer</tt> object making equality checks prettier.</p>
1288
- <div class="code_container">
1289
- <pre class="brush: ruby; gutter: false; toolbar: false">
1290
- &quot;production&quot;.inquiry.production? # =&gt; true
1291
- &quot;active&quot;.inquiry.inactive? # =&gt; false
1292
- </pre>
1293
- </div>
1294
- <h4 id="key-based-interpolation">5.5 Key-based Interpolation</h4>
1295
- <p>In Ruby 1.9 the <tt>%</tt> string operator supports key-based interpolation, both formatted and unformatted:</p>
1296
- <div class="code_container">
1297
- <pre class="brush: ruby; gutter: false; toolbar: false">
1298
- &quot;Total is %&lt;total&gt;.02f&quot; % {:total =&gt; 43.1} # =&gt; Total is 43.10
1299
- &quot;I say %{foo}&quot; % {:foo =&gt; &quot;wadus&quot;} # =&gt; &quot;I say wadus&quot;
1300
- &quot;I say %{woo}&quot; % {:foo =&gt; &quot;wadus&quot;} # =&gt; KeyError
1301
- </pre>
1302
- </div>
1303
- <p>Active Support adds that functionality to <tt>%</tt> in previous versions of Ruby.</p>
1304
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/interpolation.rb</tt>.</p></div>
1305
- <h4 id="starts_with-and-ends_with">5.6 <tt>starts_with?</tt> and <tt>ends_with?</tt></h4>
1306
- <p>Active Support defines 3rd person aliases of <tt>String#start_with?</tt> and <tt>String#end_with?</tt>:</p>
1307
- <div class="code_container">
1308
- <pre class="brush: ruby; gutter: false; toolbar: false">
1309
- &quot;foo&quot;.starts_with?(&quot;f&quot;) # =&gt; true
1310
- &quot;foo&quot;.ends_with?(&quot;o&quot;) # =&gt; true
1311
- </pre>
1312
- </div>
1313
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/starts_ends_with.rb</tt>.</p></div>
1314
- <h4 id="strip_heredoc">5.7 <tt>strip_heredoc</tt></h4>
1315
- <p>The method <tt>strip_heredoc</tt> strips indentation in heredocs.</p>
1316
- <p>For example in</p>
1317
- <div class="code_container">
1318
- <pre class="brush: ruby; gutter: false; toolbar: false">
1319
- if options[:usage]
1320
- puts &lt;&lt;-USAGE.strip_heredoc
1321
- This command does such and such.
1322
-
1323
- Supported options are:
1324
- -h This message
1325
- ...
1326
- USAGE
1327
- end
1328
- </pre>
1329
- </div>
1330
- <p>the user would see the usage message aligned against the left margin.</p>
1331
- <p>Technically, it looks for the least indented line in the whole string, and removes
1332
- that amount of leading whitespace.</p>
1333
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/strip.rb</tt>.</p></div>
1334
- <h4 id="access">5.8 Access</h4>
1335
- <h5 id="at-position">5.8.1 <tt>at(position)</tt></h5>
1336
- <p>Returns the character of the string at position <tt>position</tt>:</p>
1337
- <div class="code_container">
1338
- <pre class="brush: ruby; gutter: false; toolbar: false">
1339
- &quot;hello&quot;.at(0) # =&gt; &quot;h&quot;
1340
- &quot;hello&quot;.at(4) # =&gt; &quot;o&quot;
1341
- &quot;hello&quot;.at(-1) # =&gt; &quot;o&quot;
1342
- &quot;hello&quot;.at(10) # =&gt; ERROR if &lt; 1.9, nil in 1.9
1343
- </pre>
1344
- </div>
1345
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
1346
- <h5 id="from-position">5.8.2 <tt>from(position)</tt></h5>
1347
- <p>Returns the substring of the string starting at position <tt>position</tt>:</p>
1348
- <div class="code_container">
1349
- <pre class="brush: ruby; gutter: false; toolbar: false">
1350
- &quot;hello&quot;.from(0) # =&gt; &quot;hello&quot;
1351
- &quot;hello&quot;.from(2) # =&gt; &quot;llo&quot;
1352
- &quot;hello&quot;.from(-2) # =&gt; &quot;lo&quot;
1353
- &quot;hello&quot;.from(10) # =&gt; &quot;&quot; if &lt; 1.9, nil in 1.9
1354
- </pre>
1355
- </div>
1356
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
1357
- <h5 id="to-position">5.8.3 <tt>to(position)</tt></h5>
1358
- <p>Returns the substring of the string up to position <tt>position</tt>:</p>
1359
- <div class="code_container">
1360
- <pre class="brush: ruby; gutter: false; toolbar: false">
1361
- &quot;hello&quot;.to(0) # =&gt; &quot;h&quot;
1362
- &quot;hello&quot;.to(2) # =&gt; &quot;hel&quot;
1363
- &quot;hello&quot;.to(-2) # =&gt; &quot;hell&quot;
1364
- &quot;hello&quot;.to(10) # =&gt; &quot;hello&quot;
1365
- </pre>
1366
- </div>
1367
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
1368
- <h5 id="first-limit-1">5.8.4 <tt>first(limit = 1)</tt></h5>
1369
- <p>The call <tt>str.first(n)</tt> is equivalent to <tt>str.to(n-1)</tt> if <tt>n</tt> &gt; 0, and returns an empty string for <tt>n</tt> == 0.</p>
1370
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
1371
- <h5 id="last-limit-1">5.8.5 <tt>last(limit = 1)</tt></h5>
1372
- <p>The call <tt>str.last(n)</tt> is equivalent to <tt>str.from(-n)</tt> if <tt>n</tt> &gt; 0, and returns an empty string for <tt>n</tt> == 0.</p>
1373
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/access.rb</tt>.</p></div>
1374
- <h4 id="inflections">5.9 Inflections</h4>
1375
- <h5 id="pluralize">5.9.1 <tt>pluralize</tt></h5>
1376
- <p>The method <tt>pluralize</tt> returns the plural of its receiver:</p>
1377
- <div class="code_container">
1378
- <pre class="brush: ruby; gutter: false; toolbar: false">
1379
- &quot;table&quot;.pluralize # =&gt; &quot;tables&quot;
1380
- &quot;ruby&quot;.pluralize # =&gt; &quot;rubies&quot;
1381
- &quot;equipment&quot;.pluralize # =&gt; &quot;equipment&quot;
1382
- </pre>
1383
- </div>
1384
- <p>As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in <tt>config/initializers/inflections.rb</tt>. That file is generated by the <tt>rails</tt> command and has instructions in comments.</p>
1385
- <p><tt>pluralize</tt> can also take an optional <tt>count</tt> parameter. If <tt>count == 1</tt> the singular form will be returned. For any other value of <tt>count</tt> the plural form will be returned:</p>
1386
- <div class="code_container">
1387
- <pre class="brush: ruby; gutter: false; toolbar: false">
1388
- &quot;dude&quot;.pluralize(0) # =&gt; &quot;dudes&quot;
1389
- &quot;dude&quot;.pluralize(1) # =&gt; &quot;dude&quot;
1390
- &quot;dude&quot;.pluralize(2) # =&gt; &quot;dudes&quot;
1391
- </pre>
1392
- </div>
1393
- <p>Active Record uses this method to compute the default table name that corresponds to a model:</p>
1394
- <div class="code_container">
1395
- <pre class="brush: ruby; gutter: false; toolbar: false">
1396
- # active_record/base.rb
1397
- def undecorated_table_name(class_name = base_class.name)
1398
- table_name = class_name.to_s.demodulize.underscore
1399
- table_name = table_name.pluralize if pluralize_table_names
1400
- table_name
1401
- end
1402
- </pre>
1403
- </div>
1404
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1405
- <h5 id="singularize">5.9.2 <tt>singularize</tt></h5>
1406
- <p>The inverse of <tt>pluralize</tt>:</p>
1407
- <div class="code_container">
1408
- <pre class="brush: ruby; gutter: false; toolbar: false">
1409
- &quot;tables&quot;.singularize # =&gt; &quot;table&quot;
1410
- &quot;rubies&quot;.singularize # =&gt; &quot;ruby&quot;
1411
- &quot;equipment&quot;.singularize # =&gt; &quot;equipment&quot;
1412
- </pre>
1413
- </div>
1414
- <p>Associations compute the name of the corresponding default associated class using this method:</p>
1415
- <div class="code_container">
1416
- <pre class="brush: ruby; gutter: false; toolbar: false">
1417
- # active_record/reflection.rb
1418
- def derive_class_name
1419
- class_name = name.to_s.camelize
1420
- class_name = class_name.singularize if collection?
1421
- class_name
1422
- end
1423
- </pre>
1424
- </div>
1425
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1426
- <h5 id="camelize">5.9.3 <tt>camelize</tt></h5>
1427
- <p>The method <tt>camelize</tt> returns its receiver in camel case:</p>
1428
- <div class="code_container">
1429
- <pre class="brush: ruby; gutter: false; toolbar: false">
1430
- &quot;product&quot;.camelize # =&gt; &quot;Product&quot;
1431
- &quot;admin_user&quot;.camelize # =&gt; &quot;AdminUser&quot;
1432
- </pre>
1433
- </div>
1434
- <p>As a rule of thumb you can think of this method as the one that transforms paths into Ruby class or module names, where slashes separate namespaces:</p>
1435
- <div class="code_container">
1436
- <pre class="brush: ruby; gutter: false; toolbar: false">
1437
- &quot;backoffice/session&quot;.camelize # =&gt; &quot;Backoffice::Session&quot;
1438
- </pre>
1439
- </div>
1440
- <p>For example, Action Pack uses this method to load the class that provides a certain session store:</p>
1441
- <div class="code_container">
1442
- <pre class="brush: ruby; gutter: false; toolbar: false">
1443
- # action_controller/metal/session_management.rb
1444
- def session_store=(store)
1445
- if store == :active_record_store
1446
- self.session_store = ActiveRecord::SessionStore
1447
- else
1448
- @@session_store = store.is_a?(Symbol) ?
1449
- ActionDispatch::Session.const_get(store.to_s.camelize) :
1450
- store
1451
- end
1452
- end
1453
- </pre>
1454
- </div>
1455
- <p><tt>camelize</tt> accepts an optional argument, it can be <tt>:upper</tt> (default), or <tt>:lower</tt>. With the latter the first letter becomes lowercase:</p>
1456
- <div class="code_container">
1457
- <pre class="brush: ruby; gutter: false; toolbar: false">
1458
- &quot;visual_effect&quot;.camelize(:lower) # =&gt; &quot;visualEffect&quot;
1459
- </pre>
1460
- </div>
1461
- <p>That may be handy to compute method names in a language that follows that convention, for example JavaScript.</p>
1462
- <div class="info"><p>As a rule of thumb you can think of <tt>camelize</tt> as the inverse of <tt>underscore</tt>, though there are cases where that does not hold: <tt>&#8220;SSLError&#8221;.underscore.camelize</tt> gives back <tt>&#8220;SslError&#8221;</tt>. To support cases such as this, Active Support allows you to specify acronyms in <tt>config/initializers/inflections.rb</tt>:</p></div>
1463
- <div class="code_container">
1464
- <pre class="brush: ruby; gutter: false; toolbar: false">
1465
- ActiveSupport::Inflector.inflections do |inflect|
1466
- inflect.acronym 'SSL'
1467
- end
1468
-
1469
- &quot;SSLError&quot;.underscore.camelize #=&gt; &quot;SSLError&quot;
1470
- </pre>
1471
- </div>
1472
- <p><tt>camelize</tt> is aliased to <tt>camelcase</tt>.</p>
1473
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1474
- <h5 id="underscore">5.9.4 <tt>underscore</tt></h5>
1475
- <p>The method <tt>underscore</tt> goes the other way around, from camel case to paths:</p>
1476
- <div class="code_container">
1477
- <pre class="brush: ruby; gutter: false; toolbar: false">
1478
- &quot;Product&quot;.underscore # =&gt; &quot;product&quot;
1479
- &quot;AdminUser&quot;.underscore # =&gt; &quot;admin_user&quot;
1480
- </pre>
1481
- </div>
1482
- <p>Also converts &#8220;::&#8221; back to &#8220;/&#8221;:</p>
1483
- <div class="code_container">
1484
- <pre class="brush: ruby; gutter: false; toolbar: false">
1485
- &quot;Backoffice::Session&quot;.underscore # =&gt; &quot;backoffice/session&quot;
1486
- </pre>
1487
- </div>
1488
- <p>and understands strings that start with lowercase:</p>
1489
- <div class="code_container">
1490
- <pre class="brush: ruby; gutter: false; toolbar: false">
1491
- &quot;visualEffect&quot;.underscore # =&gt; &quot;visual_effect&quot;
1492
- </pre>
1493
- </div>
1494
- <p><tt>underscore</tt> accepts no argument though.</p>
1495
- <p>Rails class and module autoloading uses <tt>underscore</tt> to infer the relative path without extension of a file that would define a given missing constant:</p>
1496
- <div class="code_container">
1497
- <pre class="brush: ruby; gutter: false; toolbar: false">
1498
- # active_support/dependencies.rb
1499
- def load_missing_constant(from_mod, const_name)
1500
- ...
1501
- qualified_name = qualified_name_for from_mod, const_name
1502
- path_suffix = qualified_name.underscore
1503
- ...
1504
- end
1505
- </pre>
1506
- </div>
1507
- <div class="info"><p>As a rule of thumb you can think of <tt>underscore</tt> as the inverse of <tt>camelize</tt>, though there are cases where that does not hold. For example, <tt>&#8220;SSLError&#8221;.underscore.camelize</tt> gives back <tt>&#8220;SslError&#8221;</tt>.</p></div>
1508
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1509
- <h5 id="titleize">5.9.5 <tt>titleize</tt></h5>
1510
- <p>The method <tt>titleize</tt> capitalizes the words in the receiver:</p>
1511
- <div class="code_container">
1512
- <pre class="brush: ruby; gutter: false; toolbar: false">
1513
- &quot;alice in wonderland&quot;.titleize # =&gt; &quot;Alice In Wonderland&quot;
1514
- &quot;fermat's enigma&quot;.titleize # =&gt; &quot;Fermat's Enigma&quot;
1515
- </pre>
1516
- </div>
1517
- <p><tt>titleize</tt> is aliased to <tt>titlecase</tt>.</p>
1518
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1519
- <h5 id="dasherize">5.9.6 <tt>dasherize</tt></h5>
1520
- <p>The method <tt>dasherize</tt> replaces the underscores in the receiver with dashes:</p>
1521
- <div class="code_container">
1522
- <pre class="brush: ruby; gutter: false; toolbar: false">
1523
- &quot;name&quot;.dasherize # =&gt; &quot;name&quot;
1524
- &quot;contact_data&quot;.dasherize # =&gt; &quot;contact-data&quot;
1525
- </pre>
1526
- </div>
1527
- <p>The <span class="caps">XML</span> serializer of models uses this method to dasherize node names:</p>
1528
- <div class="code_container">
1529
- <pre class="brush: ruby; gutter: false; toolbar: false">
1530
- # active_model/serializers/xml.rb
1531
- def reformat_name(name)
1532
- name = name.camelize if camelize?
1533
- dasherize? ? name.dasherize : name
1534
- end
1535
- </pre>
1536
- </div>
1537
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1538
- <h5 id="demodulize">5.9.7 <tt>demodulize</tt></h5>
1539
- <p>Given a string with a qualified constant name, <tt>demodulize</tt> returns the very constant name, that is, the rightmost part of it:</p>
1540
- <div class="code_container">
1541
- <pre class="brush: ruby; gutter: false; toolbar: false">
1542
- &quot;Product&quot;.demodulize # =&gt; &quot;Product&quot;
1543
- &quot;Backoffice::UsersController&quot;.demodulize # =&gt; &quot;UsersController&quot;
1544
- &quot;Admin::Hotel::ReservationUtils&quot;.demodulize # =&gt; &quot;ReservationUtils&quot;
1545
- </pre>
1546
- </div>
1547
- <p>Active Record for example uses this method to compute the name of a counter cache column:</p>
1548
- <div class="code_container">
1549
- <pre class="brush: ruby; gutter: false; toolbar: false">
1550
- # active_record/reflection.rb
1551
- def counter_cache_column
1552
- if options[:counter_cache] == true
1553
- &quot;#{active_record.name.demodulize.underscore.pluralize}_count&quot;
1554
- elsif options[:counter_cache]
1555
- options[:counter_cache]
1556
- end
1557
- end
1558
- </pre>
1559
- </div>
1560
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1561
- <h5 id="deconstantize">5.9.8 <tt>deconstantize</tt></h5>
1562
- <p>Given a string with a qualified constant reference expression, <tt>deconstantize</tt> removes the rightmost segment, generally leaving the name of the constant&#8217;s container:</p>
1563
- <div class="code_container">
1564
- <pre class="brush: ruby; gutter: false; toolbar: false">
1565
- &quot;Product&quot;.deconstantize # =&gt; &quot;&quot;
1566
- &quot;Backoffice::UsersController&quot;.deconstantize # =&gt; &quot;Backoffice&quot;
1567
- &quot;Admin::Hotel::ReservationUtils&quot;.deconstantize # =&gt; &quot;Admin::Hotel&quot;
1568
- </pre>
1569
- </div>
1570
- <p>Active Support for example uses this method in <tt>Module#qualified_const_set</tt>:</p>
1571
- <div class="code_container">
1572
- <pre class="brush: ruby; gutter: false; toolbar: false">
1573
- def qualified_const_set(path, value)
1574
- QualifiedConstUtils.raise_if_absolute(path)
1575
-
1576
- const_name = path.demodulize
1577
- mod_name = path.deconstantize
1578
- mod = mod_name.empty? ? self : qualified_const_get(mod_name)
1579
- mod.const_set(const_name, value)
1580
- end
1581
- </pre>
1582
- </div>
1583
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1584
- <h5 id="parameterize">5.9.9 <tt>parameterize</tt></h5>
1585
- <p>The method <tt>parameterize</tt> normalizes its receiver in a way that can be used in pretty URLs.</p>
1586
- <div class="code_container">
1587
- <pre class="brush: ruby; gutter: false; toolbar: false">
1588
- &quot;John Smith&quot;.parameterize # =&gt; &quot;john-smith&quot;
1589
- &quot;Kurt Gödel&quot;.parameterize # =&gt; &quot;kurt-godel&quot;
1590
- </pre>
1591
- </div>
1592
- <p>In fact, the result string is wrapped in an instance of <tt>ActiveSupport::Multibyte::Chars</tt>.</p>
1593
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1594
- <h5 id="tableize">5.9.10 <tt>tableize</tt></h5>
1595
- <p>The method <tt>tableize</tt> is <tt>underscore</tt> followed by <tt>pluralize</tt>.</p>
1596
- <div class="code_container">
1597
- <pre class="brush: ruby; gutter: false; toolbar: false">
1598
- &quot;Person&quot;.tableize # =&gt; &quot;people&quot;
1599
- &quot;Invoice&quot;.tableize # =&gt; &quot;invoices&quot;
1600
- &quot;InvoiceLine&quot;.tableize # =&gt; &quot;invoice_lines&quot;
1601
- </pre>
1602
- </div>
1603
- <p>As a rule of thumb, <tt>tableize</tt> returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight <tt>tableize</tt> indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.</p>
1604
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1605
- <h5 id="classify">5.9.11 <tt>classify</tt></h5>
1606
- <p>The method <tt>classify</tt> is the inverse of <tt>tableize</tt>. It gives you the class name corresponding to a table name:</p>
1607
- <div class="code_container">
1608
- <pre class="brush: ruby; gutter: false; toolbar: false">
1609
- &quot;people&quot;.classify # =&gt; &quot;Person&quot;
1610
- &quot;invoices&quot;.classify # =&gt; &quot;Invoice&quot;
1611
- &quot;invoice_lines&quot;.classify # =&gt; &quot;InvoiceLine&quot;
1612
- </pre>
1613
- </div>
1614
- <p>The method understands qualified table names:</p>
1615
- <div class="code_container">
1616
- <pre class="brush: ruby; gutter: false; toolbar: false">
1617
- &quot;highrise_production.companies&quot;.classify # =&gt; &quot;Company&quot;
1618
- </pre>
1619
- </div>
1620
- <p>Note that <tt>classify</tt> returns a class name as a string. You can get the actual class object invoking <tt>constantize</tt> on it, explained next.</p>
1621
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1622
- <h5 id="constantize">5.9.12 <tt>constantize</tt></h5>
1623
- <p>The method <tt>constantize</tt> resolves the constant reference expression in its receiver:</p>
1624
- <div class="code_container">
1625
- <pre class="brush: ruby; gutter: false; toolbar: false">
1626
- &quot;Fixnum&quot;.constantize # =&gt; Fixnum
1627
-
1628
- module M
1629
- X = 1
1630
- end
1631
- &quot;M::X&quot;.constantize # =&gt; 1
1632
- </pre>
1633
- </div>
1634
- <p>If the string evaluates to no known constant, or its content is not even a valid constant name, <tt>constantize</tt> raises <tt>NameError</tt>.</p>
1635
- <p>Constant name resolution by <tt>constantize</tt> starts always at the top-level <tt>Object</tt> even if there is no leading &#8220;::&#8221;.</p>
1636
- <div class="code_container">
1637
- <pre class="brush: ruby; gutter: false; toolbar: false">
1638
- X = :in_Object
1639
- module M
1640
- X = :in_M
1641
-
1642
- X # =&gt; :in_M
1643
- &quot;::X&quot;.constantize # =&gt; :in_Object
1644
- &quot;X&quot;.constantize # =&gt; :in_Object (!)
1645
- end
1646
- </pre>
1647
- </div>
1648
- <p>So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.</p>
1649
- <p>Mailer test cases obtain the mailer being tested from the name of the test class using <tt>constantize</tt>:</p>
1650
- <div class="code_container">
1651
- <pre class="brush: ruby; gutter: false; toolbar: false">
1652
- # action_mailer/test_case.rb
1653
- def determine_default_mailer(name)
1654
- name.sub(/Test$/, '').constantize
1655
- rescue NameError =&gt; e
1656
- raise NonInferrableMailerError.new(name)
1657
- end
1658
- </pre>
1659
- </div>
1660
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1661
- <h5 id="humanize">5.9.13 <tt>humanize</tt></h5>
1662
- <p>The method <tt>humanize</tt> gives you a sensible name for display out of an attribute name. To do so it replaces underscores with spaces, removes any &#8220;_id&#8221; suffix, and capitalizes the first word:</p>
1663
- <div class="code_container">
1664
- <pre class="brush: ruby; gutter: false; toolbar: false">
1665
- &quot;name&quot;.humanize # =&gt; &quot;Name&quot;
1666
- &quot;author_id&quot;.humanize # =&gt; &quot;Author&quot;
1667
- &quot;comments_count&quot;.humanize # =&gt; &quot;Comments count&quot;
1668
- </pre>
1669
- </div>
1670
- <p>The helper method <tt>full_messages</tt> uses <tt>humanize</tt> as a fallback to include attribute names:</p>
1671
- <div class="code_container">
1672
- <pre class="brush: ruby; gutter: false; toolbar: false">
1673
- def full_messages
1674
- full_messages = []
1675
-
1676
- each do |attribute, messages|
1677
- ...
1678
- attr_name = attribute.to_s.gsub('.', '_').humanize
1679
- attr_name = @base.class.human_attribute_name(attribute, :default =&gt; attr_name)
1680
- ...
1681
- end
1682
-
1683
- full_messages
1684
- end
1685
- </pre>
1686
- </div>
1687
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1688
- <h5 id="foreign_key">5.9.14 <tt>foreign_key</tt></h5>
1689
- <p>The method <tt>foreign_key</tt> gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds &#8220;_id&#8221;:</p>
1690
- <div class="code_container">
1691
- <pre class="brush: ruby; gutter: false; toolbar: false">
1692
- &quot;User&quot;.foreign_key # =&gt; &quot;user_id&quot;
1693
- &quot;InvoiceLine&quot;.foreign_key # =&gt; &quot;invoice_line_id&quot;
1694
- &quot;Admin::Session&quot;.foreign_key # =&gt; &quot;session_id&quot;
1695
- </pre>
1696
- </div>
1697
- <p>Pass a false argument if you do not want the underscore in &#8220;_id&#8221;:</p>
1698
- <div class="code_container">
1699
- <pre class="brush: ruby; gutter: false; toolbar: false">
1700
- &quot;User&quot;.foreign_key(false) # =&gt; &quot;userid&quot;
1701
- </pre>
1702
- </div>
1703
- <p>Associations use this method to infer foreign keys, for example <tt>has_one</tt> and <tt>has_many</tt> do this:</p>
1704
- <div class="code_container">
1705
- <pre class="brush: ruby; gutter: false; toolbar: false">
1706
- # active_record/associations.rb
1707
- foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
1708
- </pre>
1709
- </div>
1710
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/inflections.rb</tt>.</p></div>
1711
- <h4 id="string-conversions">5.10 Conversions</h4>
1712
- <h5 id="ord">5.10.1 <tt>ord</tt></h5>
1713
- <p>Ruby 1.9 defines <tt>ord</tt> to be the codepoint of the first character of the receiver. Active Support backports <tt>ord</tt> for single-byte encodings like <span class="caps">ASCII</span> or <span class="caps">ISO</span>-8859-1 in Ruby 1.8:</p>
1714
- <div class="code_container">
1715
- <pre class="brush: ruby; gutter: false; toolbar: false">
1716
- &quot;a&quot;.ord # =&gt; 97
1717
- &quot;à&quot;.ord # =&gt; 224, in ISO-8859-1
1718
- </pre>
1719
- </div>
1720
- <p>In Ruby 1.8 <tt>ord</tt> doesn&#8217;t work in general in UTF8 strings, use the multibyte support in Active Support for that:</p>
1721
- <div class="code_container">
1722
- <pre class="brush: ruby; gutter: false; toolbar: false">
1723
- &quot;a&quot;.mb_chars.ord # =&gt; 97
1724
- &quot;à&quot;.mb_chars.ord # =&gt; 224, in UTF8
1725
- </pre>
1726
- </div>
1727
- <p>Note that the 224 is different in both examples. In <span class="caps">ISO</span>-8859-1 &#8220;à&#8221; is represented as a single byte, 224. Its single-character representation in UTF8 has two bytes, namely 195 and 160, but its Unicode codepoint is 224. If we call <tt>ord</tt> on the UTF8 string &#8220;à&#8221; the return value will be 195 in Ruby 1.8. That is not an error, because UTF8 is unsupported, the call itself would be bogus.</p>
1728
- <div class="info"><p><tt>ord</tt> is equivalent to <tt>getbyte(0)</tt>.</p></div>
1729
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
1730
- <h5 id="getbyte">5.10.2 <tt>getbyte</tt></h5>
1731
- <p>Active Support backports <tt>getbyte</tt> from Ruby 1.9:</p>
1732
- <div class="code_container">
1733
- <pre class="brush: ruby; gutter: false; toolbar: false">
1734
- &quot;foo&quot;.getbyte(0) # =&gt; 102, same as &quot;foo&quot;.ord
1735
- &quot;foo&quot;.getbyte(1) # =&gt; 111
1736
- &quot;foo&quot;.getbyte(9) # =&gt; nil
1737
- &quot;foo&quot;.getbyte(-1) # =&gt; 111
1738
- </pre>
1739
- </div>
1740
- <div class="info"><p><tt>getbyte</tt> is equivalent to <tt>[]</tt>.</p></div>
1741
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
1742
- <h5 id="to_date-to_time-to_datetime">5.10.3 <tt>to_date</tt>, <tt>to_time</tt>, <tt>to_datetime</tt></h5>
1743
- <p>The methods <tt>to_date</tt>, <tt>to_time</tt>, and <tt>to_datetime</tt> are basically convenience wrappers around <tt>Date._parse</tt>:</p>
1744
- <div class="code_container">
1745
- <pre class="brush: ruby; gutter: false; toolbar: false">
1746
- &quot;2010-07-27&quot;.to_date # =&gt; Tue, 27 Jul 2010
1747
- &quot;2010-07-27 23:37:00&quot;.to_time # =&gt; Tue Jul 27 23:37:00 UTC 2010
1748
- &quot;2010-07-27 23:37:00&quot;.to_datetime # =&gt; Tue, 27 Jul 2010 23:37:00 +0000
1749
- </pre>
1750
- </div>
1751
- <p><tt>to_time</tt> receives an optional argument <tt>:utc</tt> or <tt>:local</tt>, to indicate which time zone you want the time in:</p>
1752
- <div class="code_container">
1753
- <pre class="brush: ruby; gutter: false; toolbar: false">
1754
- &quot;2010-07-27 23:42:00&quot;.to_time(:utc) # =&gt; Tue Jul 27 23:42:00 UTC 2010
1755
- &quot;2010-07-27 23:42:00&quot;.to_time(:local) # =&gt; Tue Jul 27 23:42:00 +0200 2010
1756
- </pre>
1757
- </div>
1758
- <p>Default is <tt>:utc</tt>.</p>
1759
- <p>Please refer to the documentation of <tt>Date._parse</tt> for further details.</p>
1760
- <div class="info"><p>The three of them return <tt>nil</tt> for blank receivers.</p></div>
1761
- <div class="note"><p>Defined in <tt>active_support/core_ext/string/conversions.rb</tt>.</p></div>
1762
- <h3 id="extensions-to-numeric">6 Extensions to <tt>Numeric</tt></h3>
1763
- <h4 id="bytes">6.1 Bytes</h4>
1764
- <p>All numbers respond to these methods:</p>
1765
- <div class="code_container">
1766
- <pre class="brush: ruby; gutter: false; toolbar: false">
1767
- bytes
1768
- kilobytes
1769
- megabytes
1770
- gigabytes
1771
- terabytes
1772
- petabytes
1773
- exabytes
1774
- </pre>
1775
- </div>
1776
- <p>They return the corresponding amount of bytes, using a conversion factor of 1024:</p>
1777
- <div class="code_container">
1778
- <pre class="brush: ruby; gutter: false; toolbar: false">
1779
- 2.kilobytes # =&gt; 2048
1780
- 3.megabytes # =&gt; 3145728
1781
- 3.5.gigabytes # =&gt; 3758096384
1782
- -4.exabytes # =&gt; -4611686018427387904
1783
- </pre>
1784
- </div>
1785
- <p>Singular forms are aliased so you are able to say:</p>
1786
- <div class="code_container">
1787
- <pre class="brush: ruby; gutter: false; toolbar: false">
1788
- 1.megabyte # =&gt; 1048576
1789
- </pre>
1790
- </div>
1791
- <div class="note"><p>Defined in <tt>active_support/core_ext/numeric/bytes.rb</tt>.</p></div>
1792
- <h3 id="extensions-to-integer">7 Extensions to <tt>Integer</tt></h3>
1793
- <h4 id="multiple_of">7.1 <tt>multiple_of?</tt></h4>
1794
- <p>The method <tt>multiple_of?</tt> tests whether an integer is multiple of the argument:</p>
1795
- <div class="code_container">
1796
- <pre class="brush: ruby; gutter: false; toolbar: false">
1797
- 2.multiple_of?(1) # =&gt; true
1798
- 1.multiple_of?(2) # =&gt; false
1799
- </pre>
1800
- </div>
1801
- <div class="note"><p>Defined in <tt>active_support/core_ext/integer/multiple.rb</tt>.</p></div>
1802
- <h4 id="ordinalize">7.2 <tt>ordinalize</tt></h4>
1803
- <p>The method <tt>ordinalize</tt> returns the ordinal string corresponding to the receiver integer:</p>
1804
- <div class="code_container">
1805
- <pre class="brush: ruby; gutter: false; toolbar: false">
1806
- 1.ordinalize # =&gt; &quot;1st&quot;
1807
- 2.ordinalize # =&gt; &quot;2nd&quot;
1808
- 53.ordinalize # =&gt; &quot;53rd&quot;
1809
- 2009.ordinalize # =&gt; &quot;2009th&quot;
1810
- -21.ordinalize # =&gt; &quot;-21st&quot;
1811
- -134.ordinalize # =&gt; &quot;-134th&quot;
1812
- </pre>
1813
- </div>
1814
- <div class="note"><p>Defined in <tt>active_support/core_ext/integer/inflections.rb</tt>.</p></div>
1815
- <h3 id="extensions-to-float">8 Extensions to <tt>Float</tt></h3>
1816
- <h4 id="round">8.1 <tt>round</tt></h4>
1817
- <p>The built-in method <tt>Float#round</tt> rounds a float to the nearest integer. In Ruby 1.9 this method takes an optional argument to let you specify a precision. Active Support adds that functionality to <tt>round</tt> in previous versions of Ruby:</p>
1818
- <div class="code_container">
1819
- <pre class="brush: ruby; gutter: false; toolbar: false">
1820
- Math::E.round(4) # =&gt; 2.7183
1821
- </pre>
1822
- </div>
1823
- <div class="note"><p>Defined in <tt>active_support/core_ext/float/rounding.rb</tt>.</p></div>
1824
- <h3 id="extensions-to-bigdecimal">9 Extensions to <tt>BigDecimal</tt></h3>
1825
- <p>&#8230;</p>
1826
- <h3 id="extensions-to-enumerable">10 Extensions to <tt>Enumerable</tt></h3>
1827
- <h4 id="group_by">10.1 <tt>group_by</tt></h4>
1828
- <p>Active Support redefines <tt>group_by</tt> in Ruby 1.8.7 so that it returns an ordered hash as in 1.9:</p>
1829
- <div class="code_container">
1830
- <pre class="brush: ruby; gutter: false; toolbar: false">
1831
- entries_by_surname_initial = address_book.group_by do |entry|
1832
- entry.surname.at(0).upcase
1833
- end
1834
- </pre>
1835
- </div>
1836
- <p>Distinct block return values are added to the hash as they come, so that&#8217;s the resulting order.</p>
1837
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1838
- <h4 id="sum">10.2 <tt>sum</tt></h4>
1839
- <p>The method <tt>sum</tt> adds the elements of an enumerable:</p>
1840
- <div class="code_container">
1841
- <pre class="brush: ruby; gutter: false; toolbar: false">
1842
- [1, 2, 3].sum # =&gt; 6
1843
- (1..100).sum # =&gt; 5050
1844
- </pre>
1845
- </div>
1846
- <p>Addition only assumes the elements respond to <tt>+</tt>:</p>
1847
- <div class="code_container">
1848
- <pre class="brush: ruby; gutter: false; toolbar: false">
1849
- [[1, 2], [2, 3], [3, 4]].sum # =&gt; [1, 2, 2, 3, 3, 4]
1850
- %w(foo bar baz).sum # =&gt; &quot;foobarbaz&quot;
1851
- {:a =&gt; 1, :b =&gt; 2, :c =&gt; 3}.sum # =&gt; [:b, 2, :c, 3, :a, 1]
1852
- </pre>
1853
- </div>
1854
- <p>The sum of an empty collection is zero by default, but this is customizable:</p>
1855
- <div class="code_container">
1856
- <pre class="brush: ruby; gutter: false; toolbar: false">
1857
- [].sum # =&gt; 0
1858
- [].sum(1) # =&gt; 1
1859
- </pre>
1860
- </div>
1861
- <p>If a block is given, <tt>sum</tt> becomes an iterator that yields the elements of the collection and sums the returned values:</p>
1862
- <div class="code_container">
1863
- <pre class="brush: ruby; gutter: false; toolbar: false">
1864
- (1..5).sum {|n| n * 2 } # =&gt; 30
1865
- [2, 4, 6, 8, 10].sum # =&gt; 30
1866
- </pre>
1867
- </div>
1868
- <p>The sum of an empty receiver can be customized in this form as well:</p>
1869
- <div class="code_container">
1870
- <pre class="brush: ruby; gutter: false; toolbar: false">
1871
- [].sum(1) {|n| n**3} # =&gt; 1
1872
- </pre>
1873
- </div>
1874
- <p>The method <tt>ActiveRecord::Observer#observed_subclasses</tt> for example is implemented this way:</p>
1875
- <div class="code_container">
1876
- <pre class="brush: ruby; gutter: false; toolbar: false">
1877
- def observed_subclasses
1878
- observed_classes.sum([]) { |klass| klass.send(:subclasses) }
1879
- end
1880
- </pre>
1881
- </div>
1882
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1883
- <h4 id="each_with_object">10.3 <tt>each_with_object</tt></h4>
1884
- <p>The <tt>inject</tt> method offers iteration with an accumulator:</p>
1885
- <div class="code_container">
1886
- <pre class="brush: ruby; gutter: false; toolbar: false">
1887
- [2, 3, 4].inject(1) {|product, i| product*i } # =&gt; 24
1888
- </pre>
1889
- </div>
1890
- <p>The block is expected to return the value for the accumulator in the next iteration, and this makes building mutable objects a bit cumbersome:</p>
1891
- <div class="code_container">
1892
- <pre class="brush: ruby; gutter: false; toolbar: false">
1893
- [1, 2].inject({}) {|h, i| h[i] = i**2; h} # =&gt; {1 =&gt; 1, 2 =&gt; 4}
1894
- </pre>
1895
- </div>
1896
- <p>See that spurious &#8220;<tt>; h</tt>&#8221;?</p>
1897
- <p>Active Support backports <tt>each_with_object</tt> from Ruby 1.9, which addresses that use case. It iterates over the collection, passes the accumulator, and returns the accumulator when done. You normally modify the accumulator in place. The example above would be written this way:</p>
1898
- <div class="code_container">
1899
- <pre class="brush: ruby; gutter: false; toolbar: false">
1900
- [1, 2].each_with_object({}) {|i, h| h[i] = i**2} # =&gt; {1 =&gt; 1, 2 =&gt; 4}
1901
- </pre>
1902
- </div>
1903
- <div class="warning"><p>Note that the item of the collection and the accumulator come in different order in <tt>inject</tt> and <tt>each_with_object</tt>.</p></div>
1904
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1905
- <h4 id="index_by">10.4 <tt>index_by</tt></h4>
1906
- <p>The method <tt>index_by</tt> generates a hash with the elements of an enumerable indexed by some key.</p>
1907
- <p>It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:</p>
1908
- <div class="code_container">
1909
- <pre class="brush: ruby; gutter: false; toolbar: false">
1910
- invoices.index_by(&amp;:number)
1911
- # =&gt; {'2009-032' =&gt; &lt;Invoice ...&gt;, '2009-008' =&gt; &lt;Invoice ...&gt;, ...}
1912
- </pre>
1913
- </div>
1914
- <div class="warning"><p>Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.</p></div>
1915
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1916
- <h4 id="many">10.5 <tt>many?</tt></h4>
1917
- <p>The method <tt>many?</tt> is shorthand for <tt>collection.size > 1</tt>:</p>
1918
- <div class="code_container">
1919
- <pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
1920
- &lt;% if pages.many? %&gt;
1921
- &lt;%= pagination_links %&gt;
1922
- &lt;% end %&gt;
1923
- </pre>
1924
- </div>
1925
- <p>If an optional block is given, <tt>many?</tt> only takes into account those elements that return true:</p>
1926
- <div class="code_container">
1927
- <pre class="brush: ruby; gutter: false; toolbar: false">
1928
- @see_more = videos.many? {|video| video.category == params[:category]}
1929
- </pre>
1930
- </div>
1931
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1932
- <h4 id="exclude">10.6 <tt>exclude?</tt></h4>
1933
- <p>The predicate <tt>exclude?</tt> tests whether a given object does <strong>not</strong> belong to the collection. It is the negation of the built-in <tt>include?</tt>:</p>
1934
- <div class="code_container">
1935
- <pre class="brush: ruby; gutter: false; toolbar: false">
1936
- to_visit &lt;&lt; node if visited.exclude?(node)
1937
- </pre>
1938
- </div>
1939
- <div class="note"><p>Defined in <tt>active_support/core_ext/enumerable.rb</tt>.</p></div>
1940
- <h3 id="extensions-to-array">11 Extensions to <tt>Array</tt></h3>
1941
- <h4 id="accessing">11.1 Accessing</h4>
1942
- <p>Active Support augments the <span class="caps">API</span> of arrays to ease certain ways of accessing them. For example, <tt>to</tt> returns the subarray of elements up to the one at the passed index:</p>
1943
- <div class="code_container">
1944
- <pre class="brush: ruby; gutter: false; toolbar: false">
1945
- %w(a b c d).to(2) # =&gt; %w(a b c)
1946
- [].to(7) # =&gt; []
1947
- </pre>
1948
- </div>
1949
- <p>Similarly, <tt>from</tt> returns the tail from the element at the passed index to the end. If the index is greater than the length of the array, it returns an empty array.</p>
1950
- <div class="code_container">
1951
- <pre class="brush: ruby; gutter: false; toolbar: false">
1952
- %w(a b c d).from(2) # =&gt; %w(c d)
1953
- %w(a b c d).from(10) # =&gt; []
1954
- [].from(0) # =&gt; []
1955
- </pre>
1956
- </div>
1957
- <p>The methods <tt>second</tt>, <tt>third</tt>, <tt>fourth</tt>, and <tt>fifth</tt> return the corresponding element (<tt>first</tt> is built-in). Thanks to social wisdom and positive constructiveness all around, <tt>forty_two</tt> is also available.</p>
1958
- <div class="code_container">
1959
- <pre class="brush: ruby; gutter: false; toolbar: false">
1960
- %w(a b c d).third # =&gt; c
1961
- %w(a b c d).fifth # =&gt; nil
1962
- </pre>
1963
- </div>
1964
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/access.rb</tt>.</p></div>
1965
- <h4 id="random-access">11.2 Random Access</h4>
1966
- <p>Active Support backports <tt>sample</tt> from Ruby 1.9:</p>
1967
- <div class="code_container">
1968
- <pre class="brush: ruby; gutter: false; toolbar: false">
1969
- shape_type = [Circle, Square, Triangle].sample
1970
- # =&gt; Square, for example
1971
-
1972
- shape_types = [Circle, Square, Triangle].sample(2)
1973
- # =&gt; [Triangle, Circle], for example
1974
- </pre>
1975
- </div>
1976
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/random_access.rb</tt>.</p></div>
1977
- <h4 id="adding-elements">11.3 Adding Elements</h4>
1978
- <h5 id="prepend">11.3.1 <tt>prepend</tt></h5>
1979
- <p>This method is an alias of <tt>Array#unshift</tt>.</p>
1980
- <div class="code_container">
1981
- <pre class="brush: ruby; gutter: false; toolbar: false">
1982
- %w(a b c d).prepend('e') # =&gt; %w(e a b c d)
1983
- [].prepend(10) # =&gt; [10]
1984
- </pre>
1985
- </div>
1986
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/prepend_and_append.rb</tt>.</p></div>
1987
- <h5 id="append">11.3.2 <tt>append</tt></h5>
1988
- <p>This method is an alias of <tt>Array#&lt;&lt;</tt>.</p>
1989
- <div class="code_container">
1990
- <pre class="brush: ruby; gutter: false; toolbar: false">
1991
- %w(a b c d).append('e') # =&gt; %w(a b c d e)
1992
- [].append([1,2]) # =&gt; [[1,2]]
1993
- </pre>
1994
- </div>
1995
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/prepend_and_append.rb</tt>.</p></div>
1996
- <h4 id="options-extraction">11.4 Options Extraction</h4>
1997
- <p>When the last argument in a method call is a hash, except perhaps for a <tt>&block</tt> argument, Ruby allows you to omit the brackets:</p>
1998
- <div class="code_container">
1999
- <pre class="brush: ruby; gutter: false; toolbar: false">
2000
- User.exists?(:email =&gt; params[:email])
2001
- </pre>
2002
- </div>
2003
- <p>That syntactic sugar is used a lot in Rails to avoid positional arguments where there would be too many, offering instead interfaces that emulate named parameters. In particular it is very idiomatic to use a trailing hash for options.</p>
2004
- <p>If a method expects a variable number of arguments and uses <tt>*</tt> in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.</p>
2005
- <p>In those cases, you may give an options hash a distinguished treatment with <tt>extract_options!</tt>. This method checks the type of the last item of an array. If it is a hash it pops it and returns it, otherwise it returns an empty hash.</p>
2006
- <p>Let&#8217;s see for example the definition of the <tt>caches_action</tt> controller macro:</p>
2007
- <div class="code_container">
2008
- <pre class="brush: ruby; gutter: false; toolbar: false">
2009
- def caches_action(*actions)
2010
- return unless cache_configured?
2011
- options = actions.extract_options!
2012
- ...
2013
- end
2014
- </pre>
2015
- </div>
2016
- <p>This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to <tt>extract_options!</tt> you obtain the options hash and remove it from <tt>actions</tt> in a simple and explicit way.</p>
2017
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/extract_options.rb</tt>.</p></div>
2018
- <h4 id="array-conversions">11.5 Conversions</h4>
2019
- <h5 id="to_sentence">11.5.1 <tt>to_sentence</tt></h5>
2020
- <p>The method <tt>to_sentence</tt> turns an array into a string containing a sentence that enumerates its items:</p>
2021
- <div class="code_container">
2022
- <pre class="brush: ruby; gutter: false; toolbar: false">
2023
- %w().to_sentence # =&gt; &quot;&quot;
2024
- %w(Earth).to_sentence # =&gt; &quot;Earth&quot;
2025
- %w(Earth Wind).to_sentence # =&gt; &quot;Earth and Wind&quot;
2026
- %w(Earth Wind Fire).to_sentence # =&gt; &quot;Earth, Wind, and Fire&quot;
2027
- </pre>
2028
- </div>
2029
- <p>This method accepts three options:</p>
2030
- <ul>
2031
- <li><tt>:two_words_connector</tt>: What is used for arrays of length 2. Default is &quot; and &quot;.</li>
2032
- <li><tt>:words_connector</tt>: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is &quot;, &quot;.</li>
2033
- <li><tt>:last_word_connector</tt>: What is used to join the last items of an array with 3 or more elements. Default is &quot;, and &quot;.</li>
2034
- </ul>
2035
- <p>The defaults for these options can be localised, their keys are:</p>
2036
- <table>
2037
- <tr>
2038
- <th>Option </th>
2039
- <th>I18n key </th>
2040
- </tr>
2041
- <tr>
2042
- <td> <tt>:two_words_connector</tt> </td>
2043
- <td> <tt>support.array.two_words_connector</tt> </td>
2044
- </tr>
2045
- <tr>
2046
- <td> <tt>:words_connector</tt> </td>
2047
- <td> <tt>support.array.words_connector</tt> </td>
2048
- </tr>
2049
- <tr>
2050
- <td> <tt>:last_word_connector</tt> </td>
2051
- <td> <tt>support.array.last_word_connector</tt> </td>
2052
- </tr>
2053
- </table>
2054
- <p>Options <tt>:connector</tt> and <tt>:skip_last_comma</tt> are deprecated.</p>
2055
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
2056
- <h5 id="to_formatted_s">11.5.2 <tt>to_formatted_s</tt></h5>
2057
- <p>The method <tt>to_formatted_s</tt> acts like <tt>to_s</tt> by default.</p>
2058
- <p>If the array contains items that respond to <tt>id</tt>, however, it may be passed the symbol <tt>:db</tt> as argument. That&#8217;s typically used with collections of ARs, though technically any object in Ruby 1.8 responds to <tt>id</tt> indeed. Returned strings are:</p>
2059
- <div class="code_container">
2060
- <pre class="brush: ruby; gutter: false; toolbar: false">
2061
- [].to_formatted_s(:db) # =&gt; &quot;null&quot;
2062
- [user].to_formatted_s(:db) # =&gt; &quot;8456&quot;
2063
- invoice.lines.to_formatted_s(:db) # =&gt; &quot;23,567,556,12&quot;
2064
- </pre>
2065
- </div>
2066
- <p>Integers in the example above are supposed to come from the respective calls to <tt>id</tt>.</p>
2067
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
2068
- <h5 id="to_xml">11.5.3 <tt>to_xml</tt></h5>
2069
- <p>The method <tt>to_xml</tt> returns a string containing an <span class="caps">XML</span> representation of its receiver:</p>
2070
- <div class="code_container">
2071
- <pre class="brush: ruby; gutter: false; toolbar: false">
2072
- Contributor.limit(2).order(:rank).to_xml
2073
- # =&gt;
2074
- # &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
2075
- # &lt;contributors type=&quot;array&quot;&gt;
2076
- # &lt;contributor&gt;
2077
- # &lt;id type=&quot;integer&quot;&gt;4356&lt;/id&gt;
2078
- # &lt;name&gt;Jeremy Kemper&lt;/name&gt;
2079
- # &lt;rank type=&quot;integer&quot;&gt;1&lt;/rank&gt;
2080
- # &lt;url-id&gt;jeremy-kemper&lt;/url-id&gt;
2081
- # &lt;/contributor&gt;
2082
- # &lt;contributor&gt;
2083
- # &lt;id type=&quot;integer&quot;&gt;4404&lt;/id&gt;
2084
- # &lt;name&gt;David Heinemeier Hansson&lt;/name&gt;
2085
- # &lt;rank type=&quot;integer&quot;&gt;2&lt;/rank&gt;
2086
- # &lt;url-id&gt;david-heinemeier-hansson&lt;/url-id&gt;
2087
- # &lt;/contributor&gt;
2088
- # &lt;/contributors&gt;
2089
- </pre>
2090
- </div>
2091
- <p>To do so it sends <tt>to_xml</tt> to every item in turn, and collects the results under a root node. All items must respond to <tt>to_xml</tt>, an exception is raised otherwise.</p>
2092
- <p>By default, the name of the root element is the underscorized and dasherized plural of the name of the class of the first item, provided the rest of elements belong to that type (checked with <tt>is_a?</tt>) and they are not hashes. In the example above that&#8217;s &#8220;contributors&#8221;.</p>
2093
- <p>If there&#8217;s any element that does not belong to the type of the first one the root node becomes &#8220;records&#8221;:</p>
2094
- <div class="code_container">
2095
- <pre class="brush: ruby; gutter: false; toolbar: false">
2096
- [Contributor.first, Commit.first].to_xml
2097
- # =&gt;
2098
- # &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
2099
- # &lt;records type=&quot;array&quot;&gt;
2100
- # &lt;record&gt;
2101
- # &lt;id type=&quot;integer&quot;&gt;4583&lt;/id&gt;
2102
- # &lt;name&gt;Aaron Batalion&lt;/name&gt;
2103
- # &lt;rank type=&quot;integer&quot;&gt;53&lt;/rank&gt;
2104
- # &lt;url-id&gt;aaron-batalion&lt;/url-id&gt;
2105
- # &lt;/record&gt;
2106
- # &lt;record&gt;
2107
- # &lt;author&gt;Joshua Peek&lt;/author&gt;
2108
- # &lt;authored-timestamp type=&quot;datetime&quot;&gt;2009-09-02T16:44:36Z&lt;/authored-timestamp&gt;
2109
- # &lt;branch&gt;origin/master&lt;/branch&gt;
2110
- # &lt;committed-timestamp type=&quot;datetime&quot;&gt;2009-09-02T16:44:36Z&lt;/committed-timestamp&gt;
2111
- # &lt;committer&gt;Joshua Peek&lt;/committer&gt;
2112
- # &lt;git-show nil=&quot;true&quot;&gt;&lt;/git-show&gt;
2113
- # &lt;id type=&quot;integer&quot;&gt;190316&lt;/id&gt;
2114
- # &lt;imported-from-svn type=&quot;boolean&quot;&gt;false&lt;/imported-from-svn&gt;
2115
- # &lt;message&gt;Kill AMo observing wrap_with_notifications since ARes was only using it&lt;/message&gt;
2116
- # &lt;sha1&gt;723a47bfb3708f968821bc969a9a3fc873a3ed58&lt;/sha1&gt;
2117
- # &lt;/record&gt;
2118
- # &lt;/records&gt;
2119
- </pre>
2120
- </div>
2121
- <p>If the receiver is an array of hashes the root element is by default also &#8220;records&#8221;:</p>
2122
- <div class="code_container">
2123
- <pre class="brush: ruby; gutter: false; toolbar: false">
2124
- [{:a =&gt; 1, :b =&gt; 2}, {:c =&gt; 3}].to_xml
2125
- # =&gt;
2126
- # &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
2127
- # &lt;records type=&quot;array&quot;&gt;
2128
- # &lt;record&gt;
2129
- # &lt;b type=&quot;integer&quot;&gt;2&lt;/b&gt;
2130
- # &lt;a type=&quot;integer&quot;&gt;1&lt;/a&gt;
2131
- # &lt;/record&gt;
2132
- # &lt;record&gt;
2133
- # &lt;c type=&quot;integer&quot;&gt;3&lt;/c&gt;
2134
- # &lt;/record&gt;
2135
- # &lt;/records&gt;
2136
- </pre>
2137
- </div>
2138
- <div class="warning"><p>If the collection is empty the root element is by default &#8220;nil-classes&#8221;. That&#8217;s a gotcha, for example the root element of the list of contributors above would not be &#8220;contributors&#8221; if the collection was empty, but &#8220;nil-classes&#8221;. You may use the <tt>:root</tt> option to ensure a consistent root element.</p></div>
2139
- <p>The name of children nodes is by default the name of the root node singularized. In the examples above we&#8217;ve seen &#8220;contributor&#8221; and &#8220;record&#8221;. The option <tt>:children</tt> allows you to set these node names.</p>
2140
- <p>The default <span class="caps">XML</span> builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder via the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder:</p>
2141
- <div class="code_container">
2142
- <pre class="brush: ruby; gutter: false; toolbar: false">
2143
- Contributor.limit(2).order(:rank).to_xml(:skip_types =&gt; true)
2144
- # =&gt;
2145
- # &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
2146
- # &lt;contributors&gt;
2147
- # &lt;contributor&gt;
2148
- # &lt;id&gt;4356&lt;/id&gt;
2149
- # &lt;name&gt;Jeremy Kemper&lt;/name&gt;
2150
- # &lt;rank&gt;1&lt;/rank&gt;
2151
- # &lt;url-id&gt;jeremy-kemper&lt;/url-id&gt;
2152
- # &lt;/contributor&gt;
2153
- # &lt;contributor&gt;
2154
- # &lt;id&gt;4404&lt;/id&gt;
2155
- # &lt;name&gt;David Heinemeier Hansson&lt;/name&gt;
2156
- # &lt;rank&gt;2&lt;/rank&gt;
2157
- # &lt;url-id&gt;david-heinemeier-hansson&lt;/url-id&gt;
2158
- # &lt;/contributor&gt;
2159
- # &lt;/contributors&gt;
2160
- </pre>
2161
- </div>
2162
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/conversions.rb</tt>.</p></div>
2163
- <h4 id="wrapping">11.6 Wrapping</h4>
2164
- <p>The method <tt>Array.wrap</tt> wraps its argument in an array unless it is already an array (or array-like).</p>
2165
- <p>Specifically:</p>
2166
- <ul>
2167
- <li>If the argument is <tt>nil</tt> an empty list is returned.</li>
2168
- <li>Otherwise, if the argument responds to <tt>to_ary</tt> it is invoked, and if the value of <tt>to_ary</tt> is not <tt>nil</tt>, it is returned.</li>
2169
- <li>Otherwise, an array with the argument as its single element is returned.</li>
2170
- </ul>
2171
- <div class="code_container">
2172
- <pre class="brush: ruby; gutter: false; toolbar: false">
2173
- Array.wrap(nil) # =&gt; []
2174
- Array.wrap([1, 2, 3]) # =&gt; [1, 2, 3]
2175
- Array.wrap(0) # =&gt; [0]
2176
- </pre>
2177
- </div>
2178
- <p>This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences:</p>
2179
- <ul>
2180
- <li>If the argument responds to <tt>to_ary</tt> the method is invoked. <tt>Kernel#Array</tt> moves on to try <tt>to_a</tt> if the returned value is <tt>nil</tt>, but <tt>Array.wrap</tt> returns <tt>nil</tt> right away.</li>
2181
- <li>If the returned value from <tt>to_ary</tt> is neither <tt>nil</tt> nor an <tt>Array</tt> object, <tt>Kernel#Array</tt> raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.</li>
2182
- <li>It does not call <tt>to_a</tt> on the argument, though special-cases <tt>nil</tt> to return an empty array.</li>
2183
- </ul>
2184
- <p>The last point is particularly worth comparing for some enumerables:</p>
2185
- <div class="code_container">
2186
- <pre class="brush: ruby; gutter: false; toolbar: false">
2187
- Array.wrap(:foo =&gt; :bar) # =&gt; [{:foo =&gt; :bar}]
2188
- Array(:foo =&gt; :bar) # =&gt; [[:foo, :bar]]
2189
-
2190
- Array.wrap(&quot;foo\nbar&quot;) # =&gt; [&quot;foo\nbar&quot;]
2191
- Array(&quot;foo\nbar&quot;) # =&gt; [&quot;foo\n&quot;, &quot;bar&quot;], in Ruby 1.8
2192
- </pre>
2193
- </div>
2194
- <p>There&#8217;s also a related idiom that uses the splat operator:</p>
2195
- <div class="code_container">
2196
- <pre class="brush: ruby; gutter: false; toolbar: false">
2197
- [*object]
2198
- </pre>
2199
- </div>
2200
- <p>which in Ruby 1.8 returns <tt>[nil]</tt> for <tt>nil</tt>, and calls to <tt>Array(object)</tt> otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)</p>
2201
- <p>Thus, in this case the behavior is different for <tt>nil</tt>, and the differences with <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s.</p>
2202
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/wrap.rb</tt>.</p></div>
2203
- <h4 id="grouping">11.7 Grouping</h4>
2204
- <h5 id="in_groups_of-number-fill_with-nil">11.7.1 <tt>in_groups_of(number, fill_with = nil)</tt></h5>
2205
- <p>The method <tt>in_groups_of</tt> splits an array into consecutive groups of a certain size. It returns an array with the groups:</p>
2206
- <div class="code_container">
2207
- <pre class="brush: ruby; gutter: false; toolbar: false">
2208
- [1, 2, 3].in_groups_of(2) # =&gt; [[1, 2], [3, nil]]
2209
- </pre>
2210
- </div>
2211
- <p>or yields them in turn if a block is passed:</p>
2212
- <div class="code_container">
2213
- <pre class="brush: ruby; gutter: false; toolbar: false">
2214
- &lt;% sample.in_groups_of(3) do |a, b, c| %&gt;
2215
- &lt;tr&gt;
2216
- &lt;td&gt;&lt;%=h a %&gt;&lt;/td&gt;
2217
- &lt;td&gt;&lt;%=h b %&gt;&lt;/td&gt;
2218
- &lt;td&gt;&lt;%=h c %&gt;&lt;/td&gt;
2219
- &lt;/tr&gt;
2220
- &lt;% end %&gt;
2221
- </pre>
2222
- </div>
2223
- <p>The first example shows <tt>in_groups_of</tt> fills the last group with as many <tt>nil</tt> elements as needed to have the requested size. You can change this padding value using the second optional argument:</p>
2224
- <div class="code_container">
2225
- <pre class="brush: ruby; gutter: false; toolbar: false">
2226
- [1, 2, 3].in_groups_of(2, 0) # =&gt; [[1, 2], [3, 0]]
2227
- </pre>
2228
- </div>
2229
- <p>And you can tell the method not to fill the last group passing <tt>false</tt>:</p>
2230
- <div class="code_container">
2231
- <pre class="brush: ruby; gutter: false; toolbar: false">
2232
- [1, 2, 3].in_groups_of(2, false) # =&gt; [[1, 2], [3]]
2233
- </pre>
2234
- </div>
2235
- <p>As a consequence <tt>false</tt> can&#8217;t be a used as a padding value.</p>
2236
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
2237
- <h5 id="in_groups-number-fill_with-nil">11.7.2 <tt>in_groups(number, fill_with = nil)</tt></h5>
2238
- <p>The method <tt>in_groups</tt> splits an array into a certain number of groups. The method returns an array with the groups:</p>
2239
- <div class="code_container">
2240
- <pre class="brush: ruby; gutter: false; toolbar: false">
2241
- %w(1 2 3 4 5 6 7).in_groups(3)
2242
- # =&gt; [[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;], [&quot;4&quot;, &quot;5&quot;, nil], [&quot;6&quot;, &quot;7&quot;, nil]]
2243
- </pre>
2244
- </div>
2245
- <p>or yields them in turn if a block is passed:</p>
2246
- <div class="code_container">
2247
- <pre class="brush: ruby; gutter: false; toolbar: false">
2248
- %w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
2249
- [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;]
2250
- [&quot;4&quot;, &quot;5&quot;, nil]
2251
- [&quot;6&quot;, &quot;7&quot;, nil]
2252
- </pre>
2253
- </div>
2254
- <p>The examples above show that <tt>in_groups</tt> fills some groups with a trailing <tt>nil</tt> element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.</p>
2255
- <p>You can change this padding value using the second optional argument:</p>
2256
- <div class="code_container">
2257
- <pre class="brush: ruby; gutter: false; toolbar: false">
2258
- %w(1 2 3 4 5 6 7).in_groups(3, &quot;0&quot;)
2259
- # =&gt; [[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;], [&quot;4&quot;, &quot;5&quot;, &quot;0&quot;], [&quot;6&quot;, &quot;7&quot;, &quot;0&quot;]]
2260
- </pre>
2261
- </div>
2262
- <p>And you can tell the method not to fill the smaller groups passing <tt>false</tt>:</p>
2263
- <div class="code_container">
2264
- <pre class="brush: ruby; gutter: false; toolbar: false">
2265
- %w(1 2 3 4 5 6 7).in_groups(3, false)
2266
- # =&gt; [[&quot;1&quot;, &quot;2&quot;, &quot;3&quot;], [&quot;4&quot;, &quot;5&quot;], [&quot;6&quot;, &quot;7&quot;]]
2267
- </pre>
2268
- </div>
2269
- <p>As a consequence <tt>false</tt> can&#8217;t be a used as a padding value.</p>
2270
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
2271
- <h5 id="split-value-nil">11.7.3 <tt>split(value = nil)</tt></h5>
2272
- <p>The method <tt>split</tt> divides an array by a separator and returns the resulting chunks.</p>
2273
- <p>If a block is passed the separators are those elements of the array for which the block returns true:</p>
2274
- <div class="code_container">
2275
- <pre class="brush: ruby; gutter: false; toolbar: false">
2276
- (-5..5).to_a.split { |i| i.multiple_of?(4) }
2277
- # =&gt; [[-5], [-3, -2, -1], [1, 2, 3], [5]]
2278
- </pre>
2279
- </div>
2280
- <p>Otherwise, the value received as argument, which defaults to <tt>nil</tt>, is the separator:</p>
2281
- <div class="code_container">
2282
- <pre class="brush: ruby; gutter: false; toolbar: false">
2283
- [0, 1, -5, 1, 1, &quot;foo&quot;, &quot;bar&quot;].split(1)
2284
- # =&gt; [[0], [-5], [], [&quot;foo&quot;, &quot;bar&quot;]]
2285
- </pre>
2286
- </div>
2287
- <div class="info"><p>Observe in the previous example that consecutive separators result in empty arrays.</p></div>
2288
- <div class="note"><p>Defined in <tt>active_support/core_ext/array/grouping.rb</tt>.</p></div>
2289
- <h3 id="extensions-to-hash">12 Extensions to <tt>Hash</tt></h3>
2290
- <h4 id="hash-conversions">12.1 Conversions</h4>
2291
- <h5 id="hash-to-xml">12.1.1 <tt>to_xml</tt></h5>
2292
- <p>The method <tt>to_xml</tt> returns a string containing an <span class="caps">XML</span> representation of its receiver:</p>
2293
- <div class="code_container">
2294
- <pre class="brush: ruby; gutter: false; toolbar: false">
2295
- {&quot;foo&quot; =&gt; 1, &quot;bar&quot; =&gt; 2}.to_xml
2296
- # =&gt;
2297
- # &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
2298
- # &lt;hash&gt;
2299
- # &lt;foo type=&quot;integer&quot;&gt;1&lt;/foo&gt;
2300
- # &lt;bar type=&quot;integer&quot;&gt;2&lt;/bar&gt;
2301
- # &lt;/hash&gt;
2302
- </pre>
2303
- </div>
2304
- <p>To do so, the method loops over the pairs and builds nodes that depend on the <em>values</em>. Given a pair <tt>key</tt>, <tt>value</tt>:</p>
2305
- <ul>
2306
- <li>If <tt>value</tt> is a hash there&#8217;s a recursive call with <tt>key</tt> as <tt>:root</tt>.</li>
2307
- </ul>
2308
- <ul>
2309
- <li>If <tt>value</tt> is an array there&#8217;s a recursive call with <tt>key</tt> as <tt>:root</tt>, and <tt>key</tt> singularized as <tt>:children</tt>.</li>
2310
- </ul>
2311
- <ul>
2312
- <li>If <tt>value</tt> is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the <tt>options</tt> hash as first argument with <tt>key</tt> as <tt>:root</tt>, and <tt>key</tt> singularized as second argument. Its return value becomes a new node.</li>
2313
- </ul>
2314
- <ul>
2315
- <li>If <tt>value</tt> responds to <tt>to_xml</tt> the method is invoked with <tt>key</tt> as <tt>:root</tt>.</li>
2316
- </ul>
2317
- <ul>
2318
- <li>Otherwise, a node with <tt>key</tt> as tag is created with a string representation of <tt>value</tt> as text node. If <tt>value</tt> is <tt>nil</tt> an attribute &#8220;nil&#8221; set to &#8220;true&#8221; is added. Unless the option <tt>:skip_types</tt> exists and is true, an attribute &#8220;type&#8221; is added as well according to the following mapping:
2319
- <div class="code_container">
2320
- <pre class="brush: ruby; gutter: false; toolbar: false">
2321
- XML_TYPE_NAMES = {
2322
- &quot;Symbol&quot; =&gt; &quot;symbol&quot;,
2323
- &quot;Fixnum&quot; =&gt; &quot;integer&quot;,
2324
- &quot;Bignum&quot; =&gt; &quot;integer&quot;,
2325
- &quot;BigDecimal&quot; =&gt; &quot;decimal&quot;,
2326
- &quot;Float&quot; =&gt; &quot;float&quot;,
2327
- &quot;TrueClass&quot; =&gt; &quot;boolean&quot;,
2328
- &quot;FalseClass&quot; =&gt; &quot;boolean&quot;,
2329
- &quot;Date&quot; =&gt; &quot;date&quot;,
2330
- &quot;DateTime&quot; =&gt; &quot;datetime&quot;,
2331
- &quot;Time&quot; =&gt; &quot;datetime&quot;
2332
- }
2333
- </pre>
2334
- </div>
2335
- </li>
2336
- </ul>
2337
- <p>By default the root node is &#8220;hash&#8221;, but that&#8217;s configurable via the <tt>:root</tt> option.</p>
2338
- <p>The default <span class="caps">XML</span> builder is a fresh instance of <tt>Builder::XmlMarkup</tt>. You can configure your own builder with the <tt>:builder</tt> option. The method also accepts options like <tt>:dasherize</tt> and friends, they are forwarded to the builder.</p>
2339
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/conversions.rb</tt>.</p></div>
2340
- <h4 id="merging">12.2 Merging</h4>
2341
- <p>Ruby has a built-in method <tt>Hash#merge</tt> that merges two hashes:</p>
2342
- <div class="code_container">
2343
- <pre class="brush: ruby; gutter: false; toolbar: false">
2344
- {:a =&gt; 1, :b =&gt; 1}.merge(:a =&gt; 0, :c =&gt; 2)
2345
- # =&gt; {:a =&gt; 0, :b =&gt; 1, :c =&gt; 2}
2346
- </pre>
2347
- </div>
2348
- <p>Active Support defines a few more ways of merging hashes that may be convenient.</p>
2349
- <h5 id="reverse_merge-and-reverse_merge">12.2.1 <tt>reverse_merge</tt> and <tt>reverse_merge!</tt></h5>
2350
- <p>In case of collision the key in the hash of the argument wins in <tt>merge</tt>. You can support option hashes with default values in a compact way with this idiom:</p>
2351
- <div class="code_container">
2352
- <pre class="brush: ruby; gutter: false; toolbar: false">
2353
- options = {:length =&gt; 30, :omission =&gt; &quot;...&quot;}.merge(options)
2354
- </pre>
2355
- </div>
2356
- <p>Active Support defines <tt>reverse_merge</tt> in case you prefer this alternative notation:</p>
2357
- <div class="code_container">
2358
- <pre class="brush: ruby; gutter: false; toolbar: false">
2359
- options = options.reverse_merge(:length =&gt; 30, :omission =&gt; &quot;...&quot;)
2360
- </pre>
2361
- </div>
2362
- <p>And a bang version <tt>reverse_merge!</tt> that performs the merge in place:</p>
2363
- <div class="code_container">
2364
- <pre class="brush: ruby; gutter: false; toolbar: false">
2365
- options.reverse_merge!(:length =&gt; 30, :omission =&gt; &quot;...&quot;)
2366
- </pre>
2367
- </div>
2368
- <div class="warning"><p>Take into account that <tt>reverse_merge!</tt> may change the hash in the caller, which may or may not be a good idea.</p></div>
2369
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/reverse_merge.rb</tt>.</p></div>
2370
- <h5 id="reverse_update">12.2.2 <tt>reverse_update</tt></h5>
2371
- <p>The method <tt>reverse_update</tt> is an alias for <tt>reverse_merge!</tt>, explained above.</p>
2372
- <div class="warning"><p>Note that <tt>reverse_update</tt> has no bang.</p></div>
2373
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/reverse_merge.rb</tt>.</p></div>
2374
- <h5 id="deep_merge-and-deep_merge">12.2.3 <tt>deep_merge</tt> and <tt>deep_merge!</tt></h5>
2375
- <p>As you can see in the previous example if a key is found in both hashes the value in the one in the argument wins.</p>
2376
- <p>Active Support defines <tt>Hash#deep_merge</tt>. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their <em>merge</em> becomes the value in the resulting hash:</p>
2377
- <div class="code_container">
2378
- <pre class="brush: ruby; gutter: false; toolbar: false">
2379
- {:a =&gt; {:b =&gt; 1}}.deep_merge(:a =&gt; {:c =&gt; 2})
2380
- # =&gt; {:a =&gt; {:b =&gt; 1, :c =&gt; 2}}
2381
- </pre>
2382
- </div>
2383
- <p>The method <tt>deep_merge!</tt> performs a deep merge in place.</p>
2384
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/deep_merge.rb</tt>.</p></div>
2385
- <h4 id="diffing">12.3 Diffing</h4>
2386
- <p>The method <tt>diff</tt> returns a hash that represents a diff of the receiver and the argument with the following logic:</p>
2387
- <ul>
2388
- <li>Pairs <tt>key</tt>, <tt>value</tt> that exist in both hashes do not belong to the diff hash.</li>
2389
- </ul>
2390
- <ul>
2391
- <li>If both hashes have <tt>key</tt>, but with different values, the pair in the receiver wins.</li>
2392
- </ul>
2393
- <ul>
2394
- <li>The rest is just merged.</li>
2395
- </ul>
2396
- <div class="code_container">
2397
- <pre class="brush: ruby; gutter: false; toolbar: false">
2398
- {:a =&gt; 1}.diff(:a =&gt; 1)
2399
- # =&gt; {}, first rule
2400
-
2401
- {:a =&gt; 1}.diff(:a =&gt; 2)
2402
- # =&gt; {:a =&gt; 1}, second rule
2403
-
2404
- {:a =&gt; 1}.diff(:b =&gt; 2)
2405
- # =&gt; {:a =&gt; 1, :b =&gt; 2}, third rule
2406
-
2407
- {:a =&gt; 1, :b =&gt; 2, :c =&gt; 3}.diff(:b =&gt; 1, :c =&gt; 3, :d =&gt; 4)
2408
- # =&gt; {:a =&gt; 1, :b =&gt; 2, :d =&gt; 4}, all rules
2409
-
2410
- {}.diff({}) # =&gt; {}
2411
- {:a =&gt; 1}.diff({}) # =&gt; {:a =&gt; 1}
2412
- {}.diff(:a =&gt; 1) # =&gt; {:a =&gt; 1}
2413
- </pre>
2414
- </div>
2415
- <p>An important property of this diff hash is that you can retrieve the original hash by applying <tt>diff</tt> twice:</p>
2416
- <div class="code_container">
2417
- <pre class="brush: ruby; gutter: false; toolbar: false">
2418
- hash.diff(hash2).diff(hash2) == hash
2419
- </pre>
2420
- </div>
2421
- <p>Diffing hashes may be useful for error messages related to expected option hashes for example.</p>
2422
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/diff.rb</tt>.</p></div>
2423
- <h4 id="working-with-keys">12.4 Working with Keys</h4>
2424
- <h5 id="except-and-except">12.4.1 <tt>except</tt> and <tt>except!</tt></h5>
2425
- <p>The method <tt>except</tt> returns a hash with the keys in the argument list removed, if present:</p>
2426
- <div class="code_container">
2427
- <pre class="brush: ruby; gutter: false; toolbar: false">
2428
- {:a =&gt; 1, :b =&gt; 2}.except(:a) # =&gt; {:b =&gt; 2}
2429
- </pre>
2430
- </div>
2431
- <p>If the receiver responds to <tt>convert_key</tt>, the method is called on each of the arguments. This allows <tt>except</tt> to play nice with hashes with indifferent access for instance:</p>
2432
- <div class="code_container">
2433
- <pre class="brush: ruby; gutter: false; toolbar: false">
2434
- {:a =&gt; 1}.with_indifferent_access.except(:a) # =&gt; {}
2435
- {:a =&gt; 1}.with_indifferent_access.except(&quot;a&quot;) # =&gt; {}
2436
- </pre>
2437
- </div>
2438
- <p>The method <tt>except</tt> may come in handy for example when you want to protect some parameter that can&#8217;t be globally protected with <tt>attr_protected</tt>:</p>
2439
- <div class="code_container">
2440
- <pre class="brush: ruby; gutter: false; toolbar: false">
2441
- params[:account] = params[:account].except(:plan_id) unless admin?
2442
- @account.update_attributes(params[:account])
2443
- </pre>
2444
- </div>
2445
- <p>There&#8217;s also the bang variant <tt>except!</tt> that removes keys in the very receiver.</p>
2446
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/except.rb</tt>.</p></div>
2447
- <h5 id="stringify_keys-and-stringify_keys">12.4.2 <tt>stringify_keys</tt> and <tt>stringify_keys!</tt></h5>
2448
- <p>The method <tt>stringify_keys</tt> returns a hash that has a stringified version of the keys in the receiver. It does so by sending <tt>to_s</tt> to them:</p>
2449
- <div class="code_container">
2450
- <pre class="brush: ruby; gutter: false; toolbar: false">
2451
- {nil =&gt; nil, 1 =&gt; 1, :a =&gt; :a}.stringify_keys
2452
- # =&gt; {&quot;&quot; =&gt; nil, &quot;a&quot; =&gt; :a, &quot;1&quot; =&gt; 1}
2453
- </pre>
2454
- </div>
2455
- <p>The result in case of collision is undefined:</p>
2456
- <div class="code_container">
2457
- <pre class="brush: ruby; gutter: false; toolbar: false">
2458
- {&quot;a&quot; =&gt; 1, :a =&gt; 2}.stringify_keys
2459
- # =&gt; {&quot;a&quot; =&gt; 2}, in my test, can't rely on this result though
2460
- </pre>
2461
- </div>
2462
- <p>This method may be useful for example to easily accept both symbols and strings as options. For instance <tt>ActionView::Helpers::FormHelper</tt> defines:</p>
2463
- <div class="code_container">
2464
- <pre class="brush: ruby; gutter: false; toolbar: false">
2465
- def to_check_box_tag(options = {}, checked_value = &quot;1&quot;, unchecked_value = &quot;0&quot;)
2466
- options = options.stringify_keys
2467
- options[&quot;type&quot;] = &quot;checkbox&quot;
2468
- ...
2469
- end
2470
- </pre>
2471
- </div>
2472
- <p>The second line can safely access the &#8220;type&#8221; key, and let the user to pass either <tt>:type</tt> or &#8220;type&#8221;.</p>
2473
- <p>There&#8217;s also the bang variant <tt>stringify_keys!</tt> that stringifies keys in the very receiver.</p>
2474
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
2475
- <h5 id="symbolize_keys-and-symbolize_keys">12.4.3 <tt>symbolize_keys</tt> and <tt>symbolize_keys!</tt></h5>
2476
- <p>The method <tt>symbolize_keys</tt> returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending <tt>to_sym</tt> to them:</p>
2477
- <div class="code_container">
2478
- <pre class="brush: ruby; gutter: false; toolbar: false">
2479
- {nil =&gt; nil, 1 =&gt; 1, &quot;a&quot; =&gt; &quot;a&quot;}.symbolize_keys
2480
- # =&gt; {1 =&gt; 1, nil =&gt; nil, :a =&gt; &quot;a&quot;}
2481
- </pre>
2482
- </div>
2483
- <div class="warning"><p>Note in the previous example only one key was symbolized.</p></div>
2484
- <p>The result in case of collision is undefined:</p>
2485
- <div class="code_container">
2486
- <pre class="brush: ruby; gutter: false; toolbar: false">
2487
- {&quot;a&quot; =&gt; 1, :a =&gt; 2}.symbolize_keys
2488
- # =&gt; {:a =&gt; 2}, in my test, can't rely on this result though
2489
- </pre>
2490
- </div>
2491
- <p>This method may be useful for example to easily accept both symbols and strings as options. For instance <tt>ActionController::UrlRewriter</tt> defines</p>
2492
- <div class="code_container">
2493
- <pre class="brush: ruby; gutter: false; toolbar: false">
2494
- def rewrite_path(options)
2495
- options = options.symbolize_keys
2496
- options.update(options[:params].symbolize_keys) if options[:params]
2497
- ...
2498
- end
2499
- </pre>
2500
- </div>
2501
- <p>The second line can safely access the <tt>:params</tt> key, and let the user to pass either <tt>:params</tt> or &#8220;params&#8221;.</p>
2502
- <p>There&#8217;s also the bang variant <tt>symbolize_keys!</tt> that symbolizes keys in the very receiver.</p>
2503
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
2504
- <h5 id="to_options-and-to_options">12.4.4 <tt>to_options</tt> and <tt>to_options!</tt></h5>
2505
- <p>The methods <tt>to_options</tt> and <tt>to_options!</tt> are respectively aliases of <tt>symbolize_keys</tt> and <tt>symbolize_keys!</tt>.</p>
2506
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
2507
- <h5 id="assert_valid_keys">12.4.5 <tt>assert_valid_keys</tt></h5>
2508
- <p>The method <tt>assert_valid_keys</tt> receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does <tt>ArgumentError</tt> is raised.</p>
2509
- <div class="code_container">
2510
- <pre class="brush: ruby; gutter: false; toolbar: false">
2511
- {:a =&gt; 1}.assert_valid_keys(:a) # passes
2512
- {:a =&gt; 1}.assert_valid_keys(&quot;a&quot;) # ArgumentError
2513
- </pre>
2514
- </div>
2515
- <p>Active Record does not accept unknown options when building associations for example. It implements that control via <tt>assert_valid_keys</tt>:</p>
2516
- <div class="code_container">
2517
- <pre class="brush: ruby; gutter: false; toolbar: false">
2518
- mattr_accessor :valid_keys_for_has_many_association
2519
- @@valid_keys_for_has_many_association = [
2520
- :class_name, :table_name, :foreign_key, :primary_key,
2521
- :dependent,
2522
- :select, :conditions, :include, :order, :group, :having, :limit, :offset,
2523
- :as, :through, :source, :source_type,
2524
- :uniq,
2525
- :finder_sql, :counter_sql,
2526
- :before_add, :after_add, :before_remove, :after_remove,
2527
- :extend, :readonly,
2528
- :validate, :inverse_of
2529
- ]
2530
-
2531
- def create_has_many_reflection(association_id, options, &amp;extension)
2532
- options.assert_valid_keys(valid_keys_for_has_many_association)
2533
- ...
2534
- end
2535
- </pre>
2536
- </div>
2537
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/keys.rb</tt>.</p></div>
2538
- <h4 id="slicing">12.5 Slicing</h4>
2539
- <p>Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:</p>
2540
- <div class="code_container">
2541
- <pre class="brush: ruby; gutter: false; toolbar: false">
2542
- {:a =&gt; 1, :b =&gt; 2, :c =&gt; 3}.slice(:a, :c)
2543
- # =&gt; {:c =&gt; 3, :a =&gt; 1}
2544
-
2545
- {:a =&gt; 1, :b =&gt; 2, :c =&gt; 3}.slice(:b, :X)
2546
- # =&gt; {:b =&gt; 2} # non-existing keys are ignored
2547
- </pre>
2548
- </div>
2549
- <p>If the receiver responds to <tt>convert_key</tt> keys are normalized:</p>
2550
- <div class="code_container">
2551
- <pre class="brush: ruby; gutter: false; toolbar: false">
2552
- {:a =&gt; 1, :b =&gt; 2}.with_indifferent_access.slice(&quot;a&quot;)
2553
- # =&gt; {:a =&gt; 1}
2554
- </pre>
2555
- </div>
2556
- <div class="note"><p>Slicing may come in handy for sanitizing option hashes with a white list of keys.</p></div>
2557
- <p>There&#8217;s also <tt>slice!</tt> which in addition to perform a slice in place returns what&#8217;s removed:</p>
2558
- <div class="code_container">
2559
- <pre class="brush: ruby; gutter: false; toolbar: false">
2560
- hash = {:a =&gt; 1, :b =&gt; 2}
2561
- rest = hash.slice!(:a) # =&gt; {:b =&gt; 2}
2562
- hash # =&gt; {:a =&gt; 1}
2563
- </pre>
2564
- </div>
2565
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/slice.rb</tt>.</p></div>
2566
- <h4 id="extracting">12.6 Extracting</h4>
2567
- <p>The method <tt>extract!</tt> removes and returns the key/value pairs matching the given keys.</p>
2568
- <div class="code_container">
2569
- <pre class="brush: ruby; gutter: false; toolbar: false">
2570
- hash = {:a =&gt; 1, :b =&gt; 2}
2571
- rest = hash.extract!(:a) # =&gt; {:a =&gt; 1}
2572
- hash # =&gt; {:b =&gt; 2}
2573
- </pre>
2574
- </div>
2575
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/slice.rb</tt>.</p></div>
2576
- <h4 id="indifferent-access">12.7 Indifferent Access</h4>
2577
- <p>The method <tt>with_indifferent_access</tt> returns an <tt>ActiveSupport::HashWithIndifferentAccess</tt> out of its receiver:</p>
2578
- <div class="code_container">
2579
- <pre class="brush: ruby; gutter: false; toolbar: false">
2580
- {:a =&gt; 1}.with_indifferent_access[&quot;a&quot;] # =&gt; 1
2581
- </pre>
2582
- </div>
2583
- <div class="note"><p>Defined in <tt>active_support/core_ext/hash/indifferent_access.rb</tt>.</p></div>
2584
- <h3 id="extensions-to-regexp">13 Extensions to <tt>Regexp</tt></h3>
2585
- <h4 id="multiline">13.1 <tt>multiline?</tt></h4>
2586
- <p>The method <tt>multiline?</tt> says whether a regexp has the <tt>/m</tt> flag set, that is, whether the dot matches newlines.</p>
2587
- <div class="code_container">
2588
- <pre class="brush: ruby; gutter: false; toolbar: false">
2589
- %r{.}.multiline? # =&gt; false
2590
- %r{.}m.multiline? # =&gt; true
2591
-
2592
- Regexp.new('.').multiline? # =&gt; false
2593
- Regexp.new('.', Regexp::MULTILINE).multiline? # =&gt; true
2594
- </pre>
2595
- </div>
2596
- <p>Rails uses this method in a single place, also in the routing code. Multiline regexps are disallowed for route requirements and this flag eases enforcing that constraint.</p>
2597
- <div class="code_container">
2598
- <pre class="brush: ruby; gutter: false; toolbar: false">
2599
- def assign_route_options(segments, defaults, requirements)
2600
- ...
2601
- if requirement.multiline?
2602
- raise ArgumentError, &quot;Regexp multiline option not allowed in routing requirements: #{requirement.inspect}&quot;
2603
- end
2604
- ...
2605
- end
2606
- </pre>
2607
- </div>
2608
- <div class="note"><p>Defined in <tt>active_support/core_ext/regexp.rb</tt>.</p></div>
2609
- <h3 id="extensions-to-range">14 Extensions to <tt>Range</tt></h3>
2610
- <h4 id="to_s">14.1 <tt>to_s</tt></h4>
2611
- <p>Active Support extends the method <tt>Range#to_s</tt> so that it understands an optional format argument. As of this writing the only supported non-default format is <tt>:db</tt>:</p>
2612
- <div class="code_container">
2613
- <pre class="brush: ruby; gutter: false; toolbar: false">
2614
- (Date.today..Date.tomorrow).to_s
2615
- # =&gt; &quot;2009-10-25..2009-10-26&quot;
2616
-
2617
- (Date.today..Date.tomorrow).to_s(:db)
2618
- # =&gt; &quot;BETWEEN '2009-10-25' AND '2009-10-26'&quot;
2619
- </pre>
2620
- </div>
2621
- <p>As the example depicts, the <tt>:db</tt> format generates a <tt>BETWEEN</tt> <span class="caps">SQL</span> clause. That is used by Active Record in its support for range values in conditions.</p>
2622
- <div class="note"><p>Defined in <tt>active_support/core_ext/range/conversions.rb</tt>.</p></div>
2623
- <h4 id="step">14.2 <tt>step</tt></h4>
2624
- <p>Active Support extends the method <tt>Range#step</tt> so that it can be invoked without a block:</p>
2625
- <div class="code_container">
2626
- <pre class="brush: ruby; gutter: false; toolbar: false">
2627
- (1..10).step(2) # =&gt; [1, 3, 5, 7, 9]
2628
- </pre>
2629
- </div>
2630
- <p>As the example shows, in that case the method returns an array with the corresponding elements.</p>
2631
- <div class="note"><p>Defined in <tt>active_support/core_ext/range/blockless_step.rb</tt>.</p></div>
2632
- <h4 id="include">14.3 <tt>include?</tt></h4>
2633
- <p>The method <tt>Range#include?</tt> says whether some value falls between the ends of a given instance:</p>
2634
- <div class="code_container">
2635
- <pre class="brush: ruby; gutter: false; toolbar: false">
2636
- (2..3).include?(Math::E) # =&gt; true
2637
- </pre>
2638
- </div>
2639
- <p>Active Support extends this method so that the argument may be another range in turn. In that case we test whether the ends of the argument range belong to the receiver themselves:</p>
2640
- <div class="code_container">
2641
- <pre class="brush: ruby; gutter: false; toolbar: false">
2642
- (1..10).include?(3..7) # =&gt; true
2643
- (1..10).include?(0..7) # =&gt; false
2644
- (1..10).include?(3..11) # =&gt; false
2645
- (1...9).include?(3..9) # =&gt; false
2646
- </pre>
2647
- </div>
2648
- <div class="warning"><p>The original <tt>Range#include?</tt> is still the one aliased to <tt>Range#===</tt>.</p></div>
2649
- <div class="note"><p>Defined in <tt>active_support/core_ext/range/include_range.rb</tt>.</p></div>
2650
- <h4 id="cover">14.4 <tt>cover?</tt></h4>
2651
- <p>Ruby 1.9 provides <tt>cover?</tt>, and Active Support defines it for previous versions as an alias for <tt>include?</tt>.</p>
2652
- <p>The method <tt>include?</tt> in Ruby 1.9 is different from the one in 1.8 for non-numeric ranges: instead of being based on comparisons between the value and the range&#8217;s endpoints, it walks the range with <tt>succ</tt> looking for value. This works better for ranges with holes, but it has different complexity and may not finish in some other cases.</p>
2653
- <p>In Ruby 1.9 the old behavior is still available in the new <tt>cover?</tt>, which Active Support backports for forward compatibility. For example, Rails uses <tt>cover?</tt> for ranges in <tt>validates_inclusion_of</tt>.</p>
2654
- <h4 id="overlaps">14.5 <tt>overlaps?</tt></h4>
2655
- <p>The method <tt>Range#overlaps?</tt> says whether any two given ranges have non-void intersection:</p>
2656
- <div class="code_container">
2657
- <pre class="brush: ruby; gutter: false; toolbar: false">
2658
- (1..10).overlaps?(7..11) # =&gt; true
2659
- (1..10).overlaps?(0..7) # =&gt; true
2660
- (1..10).overlaps?(11..27) # =&gt; false
2661
- </pre>
2662
- </div>
2663
- <div class="note"><p>Defined in <tt>active_support/core_ext/range/overlaps.rb</tt>.</p></div>
2664
- <h3 id="extensions-to-proc">15 Extensions to <tt>Proc</tt></h3>
2665
- <h4 id="bind">15.1 <tt>bind</tt></h4>
2666
- <p>As you surely know Ruby has an <tt>UnboundMethod</tt> class whose instances are methods that belong to the limbo of methods without a self. The method <tt>Module#instance_method</tt> returns an unbound method for example:</p>
2667
- <div class="code_container">
2668
- <pre class="brush: ruby; gutter: false; toolbar: false">
2669
- Hash.instance_method(:delete) # =&gt; #&lt;UnboundMethod: Hash#delete&gt;
2670
- </pre>
2671
- </div>
2672
- <p>An unbound method is not callable as is, you need to bind it first to an object with <tt>bind</tt>:</p>
2673
- <div class="code_container">
2674
- <pre class="brush: ruby; gutter: false; toolbar: false">
2675
- clear = Hash.instance_method(:clear)
2676
- clear.bind({:a =&gt; 1}).call # =&gt; {}
2677
- </pre>
2678
- </div>
2679
- <p>Active Support defines <tt>Proc#bind</tt> with an analogous purpose:</p>
2680
- <div class="code_container">
2681
- <pre class="brush: ruby; gutter: false; toolbar: false">
2682
- Proc.new { size }.bind([]).call # =&gt; 0
2683
- </pre>
2684
- </div>
2685
- <p>As you see that&#8217;s callable and bound to the argument, the return value is indeed a <tt>Method</tt>.</p>
2686
- <div class="note"><p>To do so <tt>Proc#bind</tt> actually creates a method under the hood. If you ever see a method with a weird name like <tt>__bind_1256598120_237302</tt> in a stack trace you know now where it comes from.</p></div>
2687
- <p>Action Pack uses this trick in <tt>rescue_from</tt> for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by <tt>handler_for_rescue</tt>, thus simplifying the code in the caller:</p>
2688
- <div class="code_container">
2689
- <pre class="brush: ruby; gutter: false; toolbar: false">
2690
- def handler_for_rescue(exception)
2691
- _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
2692
- ...
2693
- end
2694
-
2695
- case rescuer
2696
- when Symbol
2697
- method(rescuer)
2698
- when Proc
2699
- rescuer.bind(self)
2700
- end
2701
- end
2702
- </pre>
2703
- </div>
2704
- <div class="note"><p>Defined in <tt>active_support/core_ext/proc.rb</tt>.</p></div>
2705
- <h3 id="extensions-to-date">16 Extensions to <tt>Date</tt></h3>
2706
- <h4 id="calculations">16.1 Calculations</h4>
2707
- <div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/date/calculations.rb</tt>.</p></div>
2708
- <div class="info"><p>The following calculation methods have edge cases in October 1582, since days 5..14 just do not exist. This guide does not document their behavior around those days for brevity, but it is enough to say that they do what you would expect. That is, <tt>Date.new(1582, 10, 4).tomorrow</tt> returns <tt>Date.new(1582, 10, 15)</tt> and so on. Please check <tt>test/core_ext/date_ext_test.rb</tt> in the Active Support test suite for expected behavior.</p></div>
2709
- <h5 id="date-current">16.1.1 <tt>Date.current</tt></h5>
2710
- <p>Active Support defines <tt>Date.current</tt> to be today in the current time zone. That&#8217;s like <tt>Date.today</tt>, except that it honors the user time zone, if defined. It also defines <tt>Date.yesterday</tt> and <tt>Date.tomorrow</tt>, and the instance predicates <tt>past?</tt>, <tt>today?</tt>, and <tt>future?</tt>, all of them relative to <tt>Date.current</tt>.</p>
2711
- <p>When making Date comparisons using methods which honor the user time zone, make sure to use <tt>Date.current</tt> and not <tt>Date.today</tt>. There are cases where the user time zone might be in the future compared to the system time zone, which <tt>Date.today</tt> uses by default. This means <tt>Date.today</tt> may equal <tt>Date.yesterday</tt>.</p>
2712
- <h5 id="named-dates">16.1.2 Named dates</h5>
2713
- <h6 id="prev_year-next_year">16.1.2.1 <tt>prev_year</tt>, <tt>next_year</tt></h6>
2714
- <p>In Ruby 1.9 <tt>prev_year</tt> and <tt>next_year</tt> return a date with the same day/month in the last or next year:</p>
2715
- <div class="code_container">
2716
- <pre class="brush: ruby; gutter: false; toolbar: false">
2717
- d = Date.new(2010, 5, 8) # =&gt; Sat, 08 May 2010
2718
- d.prev_year # =&gt; Fri, 08 May 2009
2719
- d.next_year # =&gt; Sun, 08 May 2011
2720
- </pre>
2721
- </div>
2722
- <p>If date is the 29th of February of a leap year, you obtain the 28th:</p>
2723
- <div class="code_container">
2724
- <pre class="brush: ruby; gutter: false; toolbar: false">
2725
- d = Date.new(2000, 2, 29) # =&gt; Tue, 29 Feb 2000
2726
- d.prev_year # =&gt; Sun, 28 Feb 1999
2727
- d.next_year # =&gt; Wed, 28 Feb 2001
2728
- </pre>
2729
- </div>
2730
- <p>Active Support defines these methods as well for Ruby 1.8.</p>
2731
- <h6 id="prev_month-next_month">16.1.2.2 <tt>prev_month</tt>, <tt>next_month</tt></h6>
2732
- <p>In Ruby 1.9 <tt>prev_month</tt> and <tt>next_month</tt> return the date with the same day in the last or next month:</p>
2733
- <div class="code_container">
2734
- <pre class="brush: ruby; gutter: false; toolbar: false">
2735
- d = Date.new(2010, 5, 8) # =&gt; Sat, 08 May 2010
2736
- d.prev_month # =&gt; Thu, 08 Apr 2010
2737
- d.next_month # =&gt; Tue, 08 Jun 2010
2738
- </pre>
2739
- </div>
2740
- <p>If such a day does not exist, the last day of the corresponding month is returned:</p>
2741
- <div class="code_container">
2742
- <pre class="brush: ruby; gutter: false; toolbar: false">
2743
- Date.new(2000, 5, 31).prev_month # =&gt; Sun, 30 Apr 2000
2744
- Date.new(2000, 3, 31).prev_month # =&gt; Tue, 29 Feb 2000
2745
- Date.new(2000, 5, 31).next_month # =&gt; Fri, 30 Jun 2000
2746
- Date.new(2000, 1, 31).next_month # =&gt; Tue, 29 Feb 2000
2747
- </pre>
2748
- </div>
2749
- <p>Active Support defines these methods as well for Ruby 1.8.</p>
2750
- <h6 id="beginning_of_week-end_of_week">16.1.2.3 <tt>beginning_of_week</tt>, <tt>end_of_week</tt></h6>
2751
- <p>The methods <tt>beginning_of_week</tt> and <tt>end_of_week</tt> return the dates for the beginning and end of week, assuming weeks start on Monday:</p>
2752
- <div class="code_container">
2753
- <pre class="brush: ruby; gutter: false; toolbar: false">
2754
- d = Date.new(2010, 5, 8) # =&gt; Sat, 08 May 2010
2755
- d.beginning_of_week # =&gt; Mon, 03 May 2010
2756
- d.end_of_week # =&gt; Sun, 09 May 2010
2757
- </pre>
2758
- </div>
2759
- <p><tt>beginning_of_week</tt> is aliased to <tt>monday</tt> and <tt>at_beginning_of_week</tt>. <tt>end_of_week</tt> is aliased to <tt>sunday</tt> and <tt>at_end_of_week</tt>.</p>
2760
- <h6 id="prev_week-next_week">16.1.2.4 <tt>prev_week</tt>, <tt>next_week</tt></h6>
2761
- <p>The method <tt>next_week</tt> receives a symbol with a day name in English (in lowercase, default is <tt>:monday</tt>) and it returns the date corresponding to that day:</p>
2762
- <div class="code_container">
2763
- <pre class="brush: ruby; gutter: false; toolbar: false">
2764
- d = Date.new(2010, 5, 9) # =&gt; Sun, 09 May 2010
2765
- d.next_week # =&gt; Mon, 10 May 2010
2766
- d.next_week(:saturday) # =&gt; Sat, 15 May 2010
2767
- </pre>
2768
- </div>
2769
- <p>The method <tt>prev_week</tt> is analogous:</p>
2770
- <div class="code_container">
2771
- <pre class="brush: ruby; gutter: false; toolbar: false">
2772
- d.prev_week # =&gt; Mon, 26 Apr 2010
2773
- d.prev_week(:saturday) # =&gt; Sat, 01 May 2010
2774
- d.prev_week(:friday) # =&gt; Fri, 30 Apr 2010
2775
- </pre>
2776
- </div>
2777
- <h6 id="beginning_of_month-end_of_month">16.1.2.5 <tt>beginning_of_month</tt>, <tt>end_of_month</tt></h6>
2778
- <p>The methods <tt>beginning_of_month</tt> and <tt>end_of_month</tt> return the dates for the beginning and end of the month:</p>
2779
- <div class="code_container">
2780
- <pre class="brush: ruby; gutter: false; toolbar: false">
2781
- d = Date.new(2010, 5, 9) # =&gt; Sun, 09 May 2010
2782
- d.beginning_of_month # =&gt; Sat, 01 May 2010
2783
- d.end_of_month # =&gt; Mon, 31 May 2010
2784
- </pre>
2785
- </div>
2786
- <p><tt>beginning_of_month</tt> is aliased to <tt>at_beginning_of_month</tt>, and <tt>end_of_month</tt> is aliased to <tt>at_end_of_month</tt>.</p>
2787
- <h6 id="beginning_of_quarter-end_of_quarter">16.1.2.6 <tt>beginning_of_quarter</tt>, <tt>end_of_quarter</tt></h6>
2788
- <p>The methods <tt>beginning_of_quarter</tt> and <tt>end_of_quarter</tt> return the dates for the beginning and end of the quarter of the receiver&#8217;s calendar year:</p>
2789
- <div class="code_container">
2790
- <pre class="brush: ruby; gutter: false; toolbar: false">
2791
- d = Date.new(2010, 5, 9) # =&gt; Sun, 09 May 2010
2792
- d.beginning_of_quarter # =&gt; Thu, 01 Apr 2010
2793
- d.end_of_quarter # =&gt; Wed, 30 Jun 2010
2794
- </pre>
2795
- </div>
2796
- <p><tt>beginning_of_quarter</tt> is aliased to <tt>at_beginning_of_quarter</tt>, and <tt>end_of_quarter</tt> is aliased to <tt>at_end_of_quarter</tt>.</p>
2797
- <h6 id="beginning_of_year-end_of_year">16.1.2.7 <tt>beginning_of_year</tt>, <tt>end_of_year</tt></h6>
2798
- <p>The methods <tt>beginning_of_year</tt> and <tt>end_of_year</tt> return the dates for the beginning and end of the year:</p>
2799
- <div class="code_container">
2800
- <pre class="brush: ruby; gutter: false; toolbar: false">
2801
- d = Date.new(2010, 5, 9) # =&gt; Sun, 09 May 2010
2802
- d.beginning_of_year # =&gt; Fri, 01 Jan 2010
2803
- d.end_of_year # =&gt; Fri, 31 Dec 2010
2804
- </pre>
2805
- </div>
2806
- <p><tt>beginning_of_year</tt> is aliased to <tt>at_beginning_of_year</tt>, and <tt>end_of_year</tt> is aliased to <tt>at_end_of_year</tt>.</p>
2807
- <h5 id="other-date-computations">16.1.3 Other Date Computations</h5>
2808
- <h6 id="years_ago-years_since">16.1.3.1 <tt>years_ago</tt>, <tt>years_since</tt></h6>
2809
- <p>The method <tt>years_ago</tt> receives a number of years and returns the same date those many years ago:</p>
2810
- <div class="code_container">
2811
- <pre class="brush: ruby; gutter: false; toolbar: false">
2812
- date = Date.new(2010, 6, 7)
2813
- date.years_ago(10) # =&gt; Wed, 07 Jun 2000
2814
- </pre>
2815
- </div>
2816
- <p><tt>years_since</tt> moves forward in time:</p>
2817
- <div class="code_container">
2818
- <pre class="brush: ruby; gutter: false; toolbar: false">
2819
- date = Date.new(2010, 6, 7)
2820
- date.years_since(10) # =&gt; Sun, 07 Jun 2020
2821
- </pre>
2822
- </div>
2823
- <p>If such a day does not exist, the last day of the corresponding month is returned:</p>
2824
- <div class="code_container">
2825
- <pre class="brush: ruby; gutter: false; toolbar: false">
2826
- Date.new(2012, 2, 29).years_ago(3) # =&gt; Sat, 28 Feb 2009
2827
- Date.new(2012, 2, 29).years_since(3) # =&gt; Sat, 28 Feb 2015
2828
- </pre>
2829
- </div>
2830
- <h6 id="months_ago-months_since">16.1.3.2 <tt>months_ago</tt>, <tt>months_since</tt></h6>
2831
- <p>The methods <tt>months_ago</tt> and <tt>months_since</tt> work analogously for months:</p>
2832
- <div class="code_container">
2833
- <pre class="brush: ruby; gutter: false; toolbar: false">
2834
- Date.new(2010, 4, 30).months_ago(2) # =&gt; Sun, 28 Feb 2010
2835
- Date.new(2010, 4, 30).months_since(2) # =&gt; Wed, 30 Jun 2010
2836
- </pre>
2837
- </div>
2838
- <p>If such a day does not exist, the last day of the corresponding month is returned:</p>
2839
- <div class="code_container">
2840
- <pre class="brush: ruby; gutter: false; toolbar: false">
2841
- Date.new(2010, 4, 30).months_ago(2) # =&gt; Sun, 28 Feb 2010
2842
- Date.new(2009, 12, 31).months_since(2) # =&gt; Sun, 28 Feb 2010
2843
- </pre>
2844
- </div>
2845
- <h6 id="weeks_ago">16.1.3.3 <tt>weeks_ago</tt></h6>
2846
- <p>The method <tt>weeks_ago</tt> works analogously for weeks:</p>
2847
- <div class="code_container">
2848
- <pre class="brush: ruby; gutter: false; toolbar: false">
2849
- Date.new(2010, 5, 24).weeks_ago(1) # =&gt; Mon, 17 May 2010
2850
- Date.new(2010, 5, 24).weeks_ago(2) # =&gt; Mon, 10 May 2010
2851
- </pre>
2852
- </div>
2853
- <h6 id="advance">16.1.3.4 <tt>advance</tt></h6>
2854
- <p>The most generic way to jump to other days is <tt>advance</tt>. This method receives a hash with keys <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, and returns a date advanced as much as the present keys indicate:</p>
2855
- <div class="code_container">
2856
- <pre class="brush: ruby; gutter: false; toolbar: false">
2857
- date = Date.new(2010, 6, 6)
2858
- date.advance(:years =&gt; 1, :weeks =&gt; 2) # =&gt; Mon, 20 Jun 2011
2859
- date.advance(:months =&gt; 2, :days =&gt; -2) # =&gt; Wed, 04 Aug 2010
2860
- </pre>
2861
- </div>
2862
- <p>Note in the previous example that increments may be negative.</p>
2863
- <p>To perform the computation the method first increments years, then months, then weeks, and finally days. This order is important towards the end of months. Say for example we are at the end of February of 2010, and we want to move one month and one day forward.</p>
2864
- <p>The method <tt>advance</tt> advances first one month, and then one day, the result is:</p>
2865
- <div class="code_container">
2866
- <pre class="brush: ruby; gutter: false; toolbar: false">
2867
- Date.new(2010, 2, 28).advance(:months =&gt; 1, :days =&gt; 1)
2868
- # =&gt; Sun, 29 Mar 2010
2869
- </pre>
2870
- </div>
2871
- <p>While if it did it the other way around the result would be different:</p>
2872
- <div class="code_container">
2873
- <pre class="brush: ruby; gutter: false; toolbar: false">
2874
- Date.new(2010, 2, 28).advance(:days =&gt; 1).advance(:months =&gt; 1)
2875
- # =&gt; Thu, 01 Apr 2010
2876
- </pre>
2877
- </div>
2878
- <h5 id="changing-components">16.1.4 Changing Components</h5>
2879
- <p>The method <tt>change</tt> allows you to get a new date which is the same as the receiver except for the given year, month, or day:</p>
2880
- <div class="code_container">
2881
- <pre class="brush: ruby; gutter: false; toolbar: false">
2882
- Date.new(2010, 12, 23).change(:year =&gt; 2011, :month =&gt; 11)
2883
- # =&gt; Wed, 23 Nov 2011
2884
- </pre>
2885
- </div>
2886
- <p>This method is not tolerant to non-existing dates, if the change is invalid <tt>ArgumentError</tt> is raised:</p>
2887
- <div class="code_container">
2888
- <pre class="brush: ruby; gutter: false; toolbar: false">
2889
- Date.new(2010, 1, 31).change(:month =&gt; 2)
2890
- # =&gt; ArgumentError: invalid date
2891
- </pre>
2892
- </div>
2893
- <h5 id="date-durations">16.1.5 Durations</h5>
2894
- <p>Durations can be added to and subtracted from dates:</p>
2895
- <div class="code_container">
2896
- <pre class="brush: ruby; gutter: false; toolbar: false">
2897
- d = Date.current
2898
- # =&gt; Mon, 09 Aug 2010
2899
- d + 1.year
2900
- # =&gt; Tue, 09 Aug 2011
2901
- d - 3.hours
2902
- # =&gt; Sun, 08 Aug 2010 21:00:00 UTC +00:00
2903
- </pre>
2904
- </div>
2905
- <p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
2906
- <div class="code_container">
2907
- <pre class="brush: ruby; gutter: false; toolbar: false">
2908
- Date.new(1582, 10, 4) + 1.day
2909
- # =&gt; Fri, 15 Oct 1582
2910
- </pre>
2911
- </div>
2912
- <h5 id="timestamps">16.1.6 Timestamps</h5>
2913
- <div class="info"><p>The following methods return a <tt>Time</tt> object if possible, otherwise a <tt>DateTime</tt>. If set, they honor the user time zone.</p></div>
2914
- <h6 id="beginning_of_day-end_of_day">16.1.6.1 <tt>beginning_of_day</tt>, <tt>end_of_day</tt></h6>
2915
- <p>The method <tt>beginning_of_day</tt> returns a timestamp at the beginning of the day (00:00:00):</p>
2916
- <div class="code_container">
2917
- <pre class="brush: ruby; gutter: false; toolbar: false">
2918
- date = Date.new(2010, 6, 7)
2919
- date.beginning_of_day # =&gt; Sun Jun 07 00:00:00 +0200 2010
2920
- </pre>
2921
- </div>
2922
- <p>The method <tt>end_of_day</tt> returns a timestamp at the end of the day (23:59:59):</p>
2923
- <div class="code_container">
2924
- <pre class="brush: ruby; gutter: false; toolbar: false">
2925
- date = Date.new(2010, 6, 7)
2926
- date.end_of_day # =&gt; Sun Jun 06 23:59:59 +0200 2010
2927
- </pre>
2928
- </div>
2929
- <p><tt>beginning_of_day</tt> is aliased to <tt>at_beginning_of_day</tt>, <tt>midnight</tt>, <tt>at_midnight</tt>.</p>
2930
- <h6 id="ago-since">16.1.6.2 <tt>ago</tt>, <tt>since</tt></h6>
2931
- <p>The method <tt>ago</tt> receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:</p>
2932
- <div class="code_container">
2933
- <pre class="brush: ruby; gutter: false; toolbar: false">
2934
- date = Date.current # =&gt; Fri, 11 Jun 2010
2935
- date.ago(1) # =&gt; Thu, 10 Jun 2010 23:59:59 EDT -04:00
2936
- </pre>
2937
- </div>
2938
- <p>Similarly, <tt>since</tt> moves forward:</p>
2939
- <div class="code_container">
2940
- <pre class="brush: ruby; gutter: false; toolbar: false">
2941
- date = Date.current # =&gt; Fri, 11 Jun 2010
2942
- date.since(1) # =&gt; Fri, 11 Jun 2010 00:00:01 EDT -04:00
2943
- </pre>
2944
- </div>
2945
- <h5 id="other-time-computations">16.1.7 Other Time Computations</h5>
2946
- <h4 id="date-conversions">16.2 Conversions</h4>
2947
- <h3 id="extensions-to-datetime">17 Extensions to <tt>DateTime</tt></h3>
2948
- <div class="warning"><p><tt>DateTime</tt> is not aware of <span class="caps">DST</span> rules and so some of these methods have edge cases when a <span class="caps">DST</span> change is going on. For example <tt>seconds_since_midnight</tt> might not return the real amount in such a day.</p></div>
2949
- <h4 id="calculations-datetime">17.1 Calculations</h4>
2950
- <div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/date_time/calculations.rb</tt>.</p></div>
2951
- <p>The class <tt>DateTime</tt> is a subclass of <tt>Date</tt> so by loading <tt>active_support/core_ext/date/calculations.rb</tt> you inherit these methods and their aliases, except that they will always return datetimes:</p>
2952
- <div class="code_container">
2953
- <pre class="brush: ruby; gutter: false; toolbar: false">
2954
- yesterday
2955
- tomorrow
2956
- beginning_of_week (monday, at_beginning_of_week)
2957
- end_on_week (at_end_of_week)
2958
- weeks_ago
2959
- prev_week
2960
- next_week
2961
- months_ago
2962
- months_since
2963
- beginning_of_month (at_beginning_of_month)
2964
- end_of_month (at_end_of_month)
2965
- prev_month
2966
- next_month
2967
- beginning_of_quarter (at_beginning_of_quarter)
2968
- end_of_quarter (at_end_of_quarter)
2969
- beginning_of_year (at_beginning_of_year)
2970
- end_of_year (at_end_of_year)
2971
- years_ago
2972
- years_since
2973
- prev_year
2974
- next_year
2975
- </pre>
2976
- </div>
2977
- <p>The following methods are reimplemented so you do <strong>not</strong> need to load <tt>active_support/core_ext/date/calculations.rb</tt> for these ones:</p>
2978
- <div class="code_container">
2979
- <pre class="brush: ruby; gutter: false; toolbar: false">
2980
- beginning_of_day (midnight, at_midnight, at_beginning_of_day)
2981
- end_of_day
2982
- ago
2983
- since (in)
2984
- </pre>
2985
- </div>
2986
- <p>On the other hand, <tt>advance</tt> and <tt>change</tt> are also defined and support more options, they are documented below.</p>
2987
- <h5 id="named-datetimes">17.1.1 Named Datetimes</h5>
2988
- <h6 id="datetime-current">17.1.1.1 <tt>DateTime.current</tt></h6>
2989
- <p>Active Support defines <tt>DateTime.current</tt> to be like <tt>Time.now.to_datetime</tt>, except that it honors the user time zone, if defined. It also defines <tt>DateTime.yesterday</tt> and <tt>DateTime.tomorrow</tt>, and the instance predicates <tt>past?</tt>, and <tt>future?</tt> relative to <tt>DateTime.current</tt>.</p>
2990
- <h5 id="other-extensions">17.1.2 Other Extensions</h5>
2991
- <h6 id="seconds_since_midnight">17.1.2.1 <tt>seconds_since_midnight</tt></h6>
2992
- <p>The method <tt>seconds_since_midnight</tt> returns the number of seconds since midnight:</p>
2993
- <div class="code_container">
2994
- <pre class="brush: ruby; gutter: false; toolbar: false">
2995
- now = DateTime.current # =&gt; Mon, 07 Jun 2010 20:26:36 +0000
2996
- now.seconds_since_midnight # =&gt; 73596
2997
- </pre>
2998
- </div>
2999
- <h6 id="utc-datetime">17.1.2.2 <tt>utc</tt></h6>
3000
- <p>The method <tt>utc</tt> gives you the same datetime in the receiver expressed in <span class="caps">UTC</span>.</p>
3001
- <div class="code_container">
3002
- <pre class="brush: ruby; gutter: false; toolbar: false">
3003
- now = DateTime.current # =&gt; Mon, 07 Jun 2010 19:27:52 -0400
3004
- now.utc # =&gt; Mon, 07 Jun 2010 23:27:52 +0000
3005
- </pre>
3006
- </div>
3007
- <p>This method is also aliased as <tt>getutc</tt>.</p>
3008
- <h6 id="utc">17.1.2.3 <tt>utc?</tt></h6>
3009
- <p>The predicate <tt>utc?</tt> says whether the receiver has <span class="caps">UTC</span> as its time zone:</p>
3010
- <div class="code_container">
3011
- <pre class="brush: ruby; gutter: false; toolbar: false">
3012
- now = DateTime.now # =&gt; Mon, 07 Jun 2010 19:30:47 -0400
3013
- now.utc? # =&gt; false
3014
- now.utc.utc? # =&gt; true
3015
- </pre>
3016
- </div>
3017
- <h6 id="datetime-advance">17.1.2.4 <tt>advance</tt></h6>
3018
- <p>The most generic way to jump to another datetime is <tt>advance</tt>. This method receives a hash with keys <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <tt>:minutes</tt>, and <tt>:seconds</tt>, and returns a datetime advanced as much as the present keys indicate.</p>
3019
- <div class="code_container">
3020
- <pre class="brush: ruby; gutter: false; toolbar: false">
3021
- d = DateTime.current
3022
- # =&gt; Thu, 05 Aug 2010 11:33:31 +0000
3023
- d.advance(:years =&gt; 1, :months =&gt; 1, :days =&gt; 1, :hours =&gt; 1, :minutes =&gt; 1, :seconds =&gt; 1)
3024
- # =&gt; Tue, 06 Sep 2011 12:34:32 +0000
3025
- </pre>
3026
- </div>
3027
- <p>This method first computes the destination date passing <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, and <tt>:days</tt> to <tt>Date#advance</tt> documented above. After that, it adjusts the time calling <tt>since</tt> with the number of seconds to advance. This order is relevant, a different ordering would give different datetimes in some edge-cases. The example in <tt>Date#advance</tt> applies, and we can extend it to show order relevance related to the time bits.</p>
3028
- <p>If we first move the date bits (that have also a relative order of processing, as documented before), and then the time bits we get for example the following computation:</p>
3029
- <div class="code_container">
3030
- <pre class="brush: ruby; gutter: false; toolbar: false">
3031
- d = DateTime.new(2010, 2, 28, 23, 59, 59)
3032
- # =&gt; Sun, 28 Feb 2010 23:59:59 +0000
3033
- d.advance(:months =&gt; 1, :seconds =&gt; 1)
3034
- # =&gt; Mon, 29 Mar 2010 00:00:00 +0000
3035
- </pre>
3036
- </div>
3037
- <p>but if we computed them the other way around, the result would be different:</p>
3038
- <div class="code_container">
3039
- <pre class="brush: ruby; gutter: false; toolbar: false">
3040
- d.advance(:seconds =&gt; 1).advance(:months =&gt; 1)
3041
- # =&gt; Thu, 01 Apr 2010 00:00:00 +0000
3042
- </pre>
3043
- </div>
3044
- <div class="warning"><p>Since <tt>DateTime</tt> is not <span class="caps">DST</span>-aware you can end up in a non-existing point in time with no warning or error telling you so.</p></div>
3045
- <h5 id="datetime-changing-components">17.1.3 Changing Components</h5>
3046
- <p>The method <tt>change</tt> allows you to get a new datetime which is the same as the receiver except for the given options, which may include <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, <tt>:sec</tt>, <tt>:offset</tt>, <tt>:start</tt>:</p>
3047
- <div class="code_container">
3048
- <pre class="brush: ruby; gutter: false; toolbar: false">
3049
- now = DateTime.current
3050
- # =&gt; Tue, 08 Jun 2010 01:56:22 +0000
3051
- now.change(:year =&gt; 2011, :offset =&gt; Rational(-6, 24))
3052
- # =&gt; Wed, 08 Jun 2011 01:56:22 -0600
3053
- </pre>
3054
- </div>
3055
- <p>If hours are zeroed, then minutes and seconds are too (unless they have given values):</p>
3056
- <div class="code_container">
3057
- <pre class="brush: ruby; gutter: false; toolbar: false">
3058
- now.change(:hour =&gt; 0)
3059
- # =&gt; Tue, 08 Jun 2010 00:00:00 +0000
3060
- </pre>
3061
- </div>
3062
- <p>Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):</p>
3063
- <div class="code_container">
3064
- <pre class="brush: ruby; gutter: false; toolbar: false">
3065
- now.change(:min =&gt; 0)
3066
- # =&gt; Tue, 08 Jun 2010 01:00:00 +0000
3067
- </pre>
3068
- </div>
3069
- <p>This method is not tolerant to non-existing dates, if the change is invalid <tt>ArgumentError</tt> is raised:</p>
3070
- <div class="code_container">
3071
- <pre class="brush: ruby; gutter: false; toolbar: false">
3072
- DateTime.current.change(:month =&gt; 2, :day =&gt; 30)
3073
- # =&gt; ArgumentError: invalid date
3074
- </pre>
3075
- </div>
3076
- <h5 id="datetime-durations">17.1.4 Durations</h5>
3077
- <p>Durations can be added to and subtracted from datetimes:</p>
3078
- <div class="code_container">
3079
- <pre class="brush: ruby; gutter: false; toolbar: false">
3080
- now = DateTime.current
3081
- # =&gt; Mon, 09 Aug 2010 23:15:17 +0000
3082
- now + 1.year
3083
- # =&gt; Tue, 09 Aug 2011 23:15:17 +0000
3084
- now - 1.week
3085
- # =&gt; Mon, 02 Aug 2010 23:15:17 +0000
3086
- </pre>
3087
- </div>
3088
- <p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
3089
- <div class="code_container">
3090
- <pre class="brush: ruby; gutter: false; toolbar: false">
3091
- DateTime.new(1582, 10, 4, 23) + 1.hour
3092
- # =&gt; Fri, 15 Oct 1582 00:00:00 +0000
3093
- </pre>
3094
- </div>
3095
- <h3 id="extensions-to-time">18 Extensions to <tt>Time</tt></h3>
3096
- <h4 id="time-calculations">18.1 Calculations</h4>
3097
- <div class="note"><p>All the following methods are defined in <tt>active_support/core_ext/time/calculations.rb</tt>.</p></div>
3098
- <p>Active Support adds to <tt>Time</tt> many of the methods available for <tt>DateTime</tt>:</p>
3099
- <div class="code_container">
3100
- <pre class="brush: ruby; gutter: false; toolbar: false">
3101
- past?
3102
- today?
3103
- future?
3104
- yesterday
3105
- tomorrow
3106
- seconds_since_midnight
3107
- change
3108
- advance
3109
- ago
3110
- since (in)
3111
- beginning_of_day (midnight, at_midnight, at_beginning_of_day)
3112
- end_of_day
3113
- beginning_of_week (monday, at_beginning_of_week)
3114
- end_on_week (at_end_of_week)
3115
- weeks_ago
3116
- prev_week
3117
- next_week
3118
- months_ago
3119
- months_since
3120
- beginning_of_month (at_beginning_of_month)
3121
- end_of_month (at_end_of_month)
3122
- prev_month
3123
- next_month
3124
- beginning_of_quarter (at_beginning_of_quarter)
3125
- end_of_quarter (at_end_of_quarter)
3126
- beginning_of_year (at_beginning_of_year)
3127
- end_of_year (at_end_of_year)
3128
- years_ago
3129
- years_since
3130
- prev_year
3131
- next_year
3132
- </pre>
3133
- </div>
3134
- <p>They are analogous. Please refer to their documentation above and take into account the following differences:</p>
3135
- <ul>
3136
- <li><tt>change</tt> accepts an additional <tt>:usec</tt> option.</li>
3137
- <li><tt>Time</tt> understands <span class="caps">DST</span>, so you get correct <span class="caps">DST</span> calculations as in</li>
3138
- </ul>
3139
- <div class="code_container">
3140
- <pre class="brush: ruby; gutter: false; toolbar: false">
3141
- Time.zone_default
3142
- # =&gt; #&lt;ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name=&quot;Madrid&quot;, ...&gt;
3143
-
3144
- # In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
3145
- t = Time.local_time(2010, 3, 28, 1, 59, 59)
3146
- # =&gt; Sun Mar 28 01:59:59 +0100 2010
3147
- t.advance(:seconds =&gt; 1)
3148
- # =&gt; Sun Mar 28 03:00:00 +0200 2010
3149
- </pre>
3150
- </div>
3151
- <ul>
3152
- <li>If <tt>since</tt> or <tt>ago</tt> jump to a time that can&#8217;t be expressed with <tt>Time</tt> a <tt>DateTime</tt> object is returned instead.</li>
3153
- </ul>
3154
- <h5 id="time-current">18.1.1 <tt>Time.current</tt></h5>
3155
- <p>Active Support defines <tt>Time.current</tt> to be today in the current time zone. That&#8217;s like <tt>Time.now</tt>, except that it honors the user time zone, if defined. It also defines <tt>Time.yesterday</tt> and <tt>Time.tomorrow</tt>, and the instance predicates <tt>past?</tt>, <tt>today?</tt>, and <tt>future?</tt>, all of them relative to <tt>Time.current</tt>.</p>
3156
- <p>When making Time comparisons using methods which honor the user time zone, make sure to use <tt>Time.current</tt> and not <tt>Time.now</tt>. There are cases where the user time zone might be in the future compared to the system time zone, which <tt>Time.today</tt> uses by default. This means <tt>Time.now</tt> may equal <tt>Time.yesterday</tt>.</p>
3157
- <h5 id="all_day-all_week-all_month-all_quarter-and-all_year">18.1.2 <tt>all_day</tt>, <tt>all_week</tt>, <tt>all_month</tt>, <tt>all_quarter</tt> and <tt>all_year</tt></h5>
3158
- <p>The method <tt>all_day</tt> returns a range representing the whole day of the current time.</p>
3159
- <div class="code_container">
3160
- <pre class="brush: ruby; gutter: false; toolbar: false">
3161
- now = Time.current
3162
- # =&gt; Mon, 09 Aug 2010 23:20:05 UTC +00:00
3163
- now.all_day
3164
- # =&gt; Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
3165
- </pre>
3166
- </div>
3167
- <p>Analogously, <tt>all_week</tt>, <tt>all_month</tt>, <tt>all_quarter</tt> and <tt>all_year</tt> all serve the purpose of generating time ranges.</p>
3168
- <div class="code_container">
3169
- <pre class="brush: ruby; gutter: false; toolbar: false">
3170
- now = Time.current
3171
- # =&gt; Mon, 09 Aug 2010 23:20:05 UTC +00:00
3172
- now.all_week
3173
- # =&gt; Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
3174
- now.all_month
3175
- # =&gt; Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
3176
- now.all_quarter
3177
- # =&gt; Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
3178
- now.all_year
3179
- # =&gt; Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
3180
- </pre>
3181
- </div>
3182
- <h4 id="time-constructors">18.2 Time Constructors</h4>
3183
- <p>Active Support defines <tt>Time.current</tt> to be <tt>Time.zone.now</tt> if there&#8217;s a user time zone defined, with fallback to <tt>Time.now</tt>:</p>
3184
- <div class="code_container">
3185
- <pre class="brush: ruby; gutter: false; toolbar: false">
3186
- Time.zone_default
3187
- # =&gt; #&lt;ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name=&quot;Madrid&quot;, ...&gt;
3188
- Time.current
3189
- # =&gt; Fri, 06 Aug 2010 17:11:58 CEST +02:00
3190
- </pre>
3191
- </div>
3192
- <p>Analogously to <tt>DateTime</tt>, the predicates <tt>past?</tt>, and <tt>future?</tt> are relative to <tt>Time.current</tt>.</p>
3193
- <p>Use the <tt>local_time</tt> class method to create time objects honoring the user time zone:</p>
3194
- <div class="code_container">
3195
- <pre class="brush: ruby; gutter: false; toolbar: false">
3196
- Time.zone_default
3197
- # =&gt; #&lt;ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name=&quot;Madrid&quot;, ...&gt;
3198
- Time.local_time(2010, 8, 15)
3199
- # =&gt; Sun Aug 15 00:00:00 +0200 2010
3200
- </pre>
3201
- </div>
3202
- <p>The <tt>utc_time</tt> class method returns a time in <span class="caps">UTC</span>:</p>
3203
- <div class="code_container">
3204
- <pre class="brush: ruby; gutter: false; toolbar: false">
3205
- Time.zone_default
3206
- # =&gt; #&lt;ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name=&quot;Madrid&quot;, ...&gt;
3207
- Time.utc_time(2010, 8, 15)
3208
- # =&gt; Sun Aug 15 00:00:00 UTC 2010
3209
- </pre>
3210
- </div>
3211
- <p>Both <tt>local_time</tt> and <tt>utc_time</tt> accept up to seven positional arguments: year, month, day, hour, min, sec, usec. Year is mandatory, month and day default to 1, and the rest default to 0.</p>
3212
- <p>If the time to be constructed lies beyond the range supported by <tt>Time</tt> in the runtime platform, usecs are discarded and a <tt>DateTime</tt> object is returned instead.</p>
3213
- <h5 id="time-durations">18.2.1 Durations</h5>
3214
- <p>Durations can be added to and subtracted from time objects:</p>
3215
- <div class="code_container">
3216
- <pre class="brush: ruby; gutter: false; toolbar: false">
3217
- now = Time.current
3218
- # =&gt; Mon, 09 Aug 2010 23:20:05 UTC +00:00
3219
- now + 1.year
3220
- # =&gt; Tue, 09 Aug 2011 23:21:11 UTC +00:00
3221
- now - 1.week
3222
- # =&gt; Mon, 02 Aug 2010 23:21:11 UTC +00:00
3223
- </pre>
3224
- </div>
3225
- <p>They translate to calls to <tt>since</tt> or <tt>advance</tt>. For example here we get the correct jump in the calendar reform:</p>
3226
- <div class="code_container">
3227
- <pre class="brush: ruby; gutter: false; toolbar: false">
3228
- Time.utc_time(1582, 10, 3) + 5.days
3229
- # =&gt; Mon Oct 18 00:00:00 UTC 1582
3230
- </pre>
3231
- </div>
3232
- <h3 id="extensions-to-process">19 Extensions to <tt>Process</tt></h3>
3233
- <h4 id="daemon">19.1 <tt>daemon</tt></h4>
3234
- <p>Ruby 1.9 provides <tt>Process.daemon</tt>, and Active Support defines it for previous versions. It accepts the same two arguments, whether it should chdir to the root directory (default, true), and whether it should inherit the standard file descriptors from the parent (default, false).</p>
3235
- <h3 id="extensions-to-file">20 Extensions to <tt>File</tt></h3>
3236
- <h4 id="atomic_write">20.1 <tt>atomic_write</tt></h4>
3237
- <p>With the class method <tt>File.atomic_write</tt> you can write to a file in a way that will prevent any reader from seeing half-written content.</p>
3238
- <p>The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done <tt>atomic_write</tt> closes the file handle and completes its job.</p>
3239
- <p>For example, Action Pack uses this method to write asset cache files like <tt>all.css</tt>:</p>
3240
- <div class="code_container">
3241
- <pre class="brush: ruby; gutter: false; toolbar: false">
3242
- File.atomic_write(joined_asset_path) do |cache|
3243
- cache.write(join_asset_file_contents(asset_paths))
3244
- end
3245
- </pre>
3246
- </div>
3247
- <p>To accomplish this <tt>atomic_write</tt> creates a temporary file. That&#8217;s the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on <span class="caps">POSIX</span> systems. If the target file exists <tt>atomic_write</tt> overwrites it and keeps owners and permissions.</p>
3248
- <div class="warning"><p>Note you can&#8217;t append with <tt>atomic_write</tt>.</p></div>
3249
- <p>The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.</p>
3250
- <div class="note"><p>Defined in <tt>active_support/core_ext/file/atomic.rb</tt>.</p></div>
3251
- <h3 id="extensions-to-logger">21 Extensions to <tt>Logger</tt></h3>
3252
- <h4 id="around_-level">21.1 <tt>around_[level]</tt></h4>
3253
- <p>Takes two arguments, a <tt>before_message</tt> and <tt>after_message</tt> and calls the current level method on the <tt>Logger</tt> instance, passing in the <tt>before_message</tt>, then the specified message, then the <tt>after_message</tt>:</p>
3254
- <div class="code_container">
3255
- <pre class="brush: ruby; gutter: false; toolbar: false">
3256
- logger = Logger.new(&quot;log/development.log&quot;)
3257
- logger.around_info(&quot;before&quot;, &quot;after&quot;) { |logger| logger.info(&quot;during&quot;) }
3258
- </pre>
3259
- </div>
3260
- <h4 id="silence">21.2 <tt>silence</tt></h4>
3261
- <p>Silences every log level lesser to the specified one for the duration of the given block. Log level orders are: debug, info, error and fatal.</p>
3262
- <div class="code_container">
3263
- <pre class="brush: ruby; gutter: false; toolbar: false">
3264
- logger = Logger.new(&quot;log/development.log&quot;)
3265
- logger.silence(Logger::INFO) do
3266
- logger.debug(&quot;In space, no one can hear you scream.&quot;)
3267
- logger.info(&quot;Scream all you want, small mailman!&quot;)
3268
- end
3269
- </pre>
3270
- </div>
3271
- <h4 id="datetime_format">21.3 <tt>datetime_format=</tt></h4>
3272
- <p>Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a <tt>datetime_format</tt> method then this is ignored.</p>
3273
- <div class="code_container">
3274
- <pre class="brush: ruby; gutter: false; toolbar: false">
3275
- class Logger::FormatWithTime &lt; Logger::Formatter
3276
- cattr_accessor(:datetime_format) { &quot;%Y%m%d%H%m%S&quot; }
3277
-
3278
- def self.call(severity, timestamp, progname, msg)
3279
- &quot;#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n&quot;
3280
- end
3281
- end
3282
-
3283
- logger = Logger.new(&quot;log/development.log&quot;)
3284
- logger.formatter = Logger::FormatWithTime
3285
- logger.info(&quot;&lt;- is the current time&quot;)
3286
- </pre>
3287
- </div>
3288
- <div class="note"><p>Defined in <tt>active_support/core_ext/logger.rb</tt>.</p></div>
3289
- <h3 id="extensions-to-nameerror">22 Extensions to <tt>NameError</tt></h3>
3290
- <p>Active Support adds <tt>missing_name?</tt> to <tt>NameError</tt>, which tests whether the exception was raised because of the name passed as argument.</p>
3291
- <p>The name may be given as a symbol or string. A symbol is tested against the bare constant name, a string is against the fully-qualified constant name.</p>
3292
- <div class="info"><p>A symbol can represent a fully-qualified constant name as in <tt>:"ActiveRecord::Base"</tt>, so the behavior for symbols is defined for convenience, not because it has to be that way technically.</p></div>
3293
- <p>For example, when an action of <tt>PostsController</tt> is called Rails tries optimistically to use <tt>PostsHelper</tt>. It is OK that the helper module does not exist, so if an exception for that constant name is raised it should be silenced. But it could be the case that <tt>posts_helper.rb</tt> raises a <tt>NameError</tt> due to an actual unknown constant. That should be reraised. The method <tt>missing_name?</tt> provides a way to distinguish both cases:</p>
3294
- <div class="code_container">
3295
- <pre class="brush: ruby; gutter: false; toolbar: false">
3296
- def default_helper_module!
3297
- module_name = name.sub(/Controller$/, '')
3298
- module_path = module_name.underscore
3299
- helper module_path
3300
- rescue MissingSourceFile =&gt; e
3301
- raise e unless e.is_missing? &quot;#{module_path}_helper&quot;
3302
- rescue NameError =&gt; e
3303
- raise e unless e.missing_name? &quot;#{module_name}Helper&quot;
3304
- end
3305
- </pre>
3306
- </div>
3307
- <div class="note"><p>Defined in <tt>active_support/core_ext/name_error.rb</tt>.</p></div>
3308
- <h3 id="extensions-to-loaderror">23 Extensions to <tt>LoadError</tt></h3>
3309
- <p>Active Support adds <tt>is_missing?</tt> to <tt>LoadError</tt>, and also assigns that class to the constant <tt>MissingSourceFile</tt> for backwards compatibility.</p>
3310
- <p>Given a path name <tt>is_missing?</tt> tests whether the exception was raised due to that particular file (except perhaps for the &#8220;.rb&#8221; extension).</p>
3311
- <p>For example, when an action of <tt>PostsController</tt> is called Rails tries to load <tt>posts_helper.rb</tt>, but that file may not exist. That&#8217;s fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method <tt>is_missing?</tt> provides a way to distinguish both cases:</p>
3312
- <div class="code_container">
3313
- <pre class="brush: ruby; gutter: false; toolbar: false">
3314
- def default_helper_module!
3315
- module_name = name.sub(/Controller$/, '')
3316
- module_path = module_name.underscore
3317
- helper module_path
3318
- rescue MissingSourceFile =&gt; e
3319
- raise e unless e.is_missing? &quot;helpers/#{module_path}_helper&quot;
3320
- rescue NameError =&gt; e
3321
- raise e unless e.missing_name? &quot;#{module_name}Helper&quot;
3322
- end
3323
- </pre>
3324
- </div>
3325
- <div class="note"><p>Defined in <tt>active_support/core_ext/load_error.rb</tt>.</p></div>
3326
-
3327
- <h3>Feedback</h3>
3328
- <p>
3329
- You're encouraged to help improve the quality of this guide.
3330
- </p>
3331
- <p>
3332
- If you see any typos or factual errors you are confident to
3333
- patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
3334
- and push the change yourself. That branch of Rails has public write access.
3335
- Commits are still reviewed, but that happens after you've submitted your
3336
- contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
3337
- cross-merged with master periodically.
3338
- </p>
3339
- <p>
3340
- You may also find incomplete content, or stuff that is not up to date.
3341
- Please do add any missing documentation for master. Check the
3342
- <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
3343
- for style and conventions.
3344
- </p>
3345
- <p>
3346
- If for whatever reason you spot something to fix but cannot patch it yourself, please
3347
- <a href="https://github.com/rails/rails/issues">open an issue</a>.
3348
- </p>
3349
- <p>And last but not least, any kind of discussion regarding Ruby on Rails
3350
- documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
3351
- </p>
3352
- </div>
3353
- </div>
3354
- </div>
3355
-
3356
- <hr class="hide" />
3357
- <div id="footer">
3358
- <div class="wrapper">
3359
- <p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
3360
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
3361
- </div>
3362
- </div>
3363
-
3364
- <script type="text/javascript" src="javascripts/guides.js"></script>
3365
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
3366
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
3367
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
3368
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
3369
- <script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
3370
- <script type="text/javascript">
3371
- SyntaxHighlighter.all()
3372
- </script>
3373
- </body>
3374
- </html>