rails_test 4.2.0.beta1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (215) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +83 -0
  3. data/guides/CHANGELOG.md +27 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/akshaysurve.jpg +0 -0
  6. data/guides/assets/images/belongs_to.png +0 -0
  7. data/guides/assets/images/book_icon.gif +0 -0
  8. data/guides/assets/images/bullet.gif +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  19. data/guides/assets/images/getting_started/challenge.png +0 -0
  20. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  21. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  22. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  23. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  24. data/guides/assets/images/getting_started/new_article.png +0 -0
  25. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  26. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  28. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  29. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  32. data/guides/assets/images/grey_bullet.gif +0 -0
  33. data/guides/assets/images/habtm.png +0 -0
  34. data/guides/assets/images/has_many.png +0 -0
  35. data/guides/assets/images/has_many_through.png +0 -0
  36. data/guides/assets/images/has_one.png +0 -0
  37. data/guides/assets/images/has_one_through.png +0 -0
  38. data/guides/assets/images/header_backdrop.png +0 -0
  39. data/guides/assets/images/header_tile.gif +0 -0
  40. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  41. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/assets/images/icons/README +5 -0
  47. data/guides/assets/images/icons/callouts/1.png +0 -0
  48. data/guides/assets/images/icons/callouts/10.png +0 -0
  49. data/guides/assets/images/icons/callouts/11.png +0 -0
  50. data/guides/assets/images/icons/callouts/12.png +0 -0
  51. data/guides/assets/images/icons/callouts/13.png +0 -0
  52. data/guides/assets/images/icons/callouts/14.png +0 -0
  53. data/guides/assets/images/icons/callouts/15.png +0 -0
  54. data/guides/assets/images/icons/callouts/2.png +0 -0
  55. data/guides/assets/images/icons/callouts/3.png +0 -0
  56. data/guides/assets/images/icons/callouts/4.png +0 -0
  57. data/guides/assets/images/icons/callouts/5.png +0 -0
  58. data/guides/assets/images/icons/callouts/6.png +0 -0
  59. data/guides/assets/images/icons/callouts/7.png +0 -0
  60. data/guides/assets/images/icons/callouts/8.png +0 -0
  61. data/guides/assets/images/icons/callouts/9.png +0 -0
  62. data/guides/assets/images/icons/caution.png +0 -0
  63. data/guides/assets/images/icons/example.png +0 -0
  64. data/guides/assets/images/icons/home.png +0 -0
  65. data/guides/assets/images/icons/important.png +0 -0
  66. data/guides/assets/images/icons/next.png +0 -0
  67. data/guides/assets/images/icons/note.png +0 -0
  68. data/guides/assets/images/icons/prev.png +0 -0
  69. data/guides/assets/images/icons/tip.png +0 -0
  70. data/guides/assets/images/icons/up.png +0 -0
  71. data/guides/assets/images/icons/warning.png +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/session_fixation.png +0 -0
  81. data/guides/assets/images/tab_grey.gif +0 -0
  82. data/guides/assets/images/tab_info.gif +0 -0
  83. data/guides/assets/images/tab_note.gif +0 -0
  84. data/guides/assets/images/tab_red.gif +0 -0
  85. data/guides/assets/images/tab_yellow.gif +0 -0
  86. data/guides/assets/images/tab_yellow.png +0 -0
  87. data/guides/assets/images/vijaydev.jpg +0 -0
  88. data/guides/assets/javascripts/guides.js +59 -0
  89. data/guides/assets/javascripts/jquery.min.js +4 -0
  90. data/guides/assets/javascripts/responsive-tables.js +43 -0
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  117. data/guides/assets/stylesheets/fixes.css +16 -0
  118. data/guides/assets/stylesheets/kindle.css +11 -0
  119. data/guides/assets/stylesheets/main.css +713 -0
  120. data/guides/assets/stylesheets/print.css +52 -0
  121. data/guides/assets/stylesheets/reset.css +43 -0
  122. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  123. data/guides/assets/stylesheets/style.css +13 -0
  124. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  142. data/guides/bug_report_templates/action_controller_gem.rb +47 -0
  143. data/guides/bug_report_templates/action_controller_master.rb +56 -0
  144. data/guides/bug_report_templates/active_record_gem.rb +40 -0
  145. data/guides/bug_report_templates/active_record_master.rb +51 -0
  146. data/guides/rails_guides.rb +63 -0
  147. data/guides/rails_guides/generator.rb +248 -0
  148. data/guides/rails_guides/helpers.rb +53 -0
  149. data/guides/rails_guides/indexer.rb +68 -0
  150. data/guides/rails_guides/kindle.rb +119 -0
  151. data/guides/rails_guides/levenshtein.rb +39 -0
  152. data/guides/rails_guides/markdown.rb +167 -0
  153. data/guides/rails_guides/markdown/renderer.rb +82 -0
  154. data/guides/source/2_2_release_notes.md +435 -0
  155. data/guides/source/2_3_release_notes.md +621 -0
  156. data/guides/source/3_0_release_notes.md +611 -0
  157. data/guides/source/3_1_release_notes.md +559 -0
  158. data/guides/source/3_2_release_notes.md +568 -0
  159. data/guides/source/4_0_release_notes.md +279 -0
  160. data/guides/source/4_1_release_notes.md +730 -0
  161. data/guides/source/4_2_release_notes.md +736 -0
  162. data/guides/source/_license.html.erb +2 -0
  163. data/guides/source/_welcome.html.erb +19 -0
  164. data/guides/source/action_controller_overview.md +1247 -0
  165. data/guides/source/action_mailer_basics.md +738 -0
  166. data/guides/source/action_view_overview.md +1621 -0
  167. data/guides/source/active_job_basics.md +285 -0
  168. data/guides/source/active_model_basics.md +223 -0
  169. data/guides/source/active_record_basics.md +374 -0
  170. data/guides/source/active_record_callbacks.md +413 -0
  171. data/guides/source/active_record_migrations.md +1016 -0
  172. data/guides/source/active_record_postgresql.md +438 -0
  173. data/guides/source/active_record_querying.md +1785 -0
  174. data/guides/source/active_record_validations.md +1169 -0
  175. data/guides/source/active_support_core_extensions.md +3924 -0
  176. data/guides/source/active_support_instrumentation.md +497 -0
  177. data/guides/source/api_documentation_guidelines.md +361 -0
  178. data/guides/source/asset_pipeline.md +1361 -0
  179. data/guides/source/association_basics.md +2238 -0
  180. data/guides/source/caching_with_rails.md +379 -0
  181. data/guides/source/command_line.md +634 -0
  182. data/guides/source/configuring.md +1019 -0
  183. data/guides/source/contributing_to_ruby_on_rails.md +607 -0
  184. data/guides/source/credits.html.erb +80 -0
  185. data/guides/source/debugging_rails_applications.md +861 -0
  186. data/guides/source/development_dependencies_install.md +289 -0
  187. data/guides/source/documents.yaml +197 -0
  188. data/guides/source/engines.md +1401 -0
  189. data/guides/source/form_helpers.md +1010 -0
  190. data/guides/source/generators.md +676 -0
  191. data/guides/source/getting_started.md +2085 -0
  192. data/guides/source/i18n.md +1073 -0
  193. data/guides/source/index.html.erb +28 -0
  194. data/guides/source/initialization.md +704 -0
  195. data/guides/source/kindle/copyright.html.erb +1 -0
  196. data/guides/source/kindle/layout.html.erb +27 -0
  197. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  198. data/guides/source/kindle/toc.html.erb +24 -0
  199. data/guides/source/kindle/toc.ncx.erb +64 -0
  200. data/guides/source/kindle/welcome.html.erb +5 -0
  201. data/guides/source/layout.html.erb +143 -0
  202. data/guides/source/layouts_and_rendering.md +1227 -0
  203. data/guides/source/maintenance_policy.md +75 -0
  204. data/guides/source/nested_model_forms.md +228 -0
  205. data/guides/source/plugins.md +444 -0
  206. data/guides/source/rails_application_templates.md +266 -0
  207. data/guides/source/rails_on_rack.md +332 -0
  208. data/guides/source/routing.md +1141 -0
  209. data/guides/source/ruby_on_rails_guides_guidelines.md +126 -0
  210. data/guides/source/security.md +1024 -0
  211. data/guides/source/testing.md +1055 -0
  212. data/guides/source/upgrading_ruby_on_rails.md +1046 -0
  213. data/guides/source/working_with_javascript_in_rails.md +407 -0
  214. data/guides/w3c_validator.rb +97 -0
  215. metadata +404 -0
@@ -0,0 +1,3924 @@
1
+ Active Support Core Extensions
2
+ ==============================
3
+
4
+ Active Support is the Ruby on Rails component responsible for providing Ruby language extensions, utilities, and other transversal stuff.
5
+
6
+ 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.
7
+
8
+ After reading this guide, you will know:
9
+
10
+ * What Core Extensions are.
11
+ * How to load all extensions.
12
+ * How to cherry-pick just the extensions you want.
13
+ * What extensions Active Support provides.
14
+
15
+ --------------------------------------------------------------------------------
16
+
17
+ How to Load Core Extensions
18
+ ---------------------------
19
+
20
+ ### Stand-Alone Active Support
21
+
22
+ In order to have a near-zero default footprint, Active Support does not load anything by default. It is broken in small pieces so that you can load just what you need, and also has some convenience entry points to load related extensions in one shot, even everything.
23
+
24
+ Thus, after a simple require like:
25
+
26
+ ```ruby
27
+ require 'active_support'
28
+ ```
29
+
30
+ objects do not even respond to `blank?`. Let's see how to load its definition.
31
+
32
+ #### Cherry-picking a Definition
33
+
34
+ The most lightweight way to get `blank?` is to cherry-pick the file that defines it.
35
+
36
+ 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 `blank?` the note reads:
37
+
38
+ NOTE: Defined in `active_support/core_ext/object/blank.rb`.
39
+
40
+ That means that you can require it like this:
41
+
42
+ ```ruby
43
+ require 'active_support'
44
+ require 'active_support/core_ext/object/blank'
45
+ ```
46
+
47
+ Active Support has been carefully revised so that cherry-picking a file loads only strictly needed dependencies, if any.
48
+
49
+ #### Loading Grouped Core Extensions
50
+
51
+ The next level is to simply load all extensions to `Object`. As a rule of thumb, extensions to `SomeClass` are available in one shot by loading `active_support/core_ext/some_class`.
52
+
53
+ Thus, to load all extensions to `Object` (including `blank?`):
54
+
55
+ ```ruby
56
+ require 'active_support'
57
+ require 'active_support/core_ext/object'
58
+ ```
59
+
60
+ #### Loading All Core Extensions
61
+
62
+ You may prefer just to load all core extensions, there is a file for that:
63
+
64
+ ```ruby
65
+ require 'active_support'
66
+ require 'active_support/core_ext'
67
+ ```
68
+
69
+ #### Loading All Active Support
70
+
71
+ And finally, if you want to have all Active Support available just issue:
72
+
73
+ ```ruby
74
+ require 'active_support/all'
75
+ ```
76
+
77
+ That does not even put the entire Active Support in memory upfront indeed, some stuff is configured via `autoload`, so it is only loaded if used.
78
+
79
+ ### Active Support Within a Ruby on Rails Application
80
+
81
+ A Ruby on Rails application loads all Active Support unless `config.active_support.bare` 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.
82
+
83
+ Extensions to All Objects
84
+ -------------------------
85
+
86
+ ### `blank?` and `present?`
87
+
88
+ The following values are considered to be blank in a Rails application:
89
+
90
+ * `nil` and `false`,
91
+
92
+ * strings composed only of whitespace (see note below),
93
+
94
+ * empty arrays and hashes, and
95
+
96
+ * any other object that responds to `empty?` and is empty.
97
+
98
+ INFO: The predicate for strings uses the Unicode-aware character class `[:space:]`, so for example U+2029 (paragraph separator) is considered to be whitespace.
99
+
100
+ WARNING: Note that numbers are not mentioned. In particular, 0 and 0.0 are **not** blank.
101
+
102
+ For example, this method from `ActionController::HttpAuthentication::Token::ControllerMethods` uses `blank?` for checking whether a token is present:
103
+
104
+ ```ruby
105
+ def authenticate(controller, &login_procedure)
106
+ token, options = token_and_options(controller.request)
107
+ unless token.blank?
108
+ login_procedure.call(token, options)
109
+ end
110
+ end
111
+ ```
112
+
113
+ The method `present?` is equivalent to `!blank?`. This example is taken from `ActionDispatch::Http::Cache::Response`:
114
+
115
+ ```ruby
116
+ def set_conditional_cache_control!
117
+ return if self["Cache-Control"].present?
118
+ ...
119
+ end
120
+ ```
121
+
122
+ NOTE: Defined in `active_support/core_ext/object/blank.rb`.
123
+
124
+ ### `presence`
125
+
126
+ The `presence` method returns its receiver if `present?`, and `nil` otherwise. It is useful for idioms like this:
127
+
128
+ ```ruby
129
+ host = config[:host].presence || 'localhost'
130
+ ```
131
+
132
+ NOTE: Defined in `active_support/core_ext/object/blank.rb`.
133
+
134
+ ### `duplicable?`
135
+
136
+ 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:
137
+
138
+ ```ruby
139
+ 1.object_id # => 3
140
+ Math.cos(0).to_i.object_id # => 3
141
+ ```
142
+
143
+ Hence, there's no way these objects can be duplicated through `dup` or `clone`:
144
+
145
+ ```ruby
146
+ true.dup # => TypeError: can't dup TrueClass
147
+ ```
148
+
149
+ Some numbers which are not singletons are not duplicable either:
150
+
151
+ ```ruby
152
+ 0.0.clone # => allocator undefined for Float
153
+ (2**1024).clone # => allocator undefined for Bignum
154
+ ```
155
+
156
+ Active Support provides `duplicable?` to programmatically query an object about this property:
157
+
158
+ ```ruby
159
+ "foo".duplicable? # => true
160
+ "".duplicable? # => true
161
+ 0.0.duplicable? # => false
162
+ false.duplicable? # => false
163
+ ```
164
+
165
+ By definition all objects are `duplicable?` except `nil`, `false`, `true`, symbols, numbers, class, and module objects.
166
+
167
+ WARNING: Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case.
168
+
169
+ NOTE: Defined in `active_support/core_ext/object/duplicable.rb`.
170
+
171
+ ### `deep_dup`
172
+
173
+ The `deep_dup` method returns deep copy of a given object. Normally, when you `dup` an object that contains other objects, Ruby does not `dup` them, so it creates a shallow copy of the object. If you have an array with a string, for example, it will look like this:
174
+
175
+ ```ruby
176
+ array = ['string']
177
+ duplicate = array.dup
178
+
179
+ duplicate.push 'another-string'
180
+
181
+ # the object was duplicated, so the element was added only to the duplicate
182
+ array # => ['string']
183
+ duplicate # => ['string', 'another-string']
184
+
185
+ duplicate.first.gsub!('string', 'foo')
186
+
187
+ # first element was not duplicated, it will be changed in both arrays
188
+ array # => ['foo']
189
+ duplicate # => ['foo', 'another-string']
190
+ ```
191
+
192
+ As you can see, after duplicating the `Array` instance, we got another object, therefore we can modify it and the original object will stay unchanged. This is not true for array's elements, however. Since `dup` does not make deep copy, the string inside the array is still the same object.
193
+
194
+ If you need a deep copy of an object, you should use `deep_dup`. Here is an example:
195
+
196
+ ```ruby
197
+ array = ['string']
198
+ duplicate = array.deep_dup
199
+
200
+ duplicate.first.gsub!('string', 'foo')
201
+
202
+ array # => ['string']
203
+ duplicate # => ['foo']
204
+ ```
205
+
206
+ If the object is not duplicable, `deep_dup` will just return it:
207
+
208
+ ```ruby
209
+ number = 1
210
+ duplicate = number.deep_dup
211
+ number.object_id == duplicate.object_id # => true
212
+ ```
213
+
214
+ NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
215
+
216
+ ### `try`
217
+
218
+ When you want to call a method on an object only if it is not `nil`, the simplest way to achieve it is with conditional statements, adding unnecessary clutter. The alternative is to use `try`. `try` is like `Object#send` except that it returns `nil` if sent to `nil`.
219
+
220
+ Here is an example:
221
+
222
+ ```ruby
223
+ # without try
224
+ unless @number.nil?
225
+ @number.next
226
+ end
227
+
228
+ # with try
229
+ @number.try(:next)
230
+ ```
231
+
232
+ Another example is this code from `ActiveRecord::ConnectionAdapters::AbstractAdapter` where `@logger` could be `nil`. You can see that the code uses `try` and avoids an unnecessary check.
233
+
234
+ ```ruby
235
+ def log_info(sql, name, ms)
236
+ if @logger.try(:debug?)
237
+ name = '%s (%.1fms)' % [name || 'SQL', ms]
238
+ @logger.debug(format_log_entry(name, sql.squeeze(' ')))
239
+ end
240
+ end
241
+ ```
242
+
243
+ `try` can also be called without arguments but a block, which will only be executed if the object is not nil:
244
+
245
+ ```ruby
246
+ @person.try { |p| "#{p.first_name} #{p.last_name}" }
247
+ ```
248
+
249
+ NOTE: Defined in `active_support/core_ext/object/try.rb`.
250
+
251
+ ### `class_eval(*args, &block)`
252
+
253
+ You can evaluate code in the context of any object's singleton class using `class_eval`:
254
+
255
+ ```ruby
256
+ class Proc
257
+ def bind(object)
258
+ block, time = self, Time.current
259
+ object.class_eval do
260
+ method_name = "__bind_#{time.to_i}_#{time.usec}"
261
+ define_method(method_name, &block)
262
+ method = instance_method(method_name)
263
+ remove_method(method_name)
264
+ method
265
+ end.bind(object)
266
+ end
267
+ end
268
+ ```
269
+
270
+ NOTE: Defined in `active_support/core_ext/kernel/singleton_class.rb`.
271
+
272
+ ### `acts_like?(duck)`
273
+
274
+ The method `acts_like?` provides a way to check whether some class acts like some other class based on a simple convention: a class that provides the same interface as `String` defines
275
+
276
+ ```ruby
277
+ def acts_like_string?
278
+ end
279
+ ```
280
+
281
+ which is only a marker, its body or return value are irrelevant. Then, client code can query for duck-type-safeness this way:
282
+
283
+ ```ruby
284
+ some_klass.acts_like?(:string)
285
+ ```
286
+
287
+ Rails has classes that act like `Date` or `Time` and follow this contract.
288
+
289
+ NOTE: Defined in `active_support/core_ext/object/acts_like.rb`.
290
+
291
+ ### `to_param`
292
+
293
+ All objects in Rails respond to the method `to_param`, which is meant to return something that represents them as values in a query string, or as URL fragments.
294
+
295
+ By default `to_param` just calls `to_s`:
296
+
297
+ ```ruby
298
+ 7.to_param # => "7"
299
+ ```
300
+
301
+ The return value of `to_param` should **not** be escaped:
302
+
303
+ ```ruby
304
+ "Tom & Jerry".to_param # => "Tom & Jerry"
305
+ ```
306
+
307
+ Several classes in Rails overwrite this method.
308
+
309
+ For example `nil`, `true`, and `false` return themselves. `Array#to_param` calls `to_param` on the elements and joins the result with "/":
310
+
311
+ ```ruby
312
+ [0, true, String].to_param # => "0/true/String"
313
+ ```
314
+
315
+ Notably, the Rails routing system calls `to_param` on models to get a value for the `:id` placeholder. `ActiveRecord::Base#to_param` returns the `id` of a model, but you can redefine that method in your models. For example, given
316
+
317
+ ```ruby
318
+ class User
319
+ def to_param
320
+ "#{id}-#{name.parameterize}"
321
+ end
322
+ end
323
+ ```
324
+
325
+ we get:
326
+
327
+ ```ruby
328
+ user_path(@user) # => "/users/357-john-smith"
329
+ ```
330
+
331
+ WARNING. Controllers need to be aware of any redefinition of `to_param` because when a request like that comes in "357-john-smith" is the value of `params[:id]`.
332
+
333
+ NOTE: Defined in `active_support/core_ext/object/to_param.rb`.
334
+
335
+ ### `to_query`
336
+
337
+ Except for hashes, given an unescaped `key` this method constructs the part of a query string that would map such key to what `to_param` returns. For example, given
338
+
339
+ ```ruby
340
+ class User
341
+ def to_param
342
+ "#{id}-#{name.parameterize}"
343
+ end
344
+ end
345
+ ```
346
+
347
+ we get:
348
+
349
+ ```ruby
350
+ current_user.to_query('user') # => user=357-john-smith
351
+ ```
352
+
353
+ This method escapes whatever is needed, both for the key and the value:
354
+
355
+ ```ruby
356
+ account.to_query('company[name]')
357
+ # => "company%5Bname%5D=Johnson+%26+Johnson"
358
+ ```
359
+
360
+ so its output is ready to be used in a query string.
361
+
362
+ Arrays return the result of applying `to_query` to each element with `_key_[]` as key, and join the result with "&":
363
+
364
+ ```ruby
365
+ [3.4, -45.6].to_query('sample')
366
+ # => "sample%5B%5D=3.4&sample%5B%5D=-45.6"
367
+ ```
368
+
369
+ Hashes also respond to `to_query` but with a different signature. If no argument is passed a call generates a sorted series of key/value assignments calling `to_query(key)` on its values. Then it joins the result with "&":
370
+
371
+ ```ruby
372
+ {c: 3, b: 2, a: 1}.to_query # => "a=1&b=2&c=3"
373
+ ```
374
+
375
+ The method `Hash#to_query` accepts an optional namespace for the keys:
376
+
377
+ ```ruby
378
+ {id: 89, name: "John Smith"}.to_query('user')
379
+ # => "user%5Bid%5D=89&user%5Bname%5D=John+Smith"
380
+ ```
381
+
382
+ NOTE: Defined in `active_support/core_ext/object/to_query.rb`.
383
+
384
+ ### `with_options`
385
+
386
+ The method `with_options` provides a way to factor out common options in a series of method calls.
387
+
388
+ Given a default options hash, `with_options` yields a proxy object to a block. Within the block, methods called on the proxy are forwarded to the receiver with their options merged. For example, you get rid of the duplication in:
389
+
390
+ ```ruby
391
+ class Account < ActiveRecord::Base
392
+ has_many :customers, dependent: :destroy
393
+ has_many :products, dependent: :destroy
394
+ has_many :invoices, dependent: :destroy
395
+ has_many :expenses, dependent: :destroy
396
+ end
397
+ ```
398
+
399
+ this way:
400
+
401
+ ```ruby
402
+ class Account < ActiveRecord::Base
403
+ with_options dependent: :destroy do |assoc|
404
+ assoc.has_many :customers
405
+ assoc.has_many :products
406
+ assoc.has_many :invoices
407
+ assoc.has_many :expenses
408
+ end
409
+ end
410
+ ```
411
+
412
+ That idiom may convey _grouping_ to the reader as well. For example, say you want to send a newsletter whose language depends on the user. Somewhere in the mailer you could group locale-dependent bits like this:
413
+
414
+ ```ruby
415
+ I18n.with_options locale: user.locale, scope: "newsletter" do |i18n|
416
+ subject i18n.t :subject
417
+ body i18n.t :body, user_name: user.name
418
+ end
419
+ ```
420
+
421
+ TIP: Since `with_options` forwards calls to its receiver they can be nested. Each nesting level will merge inherited defaults in addition to their own.
422
+
423
+ NOTE: Defined in `active_support/core_ext/object/with_options.rb`.
424
+
425
+ ### JSON support
426
+
427
+ Active Support provides a better implementation of `to_json` than the `json` gem ordinarily provides for Ruby objects. This is because some classes, like `Hash`, `OrderedHash` and `Process::Status` need special handling in order to provide a proper JSON representation.
428
+
429
+ NOTE: Defined in `active_support/core_ext/object/json.rb`.
430
+
431
+ ### Instance Variables
432
+
433
+ Active Support provides several methods to ease access to instance variables.
434
+
435
+ #### `instance_values`
436
+
437
+ The method `instance_values` returns a hash that maps instance variable names without "@" to their
438
+ corresponding values. Keys are strings:
439
+
440
+ ```ruby
441
+ class C
442
+ def initialize(x, y)
443
+ @x, @y = x, y
444
+ end
445
+ end
446
+
447
+ C.new(0, 1).instance_values # => {"x" => 0, "y" => 1}
448
+ ```
449
+
450
+ NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
451
+
452
+ #### `instance_variable_names`
453
+
454
+ The method `instance_variable_names` returns an array. Each name includes the "@" sign.
455
+
456
+ ```ruby
457
+ class C
458
+ def initialize(x, y)
459
+ @x, @y = x, y
460
+ end
461
+ end
462
+
463
+ C.new(0, 1).instance_variable_names # => ["@x", "@y"]
464
+ ```
465
+
466
+ NOTE: Defined in `active_support/core_ext/object/instance_variables.rb`.
467
+
468
+ ### Silencing Warnings, Streams, and Exceptions
469
+
470
+ The methods `silence_warnings` and `enable_warnings` change the value of `$VERBOSE` accordingly for the duration of their block, and reset it afterwards:
471
+
472
+ ```ruby
473
+ silence_warnings { Object.const_set "RAILS_DEFAULT_LOGGER", logger }
474
+ ```
475
+
476
+ You can silence any stream while a block runs with `silence_stream`:
477
+
478
+ ```ruby
479
+ silence_stream(STDOUT) do
480
+ # STDOUT is silent here
481
+ end
482
+ ```
483
+
484
+ The `quietly` method addresses the common use case where you want to silence STDOUT and STDERR, even in subprocesses:
485
+
486
+ ```ruby
487
+ quietly { system 'bundle install' }
488
+ ```
489
+
490
+ 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.
491
+
492
+ Silencing exceptions is also possible with `suppress`. This method receives an arbitrary number of exception classes. If an exception is raised during the execution of the block and is `kind_of?` any of the arguments, `suppress` captures it and returns silently. Otherwise the exception is reraised:
493
+
494
+ ```ruby
495
+ # If the user is locked the increment is lost, no big deal.
496
+ suppress(ActiveRecord::StaleObjectError) do
497
+ current_user.increment! :visits
498
+ end
499
+ ```
500
+
501
+ NOTE: Defined in `active_support/core_ext/kernel/reporting.rb`.
502
+
503
+ ### `in?`
504
+
505
+ The predicate `in?` tests if an object is included in another object. An `ArgumentError` exception will be raised if the argument passed does not respond to `include?`.
506
+
507
+ Examples of `in?`:
508
+
509
+ ```ruby
510
+ 1.in?([1,2]) # => true
511
+ "lo".in?("hello") # => true
512
+ 25.in?(30..50) # => false
513
+ 1.in?(1) # => ArgumentError
514
+ ```
515
+
516
+ NOTE: Defined in `active_support/core_ext/object/inclusion.rb`.
517
+
518
+ Extensions to `Module`
519
+ ----------------------
520
+
521
+ ### `alias_method_chain`
522
+
523
+ Using plain Ruby you can wrap methods with other methods, that's called _alias chaining_.
524
+
525
+ For example, let's say you'd like params to be strings in functional tests, as they are in real requests, but still want the convenience of assigning integers and other kind of values. To accomplish that you could wrap `ActionController::TestCase#process` this way in `test/test_helper.rb`:
526
+
527
+ ```ruby
528
+ ActionController::TestCase.class_eval do
529
+ # save a reference to the original process method
530
+ alias_method :original_process, :process
531
+
532
+ # now redefine process and delegate to original_process
533
+ def process(action, params=nil, session=nil, flash=nil, http_method='GET')
534
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
535
+ original_process(action, params, session, flash, http_method)
536
+ end
537
+ end
538
+ ```
539
+
540
+ That's the method `get`, `post`, etc., delegate the work to.
541
+
542
+ That technique has a risk, it could be the case that `:original_process` was taken. To try to avoid collisions people choose some label that characterizes what the chaining is about:
543
+
544
+ ```ruby
545
+ ActionController::TestCase.class_eval do
546
+ def process_with_stringified_params(...)
547
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
548
+ process_without_stringified_params(action, params, session, flash, http_method)
549
+ end
550
+ alias_method :process_without_stringified_params, :process
551
+ alias_method :process, :process_with_stringified_params
552
+ end
553
+ ```
554
+
555
+ The method `alias_method_chain` provides a shortcut for that pattern:
556
+
557
+ ```ruby
558
+ ActionController::TestCase.class_eval do
559
+ def process_with_stringified_params(...)
560
+ params = Hash[*params.map {|k, v| [k, v.to_s]}.flatten]
561
+ process_without_stringified_params(action, params, session, flash, http_method)
562
+ end
563
+ alias_method_chain :process, :stringified_params
564
+ end
565
+ ```
566
+
567
+ Rails uses `alias_method_chain` all over the code base. For example validations are added to `ActiveRecord::Base#save` by wrapping the method that way in a separate module specialized in validations.
568
+
569
+ NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
570
+
571
+ ### Attributes
572
+
573
+ #### `alias_attribute`
574
+
575
+ Model attributes have a reader, a writer, and a predicate. You can alias a model attribute having the corresponding three methods defined for you in one shot. As in other aliasing methods, the new name is the first argument, and the old name is the second (one mnemonic is that they go in the same order as if you did an assignment):
576
+
577
+ ```ruby
578
+ class User < ActiveRecord::Base
579
+ # You can refer to the email column as "login".
580
+ # This can be meaningful for authentication code.
581
+ alias_attribute :login, :email
582
+ end
583
+ ```
584
+
585
+ NOTE: Defined in `active_support/core_ext/module/aliasing.rb`.
586
+
587
+ #### Internal Attributes
588
+
589
+ When you are defining an attribute in a class that is meant to be subclassed, name collisions are a risk. That's remarkably important for libraries.
590
+
591
+ Active Support defines the macros `attr_internal_reader`, `attr_internal_writer`, and `attr_internal_accessor`. They behave like their Ruby built-in `attr_*` counterparts, except they name the underlying instance variable in a way that makes collisions less likely.
592
+
593
+ The macro `attr_internal` is a synonym for `attr_internal_accessor`:
594
+
595
+ ```ruby
596
+ # library
597
+ class ThirdPartyLibrary::Crawler
598
+ attr_internal :log_level
599
+ end
600
+
601
+ # client code
602
+ class MyCrawler < ThirdPartyLibrary::Crawler
603
+ attr_accessor :log_level
604
+ end
605
+ ```
606
+
607
+ In the previous example it could be the case that `:log_level` 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 `:log_level`. Thanks to `attr_internal` there's no collision.
608
+
609
+ By default the internal instance variable is named with a leading underscore, `@_log_level` in the example above. That's configurable via `Module.attr_internal_naming_format` though, you can pass any `sprintf`-like format string with a leading `@` and a `%s` somewhere, which is where the name will be placed. The default is `"@_%s"`.
610
+
611
+ Rails uses internal attributes in a few spots, for examples for views:
612
+
613
+ ```ruby
614
+ module ActionView
615
+ class Base
616
+ attr_internal :captures
617
+ attr_internal :request, :layout
618
+ attr_internal :controller, :template
619
+ end
620
+ end
621
+ ```
622
+
623
+ NOTE: Defined in `active_support/core_ext/module/attr_internal.rb`.
624
+
625
+ #### Module Attributes
626
+
627
+ The macros `mattr_reader`, `mattr_writer`, and `mattr_accessor` are the same as the `cattr_*` macros defined for class. In fact, the `cattr_*` macros are just aliases for the `mattr_*` macros. Check [Class Attributes](#class-attributes).
628
+
629
+ For example, the dependencies mechanism uses them:
630
+
631
+ ```ruby
632
+ module ActiveSupport
633
+ module Dependencies
634
+ mattr_accessor :warnings_on_first_load
635
+ mattr_accessor :history
636
+ mattr_accessor :loaded
637
+ mattr_accessor :mechanism
638
+ mattr_accessor :load_paths
639
+ mattr_accessor :load_once_paths
640
+ mattr_accessor :autoloaded_constants
641
+ mattr_accessor :explicitly_unloadable_constants
642
+ mattr_accessor :logger
643
+ mattr_accessor :log_activity
644
+ mattr_accessor :constant_watch_stack
645
+ mattr_accessor :constant_watch_stack_mutex
646
+ end
647
+ end
648
+ ```
649
+
650
+ NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`.
651
+
652
+ ### Parents
653
+
654
+ #### `parent`
655
+
656
+ The `parent` method on a nested named module returns the module that contains its corresponding constant:
657
+
658
+ ```ruby
659
+ module X
660
+ module Y
661
+ module Z
662
+ end
663
+ end
664
+ end
665
+ M = X::Y::Z
666
+
667
+ X::Y::Z.parent # => X::Y
668
+ M.parent # => X::Y
669
+ ```
670
+
671
+ If the module is anonymous or belongs to the top-level, `parent` returns `Object`.
672
+
673
+ WARNING: Note that in that case `parent_name` returns `nil`.
674
+
675
+ NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
676
+
677
+ #### `parent_name`
678
+
679
+ The `parent_name` method on a nested named module returns the fully-qualified name of the module that contains its corresponding constant:
680
+
681
+ ```ruby
682
+ module X
683
+ module Y
684
+ module Z
685
+ end
686
+ end
687
+ end
688
+ M = X::Y::Z
689
+
690
+ X::Y::Z.parent_name # => "X::Y"
691
+ M.parent_name # => "X::Y"
692
+ ```
693
+
694
+ For top-level or anonymous modules `parent_name` returns `nil`.
695
+
696
+ WARNING: Note that in that case `parent` returns `Object`.
697
+
698
+ NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
699
+
700
+ #### `parents`
701
+
702
+ The method `parents` calls `parent` on the receiver and upwards until `Object` is reached. The chain is returned in an array, from bottom to top:
703
+
704
+ ```ruby
705
+ module X
706
+ module Y
707
+ module Z
708
+ end
709
+ end
710
+ end
711
+ M = X::Y::Z
712
+
713
+ X::Y::Z.parents # => [X::Y, X, Object]
714
+ M.parents # => [X::Y, X, Object]
715
+ ```
716
+
717
+ NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
718
+
719
+ ### Constants
720
+
721
+ The method `local_constants` returns the names of the constants that have been
722
+ defined in the receiver module:
723
+
724
+ ```ruby
725
+ module X
726
+ X1 = 1
727
+ X2 = 2
728
+ module Y
729
+ Y1 = :y1
730
+ X1 = :overrides_X1_above
731
+ end
732
+ end
733
+
734
+ X.local_constants # => [:X1, :X2, :Y]
735
+ X::Y.local_constants # => [:Y1, :X1]
736
+ ```
737
+
738
+ The names are returned as symbols.
739
+
740
+ NOTE: Defined in `active_support/core_ext/module/introspection.rb`.
741
+
742
+ #### Qualified Constant Names
743
+
744
+ The standard methods `const_defined?`, `const_get` , and `const_set` accept
745
+ bare constant names. Active Support extends this API to be able to pass
746
+ relative qualified constant names.
747
+
748
+ The new methods are `qualified_const_defined?`, `qualified_const_get`, and
749
+ `qualified_const_set`. Their arguments are assumed to be qualified constant
750
+ names relative to their receiver:
751
+
752
+ ```ruby
753
+ Object.qualified_const_defined?("Math::PI") # => true
754
+ Object.qualified_const_get("Math::PI") # => 3.141592653589793
755
+ Object.qualified_const_set("Math::Phi", 1.618034) # => 1.618034
756
+ ```
757
+
758
+ Arguments may be bare constant names:
759
+
760
+ ```ruby
761
+ Math.qualified_const_get("E") # => 2.718281828459045
762
+ ```
763
+
764
+ These methods are analogous to their built-in counterparts. In particular,
765
+ `qualified_constant_defined?` accepts an optional second argument to be
766
+ able to say whether you want the predicate to look in the ancestors.
767
+ This flag is taken into account for each constant in the expression while
768
+ walking down the path.
769
+
770
+ For example, given
771
+
772
+ ```ruby
773
+ module M
774
+ X = 1
775
+ end
776
+
777
+ module N
778
+ class C
779
+ include M
780
+ end
781
+ end
782
+ ```
783
+
784
+ `qualified_const_defined?` behaves this way:
785
+
786
+ ```ruby
787
+ N.qualified_const_defined?("C::X", false) # => false
788
+ N.qualified_const_defined?("C::X", true) # => true
789
+ N.qualified_const_defined?("C::X") # => true
790
+ ```
791
+
792
+ As the last example implies, the second argument defaults to true,
793
+ as in `const_defined?`.
794
+
795
+ For coherence with the built-in methods only relative paths are accepted.
796
+ Absolute qualified constant names like `::Math::PI` raise `NameError`.
797
+
798
+ NOTE: Defined in `active_support/core_ext/module/qualified_const.rb`.
799
+
800
+ ### Reachable
801
+
802
+ A named module is reachable if it is stored in its corresponding constant. It means you can reach the module object via the constant.
803
+
804
+ That is what ordinarily happens, if a module is called "M", the `M` constant exists and holds it:
805
+
806
+ ```ruby
807
+ module M
808
+ end
809
+
810
+ M.reachable? # => true
811
+ ```
812
+
813
+ But since constants and modules are indeed kind of decoupled, module objects can become unreachable:
814
+
815
+ ```ruby
816
+ module M
817
+ end
818
+
819
+ orphan = Object.send(:remove_const, :M)
820
+
821
+ # The module object is orphan now but it still has a name.
822
+ orphan.name # => "M"
823
+
824
+ # You cannot reach it via the constant M because it does not even exist.
825
+ orphan.reachable? # => false
826
+
827
+ # Let's define a module called "M" again.
828
+ module M
829
+ end
830
+
831
+ # The constant M exists now again, and it stores a module
832
+ # object called "M", but it is a new instance.
833
+ orphan.reachable? # => false
834
+ ```
835
+
836
+ NOTE: Defined in `active_support/core_ext/module/reachable.rb`.
837
+
838
+ ### Anonymous
839
+
840
+ A module may or may not have a name:
841
+
842
+ ```ruby
843
+ module M
844
+ end
845
+ M.name # => "M"
846
+
847
+ N = Module.new
848
+ N.name # => "N"
849
+
850
+ Module.new.name # => nil
851
+ ```
852
+
853
+ You can check whether a module has a name with the predicate `anonymous?`:
854
+
855
+ ```ruby
856
+ module M
857
+ end
858
+ M.anonymous? # => false
859
+
860
+ Module.new.anonymous? # => true
861
+ ```
862
+
863
+ Note that being unreachable does not imply being anonymous:
864
+
865
+ ```ruby
866
+ module M
867
+ end
868
+
869
+ m = Object.send(:remove_const, :M)
870
+
871
+ m.reachable? # => false
872
+ m.anonymous? # => false
873
+ ```
874
+
875
+ though an anonymous module is unreachable by definition.
876
+
877
+ NOTE: Defined in `active_support/core_ext/module/anonymous.rb`.
878
+
879
+ ### Method Delegation
880
+
881
+ The macro `delegate` offers an easy way to forward methods.
882
+
883
+ Let's imagine that users in some application have login information in the `User` model but name and other data in a separate `Profile` model:
884
+
885
+ ```ruby
886
+ class User < ActiveRecord::Base
887
+ has_one :profile
888
+ end
889
+ ```
890
+
891
+ With that configuration you get a user's name via their profile, `user.profile.name`, but it could be handy to still be able to access such attribute directly:
892
+
893
+ ```ruby
894
+ class User < ActiveRecord::Base
895
+ has_one :profile
896
+
897
+ def name
898
+ profile.name
899
+ end
900
+ end
901
+ ```
902
+
903
+ That is what `delegate` does for you:
904
+
905
+ ```ruby
906
+ class User < ActiveRecord::Base
907
+ has_one :profile
908
+
909
+ delegate :name, to: :profile
910
+ end
911
+ ```
912
+
913
+ It is shorter, and the intention more obvious.
914
+
915
+ The method must be public in the target.
916
+
917
+ The `delegate` macro accepts several methods:
918
+
919
+ ```ruby
920
+ delegate :name, :age, :address, :twitter, to: :profile
921
+ ```
922
+
923
+ When interpolated into a string, the `:to` 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:
924
+
925
+ ```ruby
926
+ # delegates to the Rails constant
927
+ delegate :logger, to: :Rails
928
+
929
+ # delegates to the receiver's class
930
+ delegate :table_name, to: :class
931
+ ```
932
+
933
+ WARNING: If the `:prefix` option is `true` this is less generic, see below.
934
+
935
+ By default, if the delegation raises `NoMethodError` and the target is `nil` the exception is propagated. You can ask that `nil` is returned instead with the `:allow_nil` option:
936
+
937
+ ```ruby
938
+ delegate :name, to: :profile, allow_nil: true
939
+ ```
940
+
941
+ With `:allow_nil` the call `user.name` returns `nil` if the user has no profile.
942
+
943
+ The option `:prefix` adds a prefix to the name of the generated method. This may be handy for example to get a better name:
944
+
945
+ ```ruby
946
+ delegate :street, to: :address, prefix: true
947
+ ```
948
+
949
+ The previous example generates `address_street` rather than `street`.
950
+
951
+ WARNING: Since in this case the name of the generated method is composed of the target object and target method names, the `:to` option must be a method name.
952
+
953
+ A custom prefix may also be configured:
954
+
955
+ ```ruby
956
+ delegate :size, to: :attachment, prefix: :avatar
957
+ ```
958
+
959
+ In the previous example the macro generates `avatar_size` rather than `size`.
960
+
961
+ NOTE: Defined in `active_support/core_ext/module/delegation.rb`
962
+
963
+ ### Redefining Methods
964
+
965
+ There are cases where you need to define a method with `define_method`, but don't know whether a method with that name already exists. If it does, a warning is issued if they are enabled. No big deal, but not clean either.
966
+
967
+ The method `redefine_method` prevents such a potential warning, removing the existing method before if needed.
968
+
969
+ NOTE: Defined in `active_support/core_ext/module/remove_method.rb`
970
+
971
+ Extensions to `Class`
972
+ ---------------------
973
+
974
+ ### Class Attributes
975
+
976
+ #### `class_attribute`
977
+
978
+ The method `class_attribute` declares one or more inheritable class attributes that can be overridden at any level down the hierarchy.
979
+
980
+ ```ruby
981
+ class A
982
+ class_attribute :x
983
+ end
984
+
985
+ class B < A; end
986
+
987
+ class C < B; end
988
+
989
+ A.x = :a
990
+ B.x # => :a
991
+ C.x # => :a
992
+
993
+ B.x = :b
994
+ A.x # => :a
995
+ C.x # => :b
996
+
997
+ C.x = :c
998
+ A.x # => :a
999
+ B.x # => :b
1000
+ ```
1001
+
1002
+ For example `ActionMailer::Base` defines:
1003
+
1004
+ ```ruby
1005
+ class_attribute :default_params
1006
+ self.default_params = {
1007
+ mime_version: "1.0",
1008
+ charset: "UTF-8",
1009
+ content_type: "text/plain",
1010
+ parts_order: [ "text/plain", "text/enriched", "text/html" ]
1011
+ }.freeze
1012
+ ```
1013
+
1014
+ They can be also accessed and overridden at the instance level.
1015
+
1016
+ ```ruby
1017
+ A.x = 1
1018
+
1019
+ a1 = A.new
1020
+ a2 = A.new
1021
+ a2.x = 2
1022
+
1023
+ a1.x # => 1, comes from A
1024
+ a2.x # => 2, overridden in a2
1025
+ ```
1026
+
1027
+ The generation of the writer instance method can be prevented by setting the option `:instance_writer` to `false`.
1028
+
1029
+ ```ruby
1030
+ module ActiveRecord
1031
+ class Base
1032
+ class_attribute :table_name_prefix, instance_writer: false
1033
+ self.table_name_prefix = ""
1034
+ end
1035
+ end
1036
+ ```
1037
+
1038
+ A model may find that option useful as a way to prevent mass-assignment from setting the attribute.
1039
+
1040
+ The generation of the reader instance method can be prevented by setting the option `:instance_reader` to `false`.
1041
+
1042
+ ```ruby
1043
+ class A
1044
+ class_attribute :x, instance_reader: false
1045
+ end
1046
+
1047
+ A.new.x = 1 # NoMethodError
1048
+ ```
1049
+
1050
+ For convenience `class_attribute` also defines an instance predicate which is the double negation of what the instance reader returns. In the examples above it would be called `x?`.
1051
+
1052
+ When `:instance_reader` is `false`, the instance predicate returns a `NoMethodError` just like the reader method.
1053
+
1054
+ If you do not want the instance predicate, pass `instance_predicate: false` and it will not be defined.
1055
+
1056
+ NOTE: Defined in `active_support/core_ext/class/attribute.rb`
1057
+
1058
+ #### `cattr_reader`, `cattr_writer`, and `cattr_accessor`
1059
+
1060
+ The macros `cattr_reader`, `cattr_writer`, and `cattr_accessor` are analogous to their `attr_*` counterparts but for classes. They initialize a class variable to `nil` unless it already exists, and generate the corresponding class methods to access it:
1061
+
1062
+ ```ruby
1063
+ class MysqlAdapter < AbstractAdapter
1064
+ # Generates class methods to access @@emulate_booleans.
1065
+ cattr_accessor :emulate_booleans
1066
+ self.emulate_booleans = true
1067
+ end
1068
+ ```
1069
+
1070
+ 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 `class_attribute` (see above). For example given
1071
+
1072
+ ```ruby
1073
+ module ActionView
1074
+ class Base
1075
+ cattr_accessor :field_error_proc
1076
+ @@field_error_proc = Proc.new{ ... }
1077
+ end
1078
+ end
1079
+ ```
1080
+
1081
+ we can access `field_error_proc` in views.
1082
+
1083
+ Also, you can pass a block to `cattr_*` to set up the attribute with a default value:
1084
+
1085
+ ```ruby
1086
+ class MysqlAdapter < AbstractAdapter
1087
+ # Generates class methods to access @@emulate_booleans with default value of true.
1088
+ cattr_accessor(:emulate_booleans) { true }
1089
+ end
1090
+ ```
1091
+
1092
+ The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.
1093
+
1094
+ ```ruby
1095
+ module A
1096
+ class B
1097
+ # No first_name instance reader is generated.
1098
+ cattr_accessor :first_name, instance_reader: false
1099
+ # No last_name= instance writer is generated.
1100
+ cattr_accessor :last_name, instance_writer: false
1101
+ # No surname instance reader or surname= writer is generated.
1102
+ cattr_accessor :surname, instance_accessor: false
1103
+ end
1104
+ end
1105
+ ```
1106
+
1107
+ A model may find it useful to set `:instance_accessor` to `false` as a way to prevent mass-assignment from setting the attribute.
1108
+
1109
+ NOTE: Defined in `active_support/core_ext/module/attribute_accessors.rb`.
1110
+
1111
+ ### Subclasses & Descendants
1112
+
1113
+ #### `subclasses`
1114
+
1115
+ The `subclasses` method returns the subclasses of the receiver:
1116
+
1117
+ ```ruby
1118
+ class C; end
1119
+ C.subclasses # => []
1120
+
1121
+ class B < C; end
1122
+ C.subclasses # => [B]
1123
+
1124
+ class A < B; end
1125
+ C.subclasses # => [B]
1126
+
1127
+ class D < C; end
1128
+ C.subclasses # => [B, D]
1129
+ ```
1130
+
1131
+ The order in which these classes are returned is unspecified.
1132
+
1133
+ NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
1134
+
1135
+ #### `descendants`
1136
+
1137
+ The `descendants` method returns all classes that are `<` than its receiver:
1138
+
1139
+ ```ruby
1140
+ class C; end
1141
+ C.descendants # => []
1142
+
1143
+ class B < C; end
1144
+ C.descendants # => [B]
1145
+
1146
+ class A < B; end
1147
+ C.descendants # => [B, A]
1148
+
1149
+ class D < C; end
1150
+ C.descendants # => [B, A, D]
1151
+ ```
1152
+
1153
+ The order in which these classes are returned is unspecified.
1154
+
1155
+ NOTE: Defined in `active_support/core_ext/class/subclasses.rb`.
1156
+
1157
+ Extensions to `String`
1158
+ ----------------------
1159
+
1160
+ ### Output Safety
1161
+
1162
+ #### Motivation
1163
+
1164
+ Inserting data into HTML templates needs extra care. For example, you can't just interpolate `@review.title` verbatim into an HTML page. For one thing, if the review title is "Flanagan & Matz rules!" the output won't be well-formed because an ampersand has to be escaped as "&amp;amp;". What's more, depending on the application, that may be a big security hole because users can inject malicious HTML setting a hand-crafted review title. Check out the section about cross-site scripting in the [Security guide](security.html#cross-site-scripting-xss) for further information about the risks.
1165
+
1166
+ #### Safe Strings
1167
+
1168
+ Active Support has the concept of _(html) safe_ strings. A safe string is one that is marked as being insertable into HTML as is. It is trusted, no matter whether it has been escaped or not.
1169
+
1170
+ Strings are considered to be _unsafe_ by default:
1171
+
1172
+ ```ruby
1173
+ "".html_safe? # => false
1174
+ ```
1175
+
1176
+ You can obtain a safe string from a given one with the `html_safe` method:
1177
+
1178
+ ```ruby
1179
+ s = "".html_safe
1180
+ s.html_safe? # => true
1181
+ ```
1182
+
1183
+ It is important to understand that `html_safe` performs no escaping whatsoever, it is just an assertion:
1184
+
1185
+ ```ruby
1186
+ s = "<script>...</script>".html_safe
1187
+ s.html_safe? # => true
1188
+ s # => "<script>...</script>"
1189
+ ```
1190
+
1191
+ It is your responsibility to ensure calling `html_safe` on a particular string is fine.
1192
+
1193
+ If you append onto a safe string, either in-place with `concat`/`<<`, or with `+`, the result is a safe string. Unsafe arguments are escaped:
1194
+
1195
+ ```ruby
1196
+ "".html_safe + "<" # => "&lt;"
1197
+ ```
1198
+
1199
+ Safe arguments are directly appended:
1200
+
1201
+ ```ruby
1202
+ "".html_safe + "<".html_safe # => "<"
1203
+ ```
1204
+
1205
+ These methods should not be used in ordinary views. Unsafe values are automatically escaped:
1206
+
1207
+ ```erb
1208
+ <%= @review.title %> <%# fine, escaped if needed %>
1209
+ ```
1210
+
1211
+ To insert something verbatim use the `raw` helper rather than calling `html_safe`:
1212
+
1213
+ ```erb
1214
+ <%= raw @cms.current_template %> <%# inserts @cms.current_template as is %>
1215
+ ```
1216
+
1217
+ or, equivalently, use `<%==`:
1218
+
1219
+ ```erb
1220
+ <%== @cms.current_template %> <%# inserts @cms.current_template as is %>
1221
+ ```
1222
+
1223
+ The `raw` helper calls `html_safe` for you:
1224
+
1225
+ ```ruby
1226
+ def raw(stringish)
1227
+ stringish.to_s.html_safe
1228
+ end
1229
+ ```
1230
+
1231
+ NOTE: Defined in `active_support/core_ext/string/output_safety.rb`.
1232
+
1233
+ #### Transformation
1234
+
1235
+ 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 `downcase`, `gsub`, `strip`, `chomp`, `underscore`, etc.
1236
+
1237
+ In the case of in-place transformations like `gsub!` the receiver itself becomes unsafe.
1238
+
1239
+ INFO: The safety bit is lost always, no matter whether the transformation actually changed something.
1240
+
1241
+ #### Conversion and Coercion
1242
+
1243
+ Calling `to_s` on a safe string returns a safe string, but coercion with `to_str` returns an unsafe string.
1244
+
1245
+ #### Copying
1246
+
1247
+ Calling `dup` or `clone` on safe strings yields safe strings.
1248
+
1249
+ ### `remove`
1250
+
1251
+ The method `remove` will remove all occurrences of the pattern:
1252
+
1253
+ ```ruby
1254
+ "Hello World".remove(/Hello /) => "World"
1255
+ ```
1256
+
1257
+ There's also the destructive version `String#remove!`.
1258
+
1259
+ NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1260
+
1261
+ ### `squish`
1262
+
1263
+ The method `squish` strips leading and trailing whitespace, and substitutes runs of whitespace with a single space each:
1264
+
1265
+ ```ruby
1266
+ " \n foo\n\r \t bar \n".squish # => "foo bar"
1267
+ ```
1268
+
1269
+ There's also the destructive version `String#squish!`.
1270
+
1271
+ Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E).
1272
+
1273
+ NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1274
+
1275
+ ### `truncate`
1276
+
1277
+ The method `truncate` returns a copy of its receiver truncated after a given `length`:
1278
+
1279
+ ```ruby
1280
+ "Oh dear! Oh dear! I shall be late!".truncate(20)
1281
+ # => "Oh dear! Oh dear!..."
1282
+ ```
1283
+
1284
+ Ellipsis can be customized with the `:omission` option:
1285
+
1286
+ ```ruby
1287
+ "Oh dear! Oh dear! I shall be late!".truncate(20, omission: '&hellip;')
1288
+ # => "Oh dear! Oh &hellip;"
1289
+ ```
1290
+
1291
+ Note in particular that truncation takes into account the length of the omission string.
1292
+
1293
+ Pass a `:separator` to truncate the string at a natural break:
1294
+
1295
+ ```ruby
1296
+ "Oh dear! Oh dear! I shall be late!".truncate(18)
1297
+ # => "Oh dear! Oh dea..."
1298
+ "Oh dear! Oh dear! I shall be late!".truncate(18, separator: ' ')
1299
+ # => "Oh dear! Oh..."
1300
+ ```
1301
+
1302
+ The option `:separator` can be a regexp:
1303
+
1304
+ ```ruby
1305
+ "Oh dear! Oh dear! I shall be late!".truncate(18, separator: /\s/)
1306
+ # => "Oh dear! Oh..."
1307
+ ```
1308
+
1309
+ In above examples "dear" gets cut first, but then `:separator` prevents it.
1310
+
1311
+ NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1312
+
1313
+ ### `truncate_words`
1314
+
1315
+ The method `truncate_words` returns a copy of its receiver truncated after a given number of words:
1316
+
1317
+ ```ruby
1318
+ "Oh dear! Oh dear! I shall be late!".truncate_words(4)
1319
+ # => "Oh dear! Oh dear!..."
1320
+ ```
1321
+
1322
+ Ellipsis can be customized with the `:omission` option:
1323
+
1324
+ ```ruby
1325
+ "Oh dear! Oh dear! I shall be late!".truncate_words(4, omission: '&hellip;')
1326
+ # => "Oh dear! Oh dear!&hellip;"
1327
+ ```
1328
+
1329
+ Pass a `:separator` to truncate the string at a natural break:
1330
+
1331
+ ```ruby
1332
+ "Oh dear! Oh dear! I shall be late!".truncate_words(3, separator: '!')
1333
+ # => "Oh dear! Oh dear! I shall be late..."
1334
+ ```
1335
+
1336
+ The option `:separator` can be a regexp:
1337
+
1338
+ ```ruby
1339
+ "Oh dear! Oh dear! I shall be late!".truncate_words(4, separator: /\s/)
1340
+ # => "Oh dear! Oh dear!..."
1341
+ ```
1342
+
1343
+ NOTE: Defined in `active_support/core_ext/string/filters.rb`.
1344
+
1345
+ ### `inquiry`
1346
+
1347
+ The `inquiry` method converts a string into a `StringInquirer` object making equality checks prettier.
1348
+
1349
+ ```ruby
1350
+ "production".inquiry.production? # => true
1351
+ "active".inquiry.inactive? # => false
1352
+ ```
1353
+
1354
+ ### `starts_with?` and `ends_with?`
1355
+
1356
+ Active Support defines 3rd person aliases of `String#start_with?` and `String#end_with?`:
1357
+
1358
+ ```ruby
1359
+ "foo".starts_with?("f") # => true
1360
+ "foo".ends_with?("o") # => true
1361
+ ```
1362
+
1363
+ NOTE: Defined in `active_support/core_ext/string/starts_ends_with.rb`.
1364
+
1365
+ ### `strip_heredoc`
1366
+
1367
+ The method `strip_heredoc` strips indentation in heredocs.
1368
+
1369
+ For example in
1370
+
1371
+ ```ruby
1372
+ if options[:usage]
1373
+ puts <<-USAGE.strip_heredoc
1374
+ This command does such and such.
1375
+
1376
+ Supported options are:
1377
+ -h This message
1378
+ ...
1379
+ USAGE
1380
+ end
1381
+ ```
1382
+
1383
+ the user would see the usage message aligned against the left margin.
1384
+
1385
+ Technically, it looks for the least indented line in the whole string, and removes
1386
+ that amount of leading whitespace.
1387
+
1388
+ NOTE: Defined in `active_support/core_ext/string/strip.rb`.
1389
+
1390
+ ### `indent`
1391
+
1392
+ Indents the lines in the receiver:
1393
+
1394
+ ```ruby
1395
+ <<EOS.indent(2)
1396
+ def some_method
1397
+ some_code
1398
+ end
1399
+ EOS
1400
+ # =>
1401
+ def some_method
1402
+ some_code
1403
+ end
1404
+ ```
1405
+
1406
+ The second argument, `indent_string`, specifies which indent string to use. The default is `nil`, which tells the method to make an educated guess peeking at the first indented line, and fallback to a space if there is none.
1407
+
1408
+ ```ruby
1409
+ " foo".indent(2) # => " foo"
1410
+ "foo\n\t\tbar".indent(2) # => "\t\tfoo\n\t\t\t\tbar"
1411
+ "foo".indent(2, "\t") # => "\t\tfoo"
1412
+ ```
1413
+
1414
+ While `indent_string` is typically one space or tab, it may be any string.
1415
+
1416
+ The third argument, `indent_empty_lines`, is a flag that says whether empty lines should be indented. Default is false.
1417
+
1418
+ ```ruby
1419
+ "foo\n\nbar".indent(2) # => " foo\n\n bar"
1420
+ "foo\n\nbar".indent(2, nil, true) # => " foo\n \n bar"
1421
+ ```
1422
+
1423
+ The `indent!` method performs indentation in-place.
1424
+
1425
+ NOTE: Defined in `active_support/core_ext/string/indent.rb`.
1426
+
1427
+ ### Access
1428
+
1429
+ #### `at(position)`
1430
+
1431
+ Returns the character of the string at position `position`:
1432
+
1433
+ ```ruby
1434
+ "hello".at(0) # => "h"
1435
+ "hello".at(4) # => "o"
1436
+ "hello".at(-1) # => "o"
1437
+ "hello".at(10) # => nil
1438
+ ```
1439
+
1440
+ NOTE: Defined in `active_support/core_ext/string/access.rb`.
1441
+
1442
+ #### `from(position)`
1443
+
1444
+ Returns the substring of the string starting at position `position`:
1445
+
1446
+ ```ruby
1447
+ "hello".from(0) # => "hello"
1448
+ "hello".from(2) # => "llo"
1449
+ "hello".from(-2) # => "lo"
1450
+ "hello".from(10) # => "" if < 1.9, nil in 1.9
1451
+ ```
1452
+
1453
+ NOTE: Defined in `active_support/core_ext/string/access.rb`.
1454
+
1455
+ #### `to(position)`
1456
+
1457
+ Returns the substring of the string up to position `position`:
1458
+
1459
+ ```ruby
1460
+ "hello".to(0) # => "h"
1461
+ "hello".to(2) # => "hel"
1462
+ "hello".to(-2) # => "hell"
1463
+ "hello".to(10) # => "hello"
1464
+ ```
1465
+
1466
+ NOTE: Defined in `active_support/core_ext/string/access.rb`.
1467
+
1468
+ #### `first(limit = 1)`
1469
+
1470
+ The call `str.first(n)` is equivalent to `str.to(n-1)` if `n` > 0, and returns an empty string for `n` == 0.
1471
+
1472
+ NOTE: Defined in `active_support/core_ext/string/access.rb`.
1473
+
1474
+ #### `last(limit = 1)`
1475
+
1476
+ The call `str.last(n)` is equivalent to `str.from(-n)` if `n` > 0, and returns an empty string for `n` == 0.
1477
+
1478
+ NOTE: Defined in `active_support/core_ext/string/access.rb`.
1479
+
1480
+ ### Inflections
1481
+
1482
+ #### `pluralize`
1483
+
1484
+ The method `pluralize` returns the plural of its receiver:
1485
+
1486
+ ```ruby
1487
+ "table".pluralize # => "tables"
1488
+ "ruby".pluralize # => "rubies"
1489
+ "equipment".pluralize # => "equipment"
1490
+ ```
1491
+
1492
+ As the previous example shows, Active Support knows some irregular plurals and uncountable nouns. Built-in rules can be extended in `config/initializers/inflections.rb`. That file is generated by the `rails` command and has instructions in comments.
1493
+
1494
+ `pluralize` can also take an optional `count` parameter. If `count == 1` the singular form will be returned. For any other value of `count` the plural form will be returned:
1495
+
1496
+ ```ruby
1497
+ "dude".pluralize(0) # => "dudes"
1498
+ "dude".pluralize(1) # => "dude"
1499
+ "dude".pluralize(2) # => "dudes"
1500
+ ```
1501
+
1502
+ Active Record uses this method to compute the default table name that corresponds to a model:
1503
+
1504
+ ```ruby
1505
+ # active_record/model_schema.rb
1506
+ def undecorated_table_name(class_name = base_class.name)
1507
+ table_name = class_name.to_s.demodulize.underscore
1508
+ pluralize_table_names ? table_name.pluralize : table_name
1509
+ end
1510
+ ```
1511
+
1512
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1513
+
1514
+ #### `singularize`
1515
+
1516
+ The inverse of `pluralize`:
1517
+
1518
+ ```ruby
1519
+ "tables".singularize # => "table"
1520
+ "rubies".singularize # => "ruby"
1521
+ "equipment".singularize # => "equipment"
1522
+ ```
1523
+
1524
+ Associations compute the name of the corresponding default associated class using this method:
1525
+
1526
+ ```ruby
1527
+ # active_record/reflection.rb
1528
+ def derive_class_name
1529
+ class_name = name.to_s.camelize
1530
+ class_name = class_name.singularize if collection?
1531
+ class_name
1532
+ end
1533
+ ```
1534
+
1535
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1536
+
1537
+ #### `camelize`
1538
+
1539
+ The method `camelize` returns its receiver in camel case:
1540
+
1541
+ ```ruby
1542
+ "product".camelize # => "Product"
1543
+ "admin_user".camelize # => "AdminUser"
1544
+ ```
1545
+
1546
+ 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:
1547
+
1548
+ ```ruby
1549
+ "backoffice/session".camelize # => "Backoffice::Session"
1550
+ ```
1551
+
1552
+ For example, Action Pack uses this method to load the class that provides a certain session store:
1553
+
1554
+ ```ruby
1555
+ # action_controller/metal/session_management.rb
1556
+ def session_store=(store)
1557
+ @@session_store = store.is_a?(Symbol) ?
1558
+ ActionDispatch::Session.const_get(store.to_s.camelize) :
1559
+ store
1560
+ end
1561
+ ```
1562
+
1563
+ `camelize` accepts an optional argument, it can be `:upper` (default), or `:lower`. With the latter the first letter becomes lowercase:
1564
+
1565
+ ```ruby
1566
+ "visual_effect".camelize(:lower) # => "visualEffect"
1567
+ ```
1568
+
1569
+ That may be handy to compute method names in a language that follows that convention, for example JavaScript.
1570
+
1571
+ INFO: As a rule of thumb you can think of `camelize` as the inverse of `underscore`, though there are cases where that does not hold: `"SSLError".underscore.camelize` gives back `"SslError"`. To support cases such as this, Active Support allows you to specify acronyms in `config/initializers/inflections.rb`:
1572
+
1573
+ ```ruby
1574
+ ActiveSupport::Inflector.inflections do |inflect|
1575
+ inflect.acronym 'SSL'
1576
+ end
1577
+
1578
+ "SSLError".underscore.camelize # => "SSLError"
1579
+ ```
1580
+
1581
+ `camelize` is aliased to `camelcase`.
1582
+
1583
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1584
+
1585
+ #### `underscore`
1586
+
1587
+ The method `underscore` goes the other way around, from camel case to paths:
1588
+
1589
+ ```ruby
1590
+ "Product".underscore # => "product"
1591
+ "AdminUser".underscore # => "admin_user"
1592
+ ```
1593
+
1594
+ Also converts "::" back to "/":
1595
+
1596
+ ```ruby
1597
+ "Backoffice::Session".underscore # => "backoffice/session"
1598
+ ```
1599
+
1600
+ and understands strings that start with lowercase:
1601
+
1602
+ ```ruby
1603
+ "visualEffect".underscore # => "visual_effect"
1604
+ ```
1605
+
1606
+ `underscore` accepts no argument though.
1607
+
1608
+ Rails class and module autoloading uses `underscore` to infer the relative path without extension of a file that would define a given missing constant:
1609
+
1610
+ ```ruby
1611
+ # active_support/dependencies.rb
1612
+ def load_missing_constant(from_mod, const_name)
1613
+ ...
1614
+ qualified_name = qualified_name_for from_mod, const_name
1615
+ path_suffix = qualified_name.underscore
1616
+ ...
1617
+ end
1618
+ ```
1619
+
1620
+ INFO: As a rule of thumb you can think of `underscore` as the inverse of `camelize`, though there are cases where that does not hold. For example, `"SSLError".underscore.camelize` gives back `"SslError"`.
1621
+
1622
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1623
+
1624
+ #### `titleize`
1625
+
1626
+ The method `titleize` capitalizes the words in the receiver:
1627
+
1628
+ ```ruby
1629
+ "alice in wonderland".titleize # => "Alice In Wonderland"
1630
+ "fermat's enigma".titleize # => "Fermat's Enigma"
1631
+ ```
1632
+
1633
+ `titleize` is aliased to `titlecase`.
1634
+
1635
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1636
+
1637
+ #### `dasherize`
1638
+
1639
+ The method `dasherize` replaces the underscores in the receiver with dashes:
1640
+
1641
+ ```ruby
1642
+ "name".dasherize # => "name"
1643
+ "contact_data".dasherize # => "contact-data"
1644
+ ```
1645
+
1646
+ The XML serializer of models uses this method to dasherize node names:
1647
+
1648
+ ```ruby
1649
+ # active_model/serializers/xml.rb
1650
+ def reformat_name(name)
1651
+ name = name.camelize if camelize?
1652
+ dasherize? ? name.dasherize : name
1653
+ end
1654
+ ```
1655
+
1656
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1657
+
1658
+ #### `demodulize`
1659
+
1660
+ Given a string with a qualified constant name, `demodulize` returns the very constant name, that is, the rightmost part of it:
1661
+
1662
+ ```ruby
1663
+ "Product".demodulize # => "Product"
1664
+ "Backoffice::UsersController".demodulize # => "UsersController"
1665
+ "Admin::Hotel::ReservationUtils".demodulize # => "ReservationUtils"
1666
+ "::Inflections".demodulize # => "Inflections"
1667
+ "".demodulize # => ""
1668
+
1669
+ ```
1670
+
1671
+ Active Record for example uses this method to compute the name of a counter cache column:
1672
+
1673
+ ```ruby
1674
+ # active_record/reflection.rb
1675
+ def counter_cache_column
1676
+ if options[:counter_cache] == true
1677
+ "#{active_record.name.demodulize.underscore.pluralize}_count"
1678
+ elsif options[:counter_cache]
1679
+ options[:counter_cache]
1680
+ end
1681
+ end
1682
+ ```
1683
+
1684
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1685
+
1686
+ #### `deconstantize`
1687
+
1688
+ Given a string with a qualified constant reference expression, `deconstantize` removes the rightmost segment, generally leaving the name of the constant's container:
1689
+
1690
+ ```ruby
1691
+ "Product".deconstantize # => ""
1692
+ "Backoffice::UsersController".deconstantize # => "Backoffice"
1693
+ "Admin::Hotel::ReservationUtils".deconstantize # => "Admin::Hotel"
1694
+ ```
1695
+
1696
+ Active Support for example uses this method in `Module#qualified_const_set`:
1697
+
1698
+ ```ruby
1699
+ def qualified_const_set(path, value)
1700
+ QualifiedConstUtils.raise_if_absolute(path)
1701
+
1702
+ const_name = path.demodulize
1703
+ mod_name = path.deconstantize
1704
+ mod = mod_name.empty? ? self : qualified_const_get(mod_name)
1705
+ mod.const_set(const_name, value)
1706
+ end
1707
+ ```
1708
+
1709
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1710
+
1711
+ #### `parameterize`
1712
+
1713
+ The method `parameterize` normalizes its receiver in a way that can be used in pretty URLs.
1714
+
1715
+ ```ruby
1716
+ "John Smith".parameterize # => "john-smith"
1717
+ "Kurt Gödel".parameterize # => "kurt-godel"
1718
+ ```
1719
+
1720
+ In fact, the result string is wrapped in an instance of `ActiveSupport::Multibyte::Chars`.
1721
+
1722
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1723
+
1724
+ #### `tableize`
1725
+
1726
+ The method `tableize` is `underscore` followed by `pluralize`.
1727
+
1728
+ ```ruby
1729
+ "Person".tableize # => "people"
1730
+ "Invoice".tableize # => "invoices"
1731
+ "InvoiceLine".tableize # => "invoice_lines"
1732
+ ```
1733
+
1734
+ As a rule of thumb, `tableize` returns the table name that corresponds to a given model for simple cases. The actual implementation in Active Record is not straight `tableize` indeed, because it also demodulizes the class name and checks a few options that may affect the returned string.
1735
+
1736
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1737
+
1738
+ #### `classify`
1739
+
1740
+ The method `classify` is the inverse of `tableize`. It gives you the class name corresponding to a table name:
1741
+
1742
+ ```ruby
1743
+ "people".classify # => "Person"
1744
+ "invoices".classify # => "Invoice"
1745
+ "invoice_lines".classify # => "InvoiceLine"
1746
+ ```
1747
+
1748
+ The method understands qualified table names:
1749
+
1750
+ ```ruby
1751
+ "highrise_production.companies".classify # => "Company"
1752
+ ```
1753
+
1754
+ Note that `classify` returns a class name as a string. You can get the actual class object invoking `constantize` on it, explained next.
1755
+
1756
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1757
+
1758
+ #### `constantize`
1759
+
1760
+ The method `constantize` resolves the constant reference expression in its receiver:
1761
+
1762
+ ```ruby
1763
+ "Fixnum".constantize # => Fixnum
1764
+
1765
+ module M
1766
+ X = 1
1767
+ end
1768
+ "M::X".constantize # => 1
1769
+ ```
1770
+
1771
+ If the string evaluates to no known constant, or its content is not even a valid constant name, `constantize` raises `NameError`.
1772
+
1773
+ Constant name resolution by `constantize` starts always at the top-level `Object` even if there is no leading "::".
1774
+
1775
+ ```ruby
1776
+ X = :in_Object
1777
+ module M
1778
+ X = :in_M
1779
+
1780
+ X # => :in_M
1781
+ "::X".constantize # => :in_Object
1782
+ "X".constantize # => :in_Object (!)
1783
+ end
1784
+ ```
1785
+
1786
+ So, it is in general not equivalent to what Ruby would do in the same spot, had a real constant be evaluated.
1787
+
1788
+ Mailer test cases obtain the mailer being tested from the name of the test class using `constantize`:
1789
+
1790
+ ```ruby
1791
+ # action_mailer/test_case.rb
1792
+ def determine_default_mailer(name)
1793
+ name.sub(/Test$/, '').constantize
1794
+ rescue NameError => e
1795
+ raise NonInferrableMailerError.new(name)
1796
+ end
1797
+ ```
1798
+
1799
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1800
+
1801
+ #### `humanize`
1802
+
1803
+ The method `humanize` tweaks an attribute name for display to end users.
1804
+
1805
+ Specifically performs these transformations:
1806
+
1807
+ * Applies human inflection rules to the argument.
1808
+ * Deletes leading underscores, if any.
1809
+ * Removes a "_id" suffix if present.
1810
+ * Replaces underscores with spaces, if any.
1811
+ * Downcases all words except acronyms.
1812
+ * Capitalizes the first word.
1813
+
1814
+ The capitalization of the first word can be turned off by setting the
1815
+ +:capitalize+ option to false (default is true).
1816
+
1817
+ ```ruby
1818
+ "name".humanize # => "Name"
1819
+ "author_id".humanize # => "Author"
1820
+ "author_id".humanize(capitalize: false) # => "author"
1821
+ "comments_count".humanize # => "Comments count"
1822
+ "_id".humanize # => "Id"
1823
+ ```
1824
+
1825
+ If "SSL" was defined to be an acronym:
1826
+
1827
+ ```ruby
1828
+ 'ssl_error'.humanize # => "SSL error"
1829
+ ```
1830
+
1831
+ The helper method `full_messages` uses `humanize` as a fallback to include
1832
+ attribute names:
1833
+
1834
+ ```ruby
1835
+ def full_messages
1836
+ full_messages = []
1837
+
1838
+ each do |attribute, messages|
1839
+ ...
1840
+ attr_name = attribute.to_s.gsub('.', '_').humanize
1841
+ attr_name = @base.class.human_attribute_name(attribute, default: attr_name)
1842
+ ...
1843
+ end
1844
+
1845
+ full_messages
1846
+ end
1847
+ ```
1848
+
1849
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1850
+
1851
+ #### `foreign_key`
1852
+
1853
+ The method `foreign_key` gives a foreign key column name from a class name. To do so it demodulizes, underscores, and adds "_id":
1854
+
1855
+ ```ruby
1856
+ "User".foreign_key # => "user_id"
1857
+ "InvoiceLine".foreign_key # => "invoice_line_id"
1858
+ "Admin::Session".foreign_key # => "session_id"
1859
+ ```
1860
+
1861
+ Pass a false argument if you do not want the underscore in "_id":
1862
+
1863
+ ```ruby
1864
+ "User".foreign_key(false) # => "userid"
1865
+ ```
1866
+
1867
+ Associations use this method to infer foreign keys, for example `has_one` and `has_many` do this:
1868
+
1869
+ ```ruby
1870
+ # active_record/associations.rb
1871
+ foreign_key = options[:foreign_key] || reflection.active_record.name.foreign_key
1872
+ ```
1873
+
1874
+ NOTE: Defined in `active_support/core_ext/string/inflections.rb`.
1875
+
1876
+ ### Conversions
1877
+
1878
+ #### `to_date`, `to_time`, `to_datetime`
1879
+
1880
+ The methods `to_date`, `to_time`, and `to_datetime` are basically convenience wrappers around `Date._parse`:
1881
+
1882
+ ```ruby
1883
+ "2010-07-27".to_date # => Tue, 27 Jul 2010
1884
+ "2010-07-27 23:37:00".to_time # => Tue Jul 27 23:37:00 UTC 2010
1885
+ "2010-07-27 23:37:00".to_datetime # => Tue, 27 Jul 2010 23:37:00 +0000
1886
+ ```
1887
+
1888
+ `to_time` receives an optional argument `:utc` or `:local`, to indicate which time zone you want the time in:
1889
+
1890
+ ```ruby
1891
+ "2010-07-27 23:42:00".to_time(:utc) # => Tue Jul 27 23:42:00 UTC 2010
1892
+ "2010-07-27 23:42:00".to_time(:local) # => Tue Jul 27 23:42:00 +0200 2010
1893
+ ```
1894
+
1895
+ Default is `:utc`.
1896
+
1897
+ Please refer to the documentation of `Date._parse` for further details.
1898
+
1899
+ INFO: The three of them return `nil` for blank receivers.
1900
+
1901
+ NOTE: Defined in `active_support/core_ext/string/conversions.rb`.
1902
+
1903
+ Extensions to `Numeric`
1904
+ -----------------------
1905
+
1906
+ ### Bytes
1907
+
1908
+ All numbers respond to these methods:
1909
+
1910
+ ```ruby
1911
+ bytes
1912
+ kilobytes
1913
+ megabytes
1914
+ gigabytes
1915
+ terabytes
1916
+ petabytes
1917
+ exabytes
1918
+ ```
1919
+
1920
+ They return the corresponding amount of bytes, using a conversion factor of 1024:
1921
+
1922
+ ```ruby
1923
+ 2.kilobytes # => 2048
1924
+ 3.megabytes # => 3145728
1925
+ 3.5.gigabytes # => 3758096384
1926
+ -4.exabytes # => -4611686018427387904
1927
+ ```
1928
+
1929
+ Singular forms are aliased so you are able to say:
1930
+
1931
+ ```ruby
1932
+ 1.megabyte # => 1048576
1933
+ ```
1934
+
1935
+ NOTE: Defined in `active_support/core_ext/numeric/bytes.rb`.
1936
+
1937
+ ### Time
1938
+
1939
+ Enables the use of time calculations and declarations, like `45.minutes + 2.hours + 4.years`.
1940
+
1941
+ These methods use Time#advance for precise date calculations when using from_now, ago, etc.
1942
+ as well as adding or subtracting their results from a Time object. For example:
1943
+
1944
+ ```ruby
1945
+ # equivalent to Time.current.advance(months: 1)
1946
+ 1.month.from_now
1947
+
1948
+ # equivalent to Time.current.advance(years: 2)
1949
+ 2.years.from_now
1950
+
1951
+ # equivalent to Time.current.advance(months: 4, years: 5)
1952
+ (4.months + 5.years).from_now
1953
+ ```
1954
+
1955
+ While these methods provide precise calculation when used as in the examples above, care
1956
+ should be taken to note that this is not true if the result of `months', `years', etc is
1957
+ converted before use:
1958
+
1959
+ ```ruby
1960
+ # equivalent to 30.days.to_i.from_now
1961
+ 1.month.to_i.from_now
1962
+
1963
+ # equivalent to 365.25.days.to_f.from_now
1964
+ 1.year.to_f.from_now
1965
+ ```
1966
+
1967
+ In such cases, Ruby's core [Date](http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html) and
1968
+ [Time](http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html) should be used for precision
1969
+ date and time arithmetic.
1970
+
1971
+ NOTE: Defined in `active_support/core_ext/numeric/time.rb`.
1972
+
1973
+ ### Formatting
1974
+
1975
+ Enables the formatting of numbers in a variety of ways.
1976
+
1977
+ Produce a string representation of a number as a telephone number:
1978
+
1979
+ ```ruby
1980
+ 5551234.to_s(:phone)
1981
+ # => 555-1234
1982
+ 1235551234.to_s(:phone)
1983
+ # => 123-555-1234
1984
+ 1235551234.to_s(:phone, area_code: true)
1985
+ # => (123) 555-1234
1986
+ 1235551234.to_s(:phone, delimiter: " ")
1987
+ # => 123 555 1234
1988
+ 1235551234.to_s(:phone, area_code: true, extension: 555)
1989
+ # => (123) 555-1234 x 555
1990
+ 1235551234.to_s(:phone, country_code: 1)
1991
+ # => +1-123-555-1234
1992
+ ```
1993
+
1994
+ Produce a string representation of a number as currency:
1995
+
1996
+ ```ruby
1997
+ 1234567890.50.to_s(:currency) # => $1,234,567,890.50
1998
+ 1234567890.506.to_s(:currency) # => $1,234,567,890.51
1999
+ 1234567890.506.to_s(:currency, precision: 3) # => $1,234,567,890.506
2000
+ ```
2001
+
2002
+ Produce a string representation of a number as a percentage:
2003
+
2004
+ ```ruby
2005
+ 100.to_s(:percentage)
2006
+ # => 100.000%
2007
+ 100.to_s(:percentage, precision: 0)
2008
+ # => 100%
2009
+ 1000.to_s(:percentage, delimiter: '.', separator: ',')
2010
+ # => 1.000,000%
2011
+ 302.24398923423.to_s(:percentage, precision: 5)
2012
+ # => 302.24399%
2013
+ ```
2014
+
2015
+ Produce a string representation of a number in delimited form:
2016
+
2017
+ ```ruby
2018
+ 12345678.to_s(:delimited) # => 12,345,678
2019
+ 12345678.05.to_s(:delimited) # => 12,345,678.05
2020
+ 12345678.to_s(:delimited, delimiter: ".") # => 12.345.678
2021
+ 12345678.to_s(:delimited, delimiter: ",") # => 12,345,678
2022
+ 12345678.05.to_s(:delimited, separator: " ") # => 12,345,678 05
2023
+ ```
2024
+
2025
+ Produce a string representation of a number rounded to a precision:
2026
+
2027
+ ```ruby
2028
+ 111.2345.to_s(:rounded) # => 111.235
2029
+ 111.2345.to_s(:rounded, precision: 2) # => 111.23
2030
+ 13.to_s(:rounded, precision: 5) # => 13.00000
2031
+ 389.32314.to_s(:rounded, precision: 0) # => 389
2032
+ 111.2345.to_s(:rounded, significant: true) # => 111
2033
+ ```
2034
+
2035
+ Produce a string representation of a number as a human-readable number of bytes:
2036
+
2037
+ ```ruby
2038
+ 123.to_s(:human_size) # => 123 Bytes
2039
+ 1234.to_s(:human_size) # => 1.21 KB
2040
+ 12345.to_s(:human_size) # => 12.1 KB
2041
+ 1234567.to_s(:human_size) # => 1.18 MB
2042
+ 1234567890.to_s(:human_size) # => 1.15 GB
2043
+ 1234567890123.to_s(:human_size) # => 1.12 TB
2044
+ ```
2045
+
2046
+ Produce a string representation of a number in human-readable words:
2047
+
2048
+ ```ruby
2049
+ 123.to_s(:human) # => "123"
2050
+ 1234.to_s(:human) # => "1.23 Thousand"
2051
+ 12345.to_s(:human) # => "12.3 Thousand"
2052
+ 1234567.to_s(:human) # => "1.23 Million"
2053
+ 1234567890.to_s(:human) # => "1.23 Billion"
2054
+ 1234567890123.to_s(:human) # => "1.23 Trillion"
2055
+ 1234567890123456.to_s(:human) # => "1.23 Quadrillion"
2056
+ ```
2057
+
2058
+ NOTE: Defined in `active_support/core_ext/numeric/conversions.rb`.
2059
+
2060
+ Extensions to `Integer`
2061
+ -----------------------
2062
+
2063
+ ### `multiple_of?`
2064
+
2065
+ The method `multiple_of?` tests whether an integer is multiple of the argument:
2066
+
2067
+ ```ruby
2068
+ 2.multiple_of?(1) # => true
2069
+ 1.multiple_of?(2) # => false
2070
+ ```
2071
+
2072
+ NOTE: Defined in `active_support/core_ext/integer/multiple.rb`.
2073
+
2074
+ ### `ordinal`
2075
+
2076
+ The method `ordinal` returns the ordinal suffix string corresponding to the receiver integer:
2077
+
2078
+ ```ruby
2079
+ 1.ordinal # => "st"
2080
+ 2.ordinal # => "nd"
2081
+ 53.ordinal # => "rd"
2082
+ 2009.ordinal # => "th"
2083
+ -21.ordinal # => "st"
2084
+ -134.ordinal # => "th"
2085
+ ```
2086
+
2087
+ NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
2088
+
2089
+ ### `ordinalize`
2090
+
2091
+ The method `ordinalize` returns the ordinal string corresponding to the receiver integer. In comparison, note that the `ordinal` method returns **only** the suffix string.
2092
+
2093
+ ```ruby
2094
+ 1.ordinalize # => "1st"
2095
+ 2.ordinalize # => "2nd"
2096
+ 53.ordinalize # => "53rd"
2097
+ 2009.ordinalize # => "2009th"
2098
+ -21.ordinalize # => "-21st"
2099
+ -134.ordinalize # => "-134th"
2100
+ ```
2101
+
2102
+ NOTE: Defined in `active_support/core_ext/integer/inflections.rb`.
2103
+
2104
+ Extensions to `BigDecimal`
2105
+ --------------------------
2106
+ ### `to_s`
2107
+
2108
+ The method `to_s` is aliased to `to_formatted_s`. This provides a convenient way to display a BigDecimal value in floating-point notation:
2109
+
2110
+ ```ruby
2111
+ BigDecimal.new(5.00, 6).to_s # => "5.0"
2112
+ ```
2113
+
2114
+ ### `to_formatted_s`
2115
+
2116
+ Te method `to_formatted_s` provides a default specifier of "F". This means that a simple call to `to_formatted_s` or `to_s` will result in floating point representation instead of engineering notation:
2117
+
2118
+ ```ruby
2119
+ BigDecimal.new(5.00, 6).to_formatted_s # => "5.0"
2120
+ ```
2121
+
2122
+ and that symbol specifiers are also supported:
2123
+
2124
+ ```ruby
2125
+ BigDecimal.new(5.00, 6).to_formatted_s(:db) # => "5.0"
2126
+ ```
2127
+
2128
+ Engineering notation is still supported:
2129
+
2130
+ ```ruby
2131
+ BigDecimal.new(5.00, 6).to_formatted_s("e") # => "0.5E1"
2132
+ ```
2133
+
2134
+ Extensions to `Enumerable`
2135
+ --------------------------
2136
+
2137
+ ### `sum`
2138
+
2139
+ The method `sum` adds the elements of an enumerable:
2140
+
2141
+ ```ruby
2142
+ [1, 2, 3].sum # => 6
2143
+ (1..100).sum # => 5050
2144
+ ```
2145
+
2146
+ Addition only assumes the elements respond to `+`:
2147
+
2148
+ ```ruby
2149
+ [[1, 2], [2, 3], [3, 4]].sum # => [1, 2, 2, 3, 3, 4]
2150
+ %w(foo bar baz).sum # => "foobarbaz"
2151
+ {a: 1, b: 2, c: 3}.sum # => [:b, 2, :c, 3, :a, 1]
2152
+ ```
2153
+
2154
+ The sum of an empty collection is zero by default, but this is customizable:
2155
+
2156
+ ```ruby
2157
+ [].sum # => 0
2158
+ [].sum(1) # => 1
2159
+ ```
2160
+
2161
+ If a block is given, `sum` becomes an iterator that yields the elements of the collection and sums the returned values:
2162
+
2163
+ ```ruby
2164
+ (1..5).sum {|n| n * 2 } # => 30
2165
+ [2, 4, 6, 8, 10].sum # => 30
2166
+ ```
2167
+
2168
+ The sum of an empty receiver can be customized in this form as well:
2169
+
2170
+ ```ruby
2171
+ [].sum(1) {|n| n**3} # => 1
2172
+ ```
2173
+
2174
+ NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2175
+
2176
+ ### `index_by`
2177
+
2178
+ The method `index_by` generates a hash with the elements of an enumerable indexed by some key.
2179
+
2180
+ It iterates through the collection and passes each element to a block. The element will be keyed by the value returned by the block:
2181
+
2182
+ ```ruby
2183
+ invoices.index_by(&:number)
2184
+ # => {'2009-032' => <Invoice ...>, '2009-008' => <Invoice ...>, ...}
2185
+ ```
2186
+
2187
+ WARNING. Keys should normally be unique. If the block returns the same value for different elements no collection is built for that key. The last item will win.
2188
+
2189
+ NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2190
+
2191
+ ### `many?`
2192
+
2193
+ The method `many?` is shorthand for `collection.size > 1`:
2194
+
2195
+ ```erb
2196
+ <% if pages.many? %>
2197
+ <%= pagination_links %>
2198
+ <% end %>
2199
+ ```
2200
+
2201
+ If an optional block is given, `many?` only takes into account those elements that return true:
2202
+
2203
+ ```ruby
2204
+ @see_more = videos.many? {|video| video.category == params[:category]}
2205
+ ```
2206
+
2207
+ NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2208
+
2209
+ ### `exclude?`
2210
+
2211
+ The predicate `exclude?` tests whether a given object does **not** belong to the collection. It is the negation of the built-in `include?`:
2212
+
2213
+ ```ruby
2214
+ to_visit << node if visited.exclude?(node)
2215
+ ```
2216
+
2217
+ NOTE: Defined in `active_support/core_ext/enumerable.rb`.
2218
+
2219
+ Extensions to `Array`
2220
+ ---------------------
2221
+
2222
+ ### Accessing
2223
+
2224
+ Active Support augments the API of arrays to ease certain ways of accessing them. For example, `to` returns the subarray of elements up to the one at the passed index:
2225
+
2226
+ ```ruby
2227
+ %w(a b c d).to(2) # => %w(a b c)
2228
+ [].to(7) # => []
2229
+ ```
2230
+
2231
+ Similarly, `from` 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.
2232
+
2233
+ ```ruby
2234
+ %w(a b c d).from(2) # => %w(c d)
2235
+ %w(a b c d).from(10) # => []
2236
+ [].from(0) # => []
2237
+ ```
2238
+
2239
+ The methods `second`, `third`, `fourth`, and `fifth` return the corresponding element (`first` is built-in). Thanks to social wisdom and positive constructiveness all around, `forty_two` is also available.
2240
+
2241
+ ```ruby
2242
+ %w(a b c d).third # => c
2243
+ %w(a b c d).fifth # => nil
2244
+ ```
2245
+
2246
+ NOTE: Defined in `active_support/core_ext/array/access.rb`.
2247
+
2248
+ ### Adding Elements
2249
+
2250
+ #### `prepend`
2251
+
2252
+ This method is an alias of `Array#unshift`.
2253
+
2254
+ ```ruby
2255
+ %w(a b c d).prepend('e') # => %w(e a b c d)
2256
+ [].prepend(10) # => [10]
2257
+ ```
2258
+
2259
+ NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
2260
+
2261
+ #### `append`
2262
+
2263
+ This method is an alias of `Array#<<`.
2264
+
2265
+ ```ruby
2266
+ %w(a b c d).append('e') # => %w(a b c d e)
2267
+ [].append([1,2]) # => [[1,2]]
2268
+ ```
2269
+
2270
+ NOTE: Defined in `active_support/core_ext/array/prepend_and_append.rb`.
2271
+
2272
+ ### Options Extraction
2273
+
2274
+ When the last argument in a method call is a hash, except perhaps for a `&block` argument, Ruby allows you to omit the brackets:
2275
+
2276
+ ```ruby
2277
+ User.exists?(email: params[:email])
2278
+ ```
2279
+
2280
+ 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.
2281
+
2282
+ If a method expects a variable number of arguments and uses `*` in its declaration, however, such an options hash ends up being an item of the array of arguments, where it loses its role.
2283
+
2284
+ In those cases, you may give an options hash a distinguished treatment with `extract_options!`. 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.
2285
+
2286
+ Let's see for example the definition of the `caches_action` controller macro:
2287
+
2288
+ ```ruby
2289
+ def caches_action(*actions)
2290
+ return unless cache_configured?
2291
+ options = actions.extract_options!
2292
+ ...
2293
+ end
2294
+ ```
2295
+
2296
+ This method receives an arbitrary number of action names, and an optional hash of options as last argument. With the call to `extract_options!` you obtain the options hash and remove it from `actions` in a simple and explicit way.
2297
+
2298
+ NOTE: Defined in `active_support/core_ext/array/extract_options.rb`.
2299
+
2300
+ ### Conversions
2301
+
2302
+ #### `to_sentence`
2303
+
2304
+ The method `to_sentence` turns an array into a string containing a sentence that enumerates its items:
2305
+
2306
+ ```ruby
2307
+ %w().to_sentence # => ""
2308
+ %w(Earth).to_sentence # => "Earth"
2309
+ %w(Earth Wind).to_sentence # => "Earth and Wind"
2310
+ %w(Earth Wind Fire).to_sentence # => "Earth, Wind, and Fire"
2311
+ ```
2312
+
2313
+ This method accepts three options:
2314
+
2315
+ * `:two_words_connector`: What is used for arrays of length 2. Default is " and ".
2316
+ * `:words_connector`: What is used to join the elements of arrays with 3 or more elements, except for the last two. Default is ", ".
2317
+ * `:last_word_connector`: What is used to join the last items of an array with 3 or more elements. Default is ", and ".
2318
+
2319
+ The defaults for these options can be localized, their keys are:
2320
+
2321
+ | Option | I18n key |
2322
+ | ---------------------- | ----------------------------------- |
2323
+ | `:two_words_connector` | `support.array.two_words_connector` |
2324
+ | `:words_connector` | `support.array.words_connector` |
2325
+ | `:last_word_connector` | `support.array.last_word_connector` |
2326
+
2327
+ NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2328
+
2329
+ #### `to_formatted_s`
2330
+
2331
+ The method `to_formatted_s` acts like `to_s` by default.
2332
+
2333
+ If the array contains items that respond to `id`, however, the symbol
2334
+ `:db` may be passed as argument. That's typically used with
2335
+ collections of Active Record objects. Returned strings are:
2336
+
2337
+ ```ruby
2338
+ [].to_formatted_s(:db) # => "null"
2339
+ [user].to_formatted_s(:db) # => "8456"
2340
+ invoice.lines.to_formatted_s(:db) # => "23,567,556,12"
2341
+ ```
2342
+
2343
+ Integers in the example above are supposed to come from the respective calls to `id`.
2344
+
2345
+ NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2346
+
2347
+ #### `to_xml`
2348
+
2349
+ The method `to_xml` returns a string containing an XML representation of its receiver:
2350
+
2351
+ ```ruby
2352
+ Contributor.limit(2).order(:rank).to_xml
2353
+ # =>
2354
+ # <?xml version="1.0" encoding="UTF-8"?>
2355
+ # <contributors type="array">
2356
+ # <contributor>
2357
+ # <id type="integer">4356</id>
2358
+ # <name>Jeremy Kemper</name>
2359
+ # <rank type="integer">1</rank>
2360
+ # <url-id>jeremy-kemper</url-id>
2361
+ # </contributor>
2362
+ # <contributor>
2363
+ # <id type="integer">4404</id>
2364
+ # <name>David Heinemeier Hansson</name>
2365
+ # <rank type="integer">2</rank>
2366
+ # <url-id>david-heinemeier-hansson</url-id>
2367
+ # </contributor>
2368
+ # </contributors>
2369
+ ```
2370
+
2371
+ To do so it sends `to_xml` to every item in turn, and collects the results under a root node. All items must respond to `to_xml`, an exception is raised otherwise.
2372
+
2373
+ 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 `is_a?`) and they are not hashes. In the example above that's "contributors".
2374
+
2375
+ If there's any element that does not belong to the type of the first one the root node becomes "objects":
2376
+
2377
+ ```ruby
2378
+ [Contributor.first, Commit.first].to_xml
2379
+ # =>
2380
+ # <?xml version="1.0" encoding="UTF-8"?>
2381
+ # <objects type="array">
2382
+ # <object>
2383
+ # <id type="integer">4583</id>
2384
+ # <name>Aaron Batalion</name>
2385
+ # <rank type="integer">53</rank>
2386
+ # <url-id>aaron-batalion</url-id>
2387
+ # </object>
2388
+ # <object>
2389
+ # <author>Joshua Peek</author>
2390
+ # <authored-timestamp type="datetime">2009-09-02T16:44:36Z</authored-timestamp>
2391
+ # <branch>origin/master</branch>
2392
+ # <committed-timestamp type="datetime">2009-09-02T16:44:36Z</committed-timestamp>
2393
+ # <committer>Joshua Peek</committer>
2394
+ # <git-show nil="true"></git-show>
2395
+ # <id type="integer">190316</id>
2396
+ # <imported-from-svn type="boolean">false</imported-from-svn>
2397
+ # <message>Kill AMo observing wrap_with_notifications since ARes was only using it</message>
2398
+ # <sha1>723a47bfb3708f968821bc969a9a3fc873a3ed58</sha1>
2399
+ # </object>
2400
+ # </objects>
2401
+ ```
2402
+
2403
+ If the receiver is an array of hashes the root element is by default also "objects":
2404
+
2405
+ ```ruby
2406
+ [{a: 1, b: 2}, {c: 3}].to_xml
2407
+ # =>
2408
+ # <?xml version="1.0" encoding="UTF-8"?>
2409
+ # <objects type="array">
2410
+ # <object>
2411
+ # <b type="integer">2</b>
2412
+ # <a type="integer">1</a>
2413
+ # </object>
2414
+ # <object>
2415
+ # <c type="integer">3</c>
2416
+ # </object>
2417
+ # </objects>
2418
+ ```
2419
+
2420
+ WARNING. If the collection is empty the root element is by default "nil-classes". That's a gotcha, for example the root element of the list of contributors above would not be "contributors" if the collection was empty, but "nil-classes". You may use the `:root` option to ensure a consistent root element.
2421
+
2422
+ The name of children nodes is by default the name of the root node singularized. In the examples above we've seen "contributor" and "object". The option `:children` allows you to set these node names.
2423
+
2424
+ The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder via the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder:
2425
+
2426
+ ```ruby
2427
+ Contributor.limit(2).order(:rank).to_xml(skip_types: true)
2428
+ # =>
2429
+ # <?xml version="1.0" encoding="UTF-8"?>
2430
+ # <contributors>
2431
+ # <contributor>
2432
+ # <id>4356</id>
2433
+ # <name>Jeremy Kemper</name>
2434
+ # <rank>1</rank>
2435
+ # <url-id>jeremy-kemper</url-id>
2436
+ # </contributor>
2437
+ # <contributor>
2438
+ # <id>4404</id>
2439
+ # <name>David Heinemeier Hansson</name>
2440
+ # <rank>2</rank>
2441
+ # <url-id>david-heinemeier-hansson</url-id>
2442
+ # </contributor>
2443
+ # </contributors>
2444
+ ```
2445
+
2446
+ NOTE: Defined in `active_support/core_ext/array/conversions.rb`.
2447
+
2448
+ ### Wrapping
2449
+
2450
+ The method `Array.wrap` wraps its argument in an array unless it is already an array (or array-like).
2451
+
2452
+ Specifically:
2453
+
2454
+ * If the argument is `nil` an empty list is returned.
2455
+ * Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
2456
+ * Otherwise, an array with the argument as its single element is returned.
2457
+
2458
+ ```ruby
2459
+ Array.wrap(nil) # => []
2460
+ Array.wrap([1, 2, 3]) # => [1, 2, 3]
2461
+ Array.wrap(0) # => [0]
2462
+ ```
2463
+
2464
+ This method is similar in purpose to `Kernel#Array`, but there are some differences:
2465
+
2466
+ * If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
2467
+ * If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
2468
+ * It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
2469
+
2470
+ The last point is particularly worth comparing for some enumerables:
2471
+
2472
+ ```ruby
2473
+ Array.wrap(foo: :bar) # => [{:foo=>:bar}]
2474
+ Array(foo: :bar) # => [[:foo, :bar]]
2475
+ ```
2476
+
2477
+ There's also a related idiom that uses the splat operator:
2478
+
2479
+ ```ruby
2480
+ [*object]
2481
+ ```
2482
+
2483
+ which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.)
2484
+
2485
+ Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s.
2486
+
2487
+ NOTE: Defined in `active_support/core_ext/array/wrap.rb`.
2488
+
2489
+ ### Duplicating
2490
+
2491
+ The method `Array.deep_dup` duplicates itself and all objects inside
2492
+ recursively with Active Support method `Object#deep_dup`. It works like `Array#map` with sending `deep_dup` method to each object inside.
2493
+
2494
+ ```ruby
2495
+ array = [1, [2, 3]]
2496
+ dup = array.deep_dup
2497
+ dup[1][2] = 4
2498
+ array[1][2] == nil # => true
2499
+ ```
2500
+
2501
+ NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
2502
+
2503
+ ### Grouping
2504
+
2505
+ #### `in_groups_of(number, fill_with = nil)`
2506
+
2507
+ The method `in_groups_of` splits an array into consecutive groups of a certain size. It returns an array with the groups:
2508
+
2509
+ ```ruby
2510
+ [1, 2, 3].in_groups_of(2) # => [[1, 2], [3, nil]]
2511
+ ```
2512
+
2513
+ or yields them in turn if a block is passed:
2514
+
2515
+ ```html+erb
2516
+ <% sample.in_groups_of(3) do |a, b, c| %>
2517
+ <tr>
2518
+ <td><%= a %></td>
2519
+ <td><%= b %></td>
2520
+ <td><%= c %></td>
2521
+ </tr>
2522
+ <% end %>
2523
+ ```
2524
+
2525
+ The first example shows `in_groups_of` fills the last group with as many `nil` elements as needed to have the requested size. You can change this padding value using the second optional argument:
2526
+
2527
+ ```ruby
2528
+ [1, 2, 3].in_groups_of(2, 0) # => [[1, 2], [3, 0]]
2529
+ ```
2530
+
2531
+ And you can tell the method not to fill the last group passing `false`:
2532
+
2533
+ ```ruby
2534
+ [1, 2, 3].in_groups_of(2, false) # => [[1, 2], [3]]
2535
+ ```
2536
+
2537
+ As a consequence `false` can't be a used as a padding value.
2538
+
2539
+ NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2540
+
2541
+ #### `in_groups(number, fill_with = nil)`
2542
+
2543
+ The method `in_groups` splits an array into a certain number of groups. The method returns an array with the groups:
2544
+
2545
+ ```ruby
2546
+ %w(1 2 3 4 5 6 7).in_groups(3)
2547
+ # => [["1", "2", "3"], ["4", "5", nil], ["6", "7", nil]]
2548
+ ```
2549
+
2550
+ or yields them in turn if a block is passed:
2551
+
2552
+ ```ruby
2553
+ %w(1 2 3 4 5 6 7).in_groups(3) {|group| p group}
2554
+ ["1", "2", "3"]
2555
+ ["4", "5", nil]
2556
+ ["6", "7", nil]
2557
+ ```
2558
+
2559
+ The examples above show that `in_groups` fills some groups with a trailing `nil` element as needed. A group can get at most one of these extra elements, the rightmost one if any. And the groups that have them are always the last ones.
2560
+
2561
+ You can change this padding value using the second optional argument:
2562
+
2563
+ ```ruby
2564
+ %w(1 2 3 4 5 6 7).in_groups(3, "0")
2565
+ # => [["1", "2", "3"], ["4", "5", "0"], ["6", "7", "0"]]
2566
+ ```
2567
+
2568
+ And you can tell the method not to fill the smaller groups passing `false`:
2569
+
2570
+ ```ruby
2571
+ %w(1 2 3 4 5 6 7).in_groups(3, false)
2572
+ # => [["1", "2", "3"], ["4", "5"], ["6", "7"]]
2573
+ ```
2574
+
2575
+ As a consequence `false` can't be a used as a padding value.
2576
+
2577
+ NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2578
+
2579
+ #### `split(value = nil)`
2580
+
2581
+ The method `split` divides an array by a separator and returns the resulting chunks.
2582
+
2583
+ If a block is passed the separators are those elements of the array for which the block returns true:
2584
+
2585
+ ```ruby
2586
+ (-5..5).to_a.split { |i| i.multiple_of?(4) }
2587
+ # => [[-5], [-3, -2, -1], [1, 2, 3], [5]]
2588
+ ```
2589
+
2590
+ Otherwise, the value received as argument, which defaults to `nil`, is the separator:
2591
+
2592
+ ```ruby
2593
+ [0, 1, -5, 1, 1, "foo", "bar"].split(1)
2594
+ # => [[0], [-5], [], ["foo", "bar"]]
2595
+ ```
2596
+
2597
+ TIP: Observe in the previous example that consecutive separators result in empty arrays.
2598
+
2599
+ NOTE: Defined in `active_support/core_ext/array/grouping.rb`.
2600
+
2601
+ Extensions to `Hash`
2602
+ --------------------
2603
+
2604
+ ### Conversions
2605
+
2606
+ #### `to_xml`
2607
+
2608
+ The method `to_xml` returns a string containing an XML representation of its receiver:
2609
+
2610
+ ```ruby
2611
+ {"foo" => 1, "bar" => 2}.to_xml
2612
+ # =>
2613
+ # <?xml version="1.0" encoding="UTF-8"?>
2614
+ # <hash>
2615
+ # <foo type="integer">1</foo>
2616
+ # <bar type="integer">2</bar>
2617
+ # </hash>
2618
+ ```
2619
+
2620
+ To do so, the method loops over the pairs and builds nodes that depend on the _values_. Given a pair `key`, `value`:
2621
+
2622
+ * If `value` is a hash there's a recursive call with `key` as `:root`.
2623
+
2624
+ * If `value` is an array there's a recursive call with `key` as `:root`, and `key` singularized as `:children`.
2625
+
2626
+ * If `value` is a callable object it must expect one or two arguments. Depending on the arity, the callable is invoked with the `options` hash as first argument with `key` as `:root`, and `key` singularized as second argument. Its return value becomes a new node.
2627
+
2628
+ * If `value` responds to `to_xml` the method is invoked with `key` as `:root`.
2629
+
2630
+ * Otherwise, a node with `key` as tag is created with a string representation of `value` as text node. If `value` is `nil` an attribute "nil" set to "true" is added. Unless the option `:skip_types` exists and is true, an attribute "type" is added as well according to the following mapping:
2631
+
2632
+ ```ruby
2633
+ XML_TYPE_NAMES = {
2634
+ "Symbol" => "symbol",
2635
+ "Fixnum" => "integer",
2636
+ "Bignum" => "integer",
2637
+ "BigDecimal" => "decimal",
2638
+ "Float" => "float",
2639
+ "TrueClass" => "boolean",
2640
+ "FalseClass" => "boolean",
2641
+ "Date" => "date",
2642
+ "DateTime" => "datetime",
2643
+ "Time" => "datetime"
2644
+ }
2645
+ ```
2646
+
2647
+ By default the root node is "hash", but that's configurable via the `:root` option.
2648
+
2649
+ The default XML builder is a fresh instance of `Builder::XmlMarkup`. You can configure your own builder with the `:builder` option. The method also accepts options like `:dasherize` and friends, they are forwarded to the builder.
2650
+
2651
+ NOTE: Defined in `active_support/core_ext/hash/conversions.rb`.
2652
+
2653
+ ### Merging
2654
+
2655
+ Ruby has a built-in method `Hash#merge` that merges two hashes:
2656
+
2657
+ ```ruby
2658
+ {a: 1, b: 1}.merge(a: 0, c: 2)
2659
+ # => {:a=>0, :b=>1, :c=>2}
2660
+ ```
2661
+
2662
+ Active Support defines a few more ways of merging hashes that may be convenient.
2663
+
2664
+ #### `reverse_merge` and `reverse_merge!`
2665
+
2666
+ In case of collision the key in the hash of the argument wins in `merge`. You can support option hashes with default values in a compact way with this idiom:
2667
+
2668
+ ```ruby
2669
+ options = {length: 30, omission: "..."}.merge(options)
2670
+ ```
2671
+
2672
+ Active Support defines `reverse_merge` in case you prefer this alternative notation:
2673
+
2674
+ ```ruby
2675
+ options = options.reverse_merge(length: 30, omission: "...")
2676
+ ```
2677
+
2678
+ And a bang version `reverse_merge!` that performs the merge in place:
2679
+
2680
+ ```ruby
2681
+ options.reverse_merge!(length: 30, omission: "...")
2682
+ ```
2683
+
2684
+ WARNING. Take into account that `reverse_merge!` may change the hash in the caller, which may or may not be a good idea.
2685
+
2686
+ NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
2687
+
2688
+ #### `reverse_update`
2689
+
2690
+ The method `reverse_update` is an alias for `reverse_merge!`, explained above.
2691
+
2692
+ WARNING. Note that `reverse_update` has no bang.
2693
+
2694
+ NOTE: Defined in `active_support/core_ext/hash/reverse_merge.rb`.
2695
+
2696
+ #### `deep_merge` and `deep_merge!`
2697
+
2698
+ 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.
2699
+
2700
+ Active Support defines `Hash#deep_merge`. In a deep merge, if a key is found in both hashes and their values are hashes in turn, then their _merge_ becomes the value in the resulting hash:
2701
+
2702
+ ```ruby
2703
+ {a: {b: 1}}.deep_merge(a: {c: 2})
2704
+ # => {:a=>{:b=>1, :c=>2}}
2705
+ ```
2706
+
2707
+ The method `deep_merge!` performs a deep merge in place.
2708
+
2709
+ NOTE: Defined in `active_support/core_ext/hash/deep_merge.rb`.
2710
+
2711
+ ### Deep duplicating
2712
+
2713
+ The method `Hash.deep_dup` duplicates itself and all keys and values
2714
+ inside recursively with Active Support method `Object#deep_dup`. It works like `Enumerator#each_with_object` with sending `deep_dup` method to each pair inside.
2715
+
2716
+ ```ruby
2717
+ hash = { a: 1, b: { c: 2, d: [3, 4] } }
2718
+
2719
+ dup = hash.deep_dup
2720
+ dup[:b][:e] = 5
2721
+ dup[:b][:d] << 5
2722
+
2723
+ hash[:b][:e] == nil # => true
2724
+ hash[:b][:d] == [3, 4] # => true
2725
+ ```
2726
+
2727
+ NOTE: Defined in `active_support/core_ext/object/deep_dup.rb`.
2728
+
2729
+ ### Working with Keys
2730
+
2731
+ #### `except` and `except!`
2732
+
2733
+ The method `except` returns a hash with the keys in the argument list removed, if present:
2734
+
2735
+ ```ruby
2736
+ {a: 1, b: 2}.except(:a) # => {:b=>2}
2737
+ ```
2738
+
2739
+ If the receiver responds to `convert_key`, the method is called on each of the arguments. This allows `except` to play nice with hashes with indifferent access for instance:
2740
+
2741
+ ```ruby
2742
+ {a: 1}.with_indifferent_access.except(:a) # => {}
2743
+ {a: 1}.with_indifferent_access.except("a") # => {}
2744
+ ```
2745
+
2746
+ There's also the bang variant `except!` that removes keys in the very receiver.
2747
+
2748
+ NOTE: Defined in `active_support/core_ext/hash/except.rb`.
2749
+
2750
+ #### `transform_keys` and `transform_keys!`
2751
+
2752
+ The method `transform_keys` accepts a block and returns a hash that has applied the block operations to each of the keys in the receiver:
2753
+
2754
+ ```ruby
2755
+ {nil => nil, 1 => 1, a: :a}.transform_keys { |key| key.to_s.upcase }
2756
+ # => {"" => nil, "A" => :a, "1" => 1}
2757
+ ```
2758
+
2759
+ In case of key collision, one of the values will be chosen. The chosen value may not always be the same given the same hash:
2760
+
2761
+ ```ruby
2762
+ {"a" => 1, a: 2}.transform_keys { |key| key.to_s.upcase }
2763
+ # The result could either be
2764
+ # => {"A"=>2}
2765
+ # or
2766
+ # => {"A"=>1}
2767
+ ```
2768
+
2769
+ This method may be useful for example to build specialized conversions. For instance `stringify_keys` and `symbolize_keys` use `transform_keys` to perform their key conversions:
2770
+
2771
+ ```ruby
2772
+ def stringify_keys
2773
+ transform_keys { |key| key.to_s }
2774
+ end
2775
+ ...
2776
+ def symbolize_keys
2777
+ transform_keys { |key| key.to_sym rescue key }
2778
+ end
2779
+ ```
2780
+
2781
+ There's also the bang variant `transform_keys!` that applies the block operations to keys in the very receiver.
2782
+
2783
+ Besides that, one can use `deep_transform_keys` and `deep_transform_keys!` to perform the block operation on all the keys in the given hash and all the hashes nested into it. An example of the result is:
2784
+
2785
+ ```ruby
2786
+ {nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_transform_keys { |key| key.to_s.upcase }
2787
+ # => {""=>nil, "1"=>1, "NESTED"=>{"A"=>3, "5"=>5}}
2788
+ ```
2789
+
2790
+ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2791
+
2792
+ #### `stringify_keys` and `stringify_keys!`
2793
+
2794
+ The method `stringify_keys` returns a hash that has a stringified version of the keys in the receiver. It does so by sending `to_s` to them:
2795
+
2796
+ ```ruby
2797
+ {nil => nil, 1 => 1, a: :a}.stringify_keys
2798
+ # => {"" => nil, "a" => :a, "1" => 1}
2799
+ ```
2800
+
2801
+ In case of key collision, one of the values will be chosen. The chosen value may not always be the same given the same hash:
2802
+
2803
+ ```ruby
2804
+ {"a" => 1, a: 2}.stringify_keys
2805
+ # The result could either be
2806
+ # => {"a"=>2}
2807
+ # or
2808
+ # => {"a"=>1}
2809
+ ```
2810
+
2811
+ This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionView::Helpers::FormHelper` defines:
2812
+
2813
+ ```ruby
2814
+ def to_check_box_tag(options = {}, checked_value = "1", unchecked_value = "0")
2815
+ options = options.stringify_keys
2816
+ options["type"] = "checkbox"
2817
+ ...
2818
+ end
2819
+ ```
2820
+
2821
+ The second line can safely access the "type" key, and let the user to pass either `:type` or "type".
2822
+
2823
+ There's also the bang variant `stringify_keys!` that stringifies keys in the very receiver.
2824
+
2825
+ Besides that, one can use `deep_stringify_keys` and `deep_stringify_keys!` to stringify all the keys in the given hash and all the hashes nested into it. An example of the result is:
2826
+
2827
+ ```ruby
2828
+ {nil => nil, 1 => 1, nested: {a: 3, 5 => 5}}.deep_stringify_keys
2829
+ # => {""=>nil, "1"=>1, "nested"=>{"a"=>3, "5"=>5}}
2830
+ ```
2831
+
2832
+ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2833
+
2834
+ #### `symbolize_keys` and `symbolize_keys!`
2835
+
2836
+ The method `symbolize_keys` returns a hash that has a symbolized version of the keys in the receiver, where possible. It does so by sending `to_sym` to them:
2837
+
2838
+ ```ruby
2839
+ {nil => nil, 1 => 1, "a" => "a"}.symbolize_keys
2840
+ # => {1=>1, nil=>nil, :a=>"a"}
2841
+ ```
2842
+
2843
+ WARNING. Note in the previous example only one key was symbolized.
2844
+
2845
+ In case of key collision, one of the values will be chosen. The chosen value may not always be the same given the same hash:
2846
+
2847
+ ```ruby
2848
+ {"a" => 1, a: 2}.symbolize_keys
2849
+ # The result could either be
2850
+ # => {:a=>2}
2851
+ # or
2852
+ # => {:a=>1}
2853
+ ```
2854
+
2855
+ This method may be useful for example to easily accept both symbols and strings as options. For instance `ActionController::UrlRewriter` defines
2856
+
2857
+ ```ruby
2858
+ def rewrite_path(options)
2859
+ options = options.symbolize_keys
2860
+ options.update(options[:params].symbolize_keys) if options[:params]
2861
+ ...
2862
+ end
2863
+ ```
2864
+
2865
+ The second line can safely access the `:params` key, and let the user to pass either `:params` or "params".
2866
+
2867
+ There's also the bang variant `symbolize_keys!` that symbolizes keys in the very receiver.
2868
+
2869
+ Besides that, one can use `deep_symbolize_keys` and `deep_symbolize_keys!` to symbolize all the keys in the given hash and all the hashes nested into it. An example of the result is:
2870
+
2871
+ ```ruby
2872
+ {nil => nil, 1 => 1, "nested" => {"a" => 3, 5 => 5}}.deep_symbolize_keys
2873
+ # => {nil=>nil, 1=>1, nested:{a:3, 5=>5}}
2874
+ ```
2875
+
2876
+ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2877
+
2878
+ #### `to_options` and `to_options!`
2879
+
2880
+ The methods `to_options` and `to_options!` are respectively aliases of `symbolize_keys` and `symbolize_keys!`.
2881
+
2882
+ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2883
+
2884
+ #### `assert_valid_keys`
2885
+
2886
+ The method `assert_valid_keys` receives an arbitrary number of arguments, and checks whether the receiver has any key outside that white list. If it does `ArgumentError` is raised.
2887
+
2888
+ ```ruby
2889
+ {a: 1}.assert_valid_keys(:a) # passes
2890
+ {a: 1}.assert_valid_keys("a") # ArgumentError
2891
+ ```
2892
+
2893
+ Active Record does not accept unknown options when building associations, for example. It implements that control via `assert_valid_keys`.
2894
+
2895
+ NOTE: Defined in `active_support/core_ext/hash/keys.rb`.
2896
+
2897
+ ### Working with Values
2898
+
2899
+ #### `transform_values` && `transform_values!`
2900
+
2901
+ The method `transform_values` accepts a block and returns a hash that has applied the block operations to each of the values in the receiver.
2902
+
2903
+ ```ruby
2904
+ { nil => nil, 1 => 1, :x => :a }.transform_values { |value| value.to_s.upcase }
2905
+ # => {nil=>"", 1=>"1", :x=>"A"}
2906
+ ```
2907
+ There's also the bang variant `transform_values!` that applies the block operations to values in the very receiver.
2908
+
2909
+ NOTE: Defined in `active_support/core_text/hash/transform_values.rb`.
2910
+
2911
+ ### Slicing
2912
+
2913
+ Ruby has built-in support for taking slices out of strings and arrays. Active Support extends slicing to hashes:
2914
+
2915
+ ```ruby
2916
+ {a: 1, b: 2, c: 3}.slice(:a, :c)
2917
+ # => {:c=>3, :a=>1}
2918
+
2919
+ {a: 1, b: 2, c: 3}.slice(:b, :X)
2920
+ # => {:b=>2} # non-existing keys are ignored
2921
+ ```
2922
+
2923
+ If the receiver responds to `convert_key` keys are normalized:
2924
+
2925
+ ```ruby
2926
+ {a: 1, b: 2}.with_indifferent_access.slice("a")
2927
+ # => {:a=>1}
2928
+ ```
2929
+
2930
+ NOTE. Slicing may come in handy for sanitizing option hashes with a white list of keys.
2931
+
2932
+ There's also `slice!` which in addition to perform a slice in place returns what's removed:
2933
+
2934
+ ```ruby
2935
+ hash = {a: 1, b: 2}
2936
+ rest = hash.slice!(:a) # => {:b=>2}
2937
+ hash # => {:a=>1}
2938
+ ```
2939
+
2940
+ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
2941
+
2942
+ ### Extracting
2943
+
2944
+ The method `extract!` removes and returns the key/value pairs matching the given keys.
2945
+
2946
+ ```ruby
2947
+ hash = {a: 1, b: 2}
2948
+ rest = hash.extract!(:a) # => {:a=>1}
2949
+ hash # => {:b=>2}
2950
+ ```
2951
+
2952
+ The method `extract!` returns the same subclass of Hash, that the receiver is.
2953
+
2954
+ ```ruby
2955
+ hash = {a: 1, b: 2}.with_indifferent_access
2956
+ rest = hash.extract!(:a).class
2957
+ # => ActiveSupport::HashWithIndifferentAccess
2958
+ ```
2959
+
2960
+ NOTE: Defined in `active_support/core_ext/hash/slice.rb`.
2961
+
2962
+ ### Indifferent Access
2963
+
2964
+ The method `with_indifferent_access` returns an `ActiveSupport::HashWithIndifferentAccess` out of its receiver:
2965
+
2966
+ ```ruby
2967
+ {a: 1}.with_indifferent_access["a"] # => 1
2968
+ ```
2969
+
2970
+ NOTE: Defined in `active_support/core_ext/hash/indifferent_access.rb`.
2971
+
2972
+ ### Compacting
2973
+
2974
+ The methods `compact` and `compact!` return a Hash without items with `nil` value.
2975
+
2976
+ ```ruby
2977
+ {a: 1, b: 2, c: nil}.compact # => {a: 1, b: 2}
2978
+ ```
2979
+
2980
+ NOTE: Defined in `active_support/core_ext/hash/compact.rb`.
2981
+
2982
+ Extensions to `Regexp`
2983
+ ----------------------
2984
+
2985
+ ### `multiline?`
2986
+
2987
+ The method `multiline?` says whether a regexp has the `/m` flag set, that is, whether the dot matches newlines.
2988
+
2989
+ ```ruby
2990
+ %r{.}.multiline? # => false
2991
+ %r{.}m.multiline? # => true
2992
+
2993
+ Regexp.new('.').multiline? # => false
2994
+ Regexp.new('.', Regexp::MULTILINE).multiline? # => true
2995
+ ```
2996
+
2997
+ 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.
2998
+
2999
+ ```ruby
3000
+ def assign_route_options(segments, defaults, requirements)
3001
+ ...
3002
+ if requirement.multiline?
3003
+ raise ArgumentError, "Regexp multiline option not allowed in routing requirements: #{requirement.inspect}"
3004
+ end
3005
+ ...
3006
+ end
3007
+ ```
3008
+
3009
+ NOTE: Defined in `active_support/core_ext/regexp.rb`.
3010
+
3011
+ Extensions to `Range`
3012
+ ---------------------
3013
+
3014
+ ### `to_s`
3015
+
3016
+ Active Support extends the method `Range#to_s` so that it understands an optional format argument. As of this writing the only supported non-default format is `:db`:
3017
+
3018
+ ```ruby
3019
+ (Date.today..Date.tomorrow).to_s
3020
+ # => "2009-10-25..2009-10-26"
3021
+
3022
+ (Date.today..Date.tomorrow).to_s(:db)
3023
+ # => "BETWEEN '2009-10-25' AND '2009-10-26'"
3024
+ ```
3025
+
3026
+ As the example depicts, the `:db` format generates a `BETWEEN` SQL clause. That is used by Active Record in its support for range values in conditions.
3027
+
3028
+ NOTE: Defined in `active_support/core_ext/range/conversions.rb`.
3029
+
3030
+ ### `include?`
3031
+
3032
+ The methods `Range#include?` and `Range#===` say whether some value falls between the ends of a given instance:
3033
+
3034
+ ```ruby
3035
+ (2..3).include?(Math::E) # => true
3036
+ ```
3037
+
3038
+ Active Support extends these methods 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:
3039
+
3040
+ ```ruby
3041
+ (1..10).include?(3..7) # => true
3042
+ (1..10).include?(0..7) # => false
3043
+ (1..10).include?(3..11) # => false
3044
+ (1...9).include?(3..9) # => false
3045
+
3046
+ (1..10) === (3..7) # => true
3047
+ (1..10) === (0..7) # => false
3048
+ (1..10) === (3..11) # => false
3049
+ (1...9) === (3..9) # => false
3050
+ ```
3051
+
3052
+ NOTE: Defined in `active_support/core_ext/range/include_range.rb`.
3053
+
3054
+ ### `overlaps?`
3055
+
3056
+ The method `Range#overlaps?` says whether any two given ranges have non-void intersection:
3057
+
3058
+ ```ruby
3059
+ (1..10).overlaps?(7..11) # => true
3060
+ (1..10).overlaps?(0..7) # => true
3061
+ (1..10).overlaps?(11..27) # => false
3062
+ ```
3063
+
3064
+ NOTE: Defined in `active_support/core_ext/range/overlaps.rb`.
3065
+
3066
+ Extensions to `Proc`
3067
+ --------------------
3068
+
3069
+ ### `bind`
3070
+
3071
+ As you surely know Ruby has an `UnboundMethod` class whose instances are methods that belong to the limbo of methods without a self. The method `Module#instance_method` returns an unbound method for example:
3072
+
3073
+ ```ruby
3074
+ Hash.instance_method(:delete) # => #<UnboundMethod: Hash#delete>
3075
+ ```
3076
+
3077
+ An unbound method is not callable as is, you need to bind it first to an object with `bind`:
3078
+
3079
+ ```ruby
3080
+ clear = Hash.instance_method(:clear)
3081
+ clear.bind({a: 1}).call # => {}
3082
+ ```
3083
+
3084
+ Active Support defines `Proc#bind` with an analogous purpose:
3085
+
3086
+ ```ruby
3087
+ Proc.new { size }.bind([]).call # => 0
3088
+ ```
3089
+
3090
+ As you see that's callable and bound to the argument, the return value is indeed a `Method`.
3091
+
3092
+ NOTE: To do so `Proc#bind` actually creates a method under the hood. If you ever see a method with a weird name like `__bind_1256598120_237302` in a stack trace you know now where it comes from.
3093
+
3094
+ Action Pack uses this trick in `rescue_from` for example, which accepts the name of a method and also a proc as callbacks for a given rescued exception. It has to call them in either case, so a bound method is returned by `handler_for_rescue`, thus simplifying the code in the caller:
3095
+
3096
+ ```ruby
3097
+ def handler_for_rescue(exception)
3098
+ _, rescuer = Array(rescue_handlers).reverse.detect do |klass_name, handler|
3099
+ ...
3100
+ end
3101
+
3102
+ case rescuer
3103
+ when Symbol
3104
+ method(rescuer)
3105
+ when Proc
3106
+ rescuer.bind(self)
3107
+ end
3108
+ end
3109
+ ```
3110
+
3111
+ NOTE: Defined in `active_support/core_ext/proc.rb`.
3112
+
3113
+ Extensions to `Date`
3114
+ --------------------
3115
+
3116
+ ### Calculations
3117
+
3118
+ NOTE: All the following methods are defined in `active_support/core_ext/date/calculations.rb`.
3119
+
3120
+ INFO: 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, `Date.new(1582, 10, 4).tomorrow` returns `Date.new(1582, 10, 15)` and so on. Please check `test/core_ext/date_ext_test.rb` in the Active Support test suite for expected behavior.
3121
+
3122
+ #### `Date.current`
3123
+
3124
+ Active Support defines `Date.current` to be today in the current time zone. That's like `Date.today`, except that it honors the user time zone, if defined. It also defines `Date.yesterday` and `Date.tomorrow`, and the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Date.current`.
3125
+
3126
+ When making Date comparisons using methods which honor the user time zone, make sure to use `Date.current` and not `Date.today`. There are cases where the user time zone might be in the future compared to the system time zone, which `Date.today` uses by default. This means `Date.today` may equal `Date.yesterday`.
3127
+
3128
+ #### Named dates
3129
+
3130
+ ##### `prev_year`, `next_year`
3131
+
3132
+ In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year:
3133
+
3134
+ ```ruby
3135
+ d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3136
+ d.prev_year # => Fri, 08 May 2009
3137
+ d.next_year # => Sun, 08 May 2011
3138
+ ```
3139
+
3140
+ If date is the 29th of February of a leap year, you obtain the 28th:
3141
+
3142
+ ```ruby
3143
+ d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000
3144
+ d.prev_year # => Sun, 28 Feb 1999
3145
+ d.next_year # => Wed, 28 Feb 2001
3146
+ ```
3147
+
3148
+ `prev_year` is aliased to `last_year`.
3149
+
3150
+ ##### `prev_month`, `next_month`
3151
+
3152
+ In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month:
3153
+
3154
+ ```ruby
3155
+ d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3156
+ d.prev_month # => Thu, 08 Apr 2010
3157
+ d.next_month # => Tue, 08 Jun 2010
3158
+ ```
3159
+
3160
+ If such a day does not exist, the last day of the corresponding month is returned:
3161
+
3162
+ ```ruby
3163
+ Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000
3164
+ Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000
3165
+ Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000
3166
+ Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000
3167
+ ```
3168
+
3169
+ `prev_month` is aliased to `last_month`.
3170
+
3171
+ ##### `prev_quarter`, `next_quarter`
3172
+
3173
+ Same as `prev_month` and `next_month`. It returns the date with the same day in the previous or next quarter:
3174
+
3175
+ ```ruby
3176
+ t = Time.local(2010, 5, 8) # => Sat, 08 May 2010
3177
+ t.prev_quarter # => Mon, 08 Feb 2010
3178
+ t.next_quarter # => Sun, 08 Aug 2010
3179
+ ```
3180
+
3181
+ If such a day does not exist, the last day of the corresponding month is returned:
3182
+
3183
+ ```ruby
3184
+ Time.local(2000, 7, 31).prev_quarter # => Sun, 30 Apr 2000
3185
+ Time.local(2000, 5, 31).prev_quarter # => Tue, 29 Feb 2000
3186
+ Time.local(2000, 10, 31).prev_quarter # => Mon, 30 Oct 2000
3187
+ Time.local(2000, 11, 31).next_quarter # => Wed, 28 Feb 2001
3188
+ ```
3189
+
3190
+ `prev_quarter` is aliased to `last_quarter`.
3191
+
3192
+ ##### `beginning_of_week`, `end_of_week`
3193
+
3194
+ The methods `beginning_of_week` and `end_of_week` return the dates for the
3195
+ beginning and end of the week, respectively. Weeks are assumed to start on
3196
+ Monday, but that can be changed passing an argument, setting thread local
3197
+ `Date.beginning_of_week` or `config.beginning_of_week`.
3198
+
3199
+ ```ruby
3200
+ d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3201
+ d.beginning_of_week # => Mon, 03 May 2010
3202
+ d.beginning_of_week(:sunday) # => Sun, 02 May 2010
3203
+ d.end_of_week # => Sun, 09 May 2010
3204
+ d.end_of_week(:sunday) # => Sat, 08 May 2010
3205
+ ```
3206
+
3207
+ `beginning_of_week` is aliased to `at_beginning_of_week` and `end_of_week` is aliased to `at_end_of_week`.
3208
+
3209
+ ##### `monday`, `sunday`
3210
+
3211
+ The methods `monday` and `sunday` return the dates for the previous Monday and
3212
+ next Sunday, respectively.
3213
+
3214
+ ```ruby
3215
+ d = Date.new(2010, 5, 8) # => Sat, 08 May 2010
3216
+ d.monday # => Mon, 03 May 2010
3217
+ d.sunday # => Sun, 09 May 2010
3218
+
3219
+ d = Date.new(2012, 9, 10) # => Mon, 10 Sep 2012
3220
+ d.monday # => Mon, 10 Sep 2012
3221
+
3222
+ d = Date.new(2012, 9, 16) # => Sun, 16 Sep 2012
3223
+ d.sunday # => Sun, 16 Sep 2012
3224
+ ```
3225
+
3226
+ ##### `prev_week`, `next_week`
3227
+
3228
+ The method `next_week` receives a symbol with a day name in English (default is the thread local `Date.beginning_of_week`, or `config.beginning_of_week`, or `:monday`) and it returns the date corresponding to that day.
3229
+
3230
+ ```ruby
3231
+ d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
3232
+ d.next_week # => Mon, 10 May 2010
3233
+ d.next_week(:saturday) # => Sat, 15 May 2010
3234
+ ```
3235
+
3236
+ The method `prev_week` is analogous:
3237
+
3238
+ ```ruby
3239
+ d.prev_week # => Mon, 26 Apr 2010
3240
+ d.prev_week(:saturday) # => Sat, 01 May 2010
3241
+ d.prev_week(:friday) # => Fri, 30 Apr 2010
3242
+ ```
3243
+
3244
+ `prev_week` is aliased to `last_week`.
3245
+
3246
+ Both `next_week` and `prev_week` work as expected when `Date.beginning_of_week` or `config.beginning_of_week` are set.
3247
+
3248
+ ##### `beginning_of_month`, `end_of_month`
3249
+
3250
+ The methods `beginning_of_month` and `end_of_month` return the dates for the beginning and end of the month:
3251
+
3252
+ ```ruby
3253
+ d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
3254
+ d.beginning_of_month # => Sat, 01 May 2010
3255
+ d.end_of_month # => Mon, 31 May 2010
3256
+ ```
3257
+
3258
+ `beginning_of_month` is aliased to `at_beginning_of_month`, and `end_of_month` is aliased to `at_end_of_month`.
3259
+
3260
+ ##### `beginning_of_quarter`, `end_of_quarter`
3261
+
3262
+ The methods `beginning_of_quarter` and `end_of_quarter` return the dates for the beginning and end of the quarter of the receiver's calendar year:
3263
+
3264
+ ```ruby
3265
+ d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
3266
+ d.beginning_of_quarter # => Thu, 01 Apr 2010
3267
+ d.end_of_quarter # => Wed, 30 Jun 2010
3268
+ ```
3269
+
3270
+ `beginning_of_quarter` is aliased to `at_beginning_of_quarter`, and `end_of_quarter` is aliased to `at_end_of_quarter`.
3271
+
3272
+ ##### `beginning_of_year`, `end_of_year`
3273
+
3274
+ The methods `beginning_of_year` and `end_of_year` return the dates for the beginning and end of the year:
3275
+
3276
+ ```ruby
3277
+ d = Date.new(2010, 5, 9) # => Sun, 09 May 2010
3278
+ d.beginning_of_year # => Fri, 01 Jan 2010
3279
+ d.end_of_year # => Fri, 31 Dec 2010
3280
+ ```
3281
+
3282
+ `beginning_of_year` is aliased to `at_beginning_of_year`, and `end_of_year` is aliased to `at_end_of_year`.
3283
+
3284
+ #### Other Date Computations
3285
+
3286
+ ##### `years_ago`, `years_since`
3287
+
3288
+ The method `years_ago` receives a number of years and returns the same date those many years ago:
3289
+
3290
+ ```ruby
3291
+ date = Date.new(2010, 6, 7)
3292
+ date.years_ago(10) # => Wed, 07 Jun 2000
3293
+ ```
3294
+
3295
+ `years_since` moves forward in time:
3296
+
3297
+ ```ruby
3298
+ date = Date.new(2010, 6, 7)
3299
+ date.years_since(10) # => Sun, 07 Jun 2020
3300
+ ```
3301
+
3302
+ If such a day does not exist, the last day of the corresponding month is returned:
3303
+
3304
+ ```ruby
3305
+ Date.new(2012, 2, 29).years_ago(3) # => Sat, 28 Feb 2009
3306
+ Date.new(2012, 2, 29).years_since(3) # => Sat, 28 Feb 2015
3307
+ ```
3308
+
3309
+ ##### `months_ago`, `months_since`
3310
+
3311
+ The methods `months_ago` and `months_since` work analogously for months:
3312
+
3313
+ ```ruby
3314
+ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
3315
+ Date.new(2010, 4, 30).months_since(2) # => Wed, 30 Jun 2010
3316
+ ```
3317
+
3318
+ If such a day does not exist, the last day of the corresponding month is returned:
3319
+
3320
+ ```ruby
3321
+ Date.new(2010, 4, 30).months_ago(2) # => Sun, 28 Feb 2010
3322
+ Date.new(2009, 12, 31).months_since(2) # => Sun, 28 Feb 2010
3323
+ ```
3324
+
3325
+ ##### `weeks_ago`
3326
+
3327
+ The method `weeks_ago` works analogously for weeks:
3328
+
3329
+ ```ruby
3330
+ Date.new(2010, 5, 24).weeks_ago(1) # => Mon, 17 May 2010
3331
+ Date.new(2010, 5, 24).weeks_ago(2) # => Mon, 10 May 2010
3332
+ ```
3333
+
3334
+ ##### `advance`
3335
+
3336
+ The most generic way to jump to other days is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, and returns a date advanced as much as the present keys indicate:
3337
+
3338
+ ```ruby
3339
+ date = Date.new(2010, 6, 6)
3340
+ date.advance(years: 1, weeks: 2) # => Mon, 20 Jun 2011
3341
+ date.advance(months: 2, days: -2) # => Wed, 04 Aug 2010
3342
+ ```
3343
+
3344
+ Note in the previous example that increments may be negative.
3345
+
3346
+ 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.
3347
+
3348
+ The method `advance` advances first one month, and then one day, the result is:
3349
+
3350
+ ```ruby
3351
+ Date.new(2010, 2, 28).advance(months: 1, days: 1)
3352
+ # => Sun, 29 Mar 2010
3353
+ ```
3354
+
3355
+ While if it did it the other way around the result would be different:
3356
+
3357
+ ```ruby
3358
+ Date.new(2010, 2, 28).advance(days: 1).advance(months: 1)
3359
+ # => Thu, 01 Apr 2010
3360
+ ```
3361
+
3362
+ #### Changing Components
3363
+
3364
+ The method `change` allows you to get a new date which is the same as the receiver except for the given year, month, or day:
3365
+
3366
+ ```ruby
3367
+ Date.new(2010, 12, 23).change(year: 2011, month: 11)
3368
+ # => Wed, 23 Nov 2011
3369
+ ```
3370
+
3371
+ This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
3372
+
3373
+ ```ruby
3374
+ Date.new(2010, 1, 31).change(month: 2)
3375
+ # => ArgumentError: invalid date
3376
+ ```
3377
+
3378
+ #### Durations
3379
+
3380
+ Durations can be added to and subtracted from dates:
3381
+
3382
+ ```ruby
3383
+ d = Date.current
3384
+ # => Mon, 09 Aug 2010
3385
+ d + 1.year
3386
+ # => Tue, 09 Aug 2011
3387
+ d - 3.hours
3388
+ # => Sun, 08 Aug 2010 21:00:00 UTC +00:00
3389
+ ```
3390
+
3391
+ They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3392
+
3393
+ ```ruby
3394
+ Date.new(1582, 10, 4) + 1.day
3395
+ # => Fri, 15 Oct 1582
3396
+ ```
3397
+
3398
+ #### Timestamps
3399
+
3400
+ INFO: The following methods return a `Time` object if possible, otherwise a `DateTime`. If set, they honor the user time zone.
3401
+
3402
+ ##### `beginning_of_day`, `end_of_day`
3403
+
3404
+ The method `beginning_of_day` returns a timestamp at the beginning of the day (00:00:00):
3405
+
3406
+ ```ruby
3407
+ date = Date.new(2010, 6, 7)
3408
+ date.beginning_of_day # => Mon Jun 07 00:00:00 +0200 2010
3409
+ ```
3410
+
3411
+ The method `end_of_day` returns a timestamp at the end of the day (23:59:59):
3412
+
3413
+ ```ruby
3414
+ date = Date.new(2010, 6, 7)
3415
+ date.end_of_day # => Mon Jun 07 23:59:59 +0200 2010
3416
+ ```
3417
+
3418
+ `beginning_of_day` is aliased to `at_beginning_of_day`, `midnight`, `at_midnight`.
3419
+
3420
+ ##### `beginning_of_hour`, `end_of_hour`
3421
+
3422
+ The method `beginning_of_hour` returns a timestamp at the beginning of the hour (hh:00:00):
3423
+
3424
+ ```ruby
3425
+ date = DateTime.new(2010, 6, 7, 19, 55, 25)
3426
+ date.beginning_of_hour # => Mon Jun 07 19:00:00 +0200 2010
3427
+ ```
3428
+
3429
+ The method `end_of_hour` returns a timestamp at the end of the hour (hh:59:59):
3430
+
3431
+ ```ruby
3432
+ date = DateTime.new(2010, 6, 7, 19, 55, 25)
3433
+ date.end_of_hour # => Mon Jun 07 19:59:59 +0200 2010
3434
+ ```
3435
+
3436
+ `beginning_of_hour` is aliased to `at_beginning_of_hour`.
3437
+
3438
+ ##### `beginning_of_minute`, `end_of_minute`
3439
+
3440
+ The method `beginning_of_minute` returns a timestamp at the beginning of the minute (hh:mm:00):
3441
+
3442
+ ```ruby
3443
+ date = DateTime.new(2010, 6, 7, 19, 55, 25)
3444
+ date.beginning_of_minute # => Mon Jun 07 19:55:00 +0200 2010
3445
+ ```
3446
+
3447
+ The method `end_of_minute` returns a timestamp at the end of the minute (hh:mm:59):
3448
+
3449
+ ```ruby
3450
+ date = DateTime.new(2010, 6, 7, 19, 55, 25)
3451
+ date.end_of_minute # => Mon Jun 07 19:55:59 +0200 2010
3452
+ ```
3453
+
3454
+ `beginning_of_minute` is aliased to `at_beginning_of_minute`.
3455
+
3456
+ INFO: `beginning_of_hour`, `end_of_hour`, `beginning_of_minute` and `end_of_minute` are implemented for `Time` and `DateTime` but **not** `Date` as it does not make sense to request the beginning or end of an hour or minute on a `Date` instance.
3457
+
3458
+ ##### `ago`, `since`
3459
+
3460
+ The method `ago` receives a number of seconds as argument and returns a timestamp those many seconds ago from midnight:
3461
+
3462
+ ```ruby
3463
+ date = Date.current # => Fri, 11 Jun 2010
3464
+ date.ago(1) # => Thu, 10 Jun 2010 23:59:59 EDT -04:00
3465
+ ```
3466
+
3467
+ Similarly, `since` moves forward:
3468
+
3469
+ ```ruby
3470
+ date = Date.current # => Fri, 11 Jun 2010
3471
+ date.since(1) # => Fri, 11 Jun 2010 00:00:01 EDT -04:00
3472
+ ```
3473
+
3474
+ #### Other Time Computations
3475
+
3476
+ ### Conversions
3477
+
3478
+ Extensions to `DateTime`
3479
+ ------------------------
3480
+
3481
+ WARNING: `DateTime` is not aware of DST rules and so some of these methods have edge cases when a DST change is going on. For example `seconds_since_midnight` might not return the real amount in such a day.
3482
+
3483
+ ### Calculations
3484
+
3485
+ NOTE: All the following methods are defined in `active_support/core_ext/date_time/calculations.rb`.
3486
+
3487
+ The class `DateTime` is a subclass of `Date` so by loading `active_support/core_ext/date/calculations.rb` you inherit these methods and their aliases, except that they will always return datetimes:
3488
+
3489
+ ```ruby
3490
+ yesterday
3491
+ tomorrow
3492
+ beginning_of_week (at_beginning_of_week)
3493
+ end_of_week (at_end_of_week)
3494
+ monday
3495
+ sunday
3496
+ weeks_ago
3497
+ prev_week (last_week)
3498
+ next_week
3499
+ months_ago
3500
+ months_since
3501
+ beginning_of_month (at_beginning_of_month)
3502
+ end_of_month (at_end_of_month)
3503
+ prev_month (last_month)
3504
+ next_month
3505
+ beginning_of_quarter (at_beginning_of_quarter)
3506
+ end_of_quarter (at_end_of_quarter)
3507
+ beginning_of_year (at_beginning_of_year)
3508
+ end_of_year (at_end_of_year)
3509
+ years_ago
3510
+ years_since
3511
+ prev_year (last_year)
3512
+ next_year
3513
+ ```
3514
+
3515
+ The following methods are reimplemented so you do **not** need to load `active_support/core_ext/date/calculations.rb` for these ones:
3516
+
3517
+ ```ruby
3518
+ beginning_of_day (midnight, at_midnight, at_beginning_of_day)
3519
+ end_of_day
3520
+ ago
3521
+ since (in)
3522
+ ```
3523
+
3524
+ On the other hand, `advance` and `change` are also defined and support more options, they are documented below.
3525
+
3526
+ The following methods are only implemented in `active_support/core_ext/date_time/calculations.rb` as they only make sense when used with a `DateTime` instance:
3527
+
3528
+ ```ruby
3529
+ beginning_of_hour (at_beginning_of_hour)
3530
+ end_of_hour
3531
+ ```
3532
+
3533
+ #### Named Datetimes
3534
+
3535
+ ##### `DateTime.current`
3536
+
3537
+ Active Support defines `DateTime.current` to be like `Time.now.to_datetime`, except that it honors the user time zone, if defined. It also defines `DateTime.yesterday` and `DateTime.tomorrow`, and the instance predicates `past?`, and `future?` relative to `DateTime.current`.
3538
+
3539
+ #### Other Extensions
3540
+
3541
+ ##### `seconds_since_midnight`
3542
+
3543
+ The method `seconds_since_midnight` returns the number of seconds since midnight:
3544
+
3545
+ ```ruby
3546
+ now = DateTime.current # => Mon, 07 Jun 2010 20:26:36 +0000
3547
+ now.seconds_since_midnight # => 73596
3548
+ ```
3549
+
3550
+ ##### `utc`
3551
+
3552
+ The method `utc` gives you the same datetime in the receiver expressed in UTC.
3553
+
3554
+ ```ruby
3555
+ now = DateTime.current # => Mon, 07 Jun 2010 19:27:52 -0400
3556
+ now.utc # => Mon, 07 Jun 2010 23:27:52 +0000
3557
+ ```
3558
+
3559
+ This method is also aliased as `getutc`.
3560
+
3561
+ ##### `utc?`
3562
+
3563
+ The predicate `utc?` says whether the receiver has UTC as its time zone:
3564
+
3565
+ ```ruby
3566
+ now = DateTime.now # => Mon, 07 Jun 2010 19:30:47 -0400
3567
+ now.utc? # => false
3568
+ now.utc.utc? # => true
3569
+ ```
3570
+
3571
+ ##### `advance`
3572
+
3573
+ The most generic way to jump to another datetime is `advance`. This method receives a hash with keys `:years`, `:months`, `:weeks`, `:days`, `:hours`, `:minutes`, and `:seconds`, and returns a datetime advanced as much as the present keys indicate.
3574
+
3575
+ ```ruby
3576
+ d = DateTime.current
3577
+ # => Thu, 05 Aug 2010 11:33:31 +0000
3578
+ d.advance(years: 1, months: 1, days: 1, hours: 1, minutes: 1, seconds: 1)
3579
+ # => Tue, 06 Sep 2011 12:34:32 +0000
3580
+ ```
3581
+
3582
+ This method first computes the destination date passing `:years`, `:months`, `:weeks`, and `:days` to `Date#advance` documented above. After that, it adjusts the time calling `since` 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 `Date#advance` applies, and we can extend it to show order relevance related to the time bits.
3583
+
3584
+ 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:
3585
+
3586
+ ```ruby
3587
+ d = DateTime.new(2010, 2, 28, 23, 59, 59)
3588
+ # => Sun, 28 Feb 2010 23:59:59 +0000
3589
+ d.advance(months: 1, seconds: 1)
3590
+ # => Mon, 29 Mar 2010 00:00:00 +0000
3591
+ ```
3592
+
3593
+ but if we computed them the other way around, the result would be different:
3594
+
3595
+ ```ruby
3596
+ d.advance(seconds: 1).advance(months: 1)
3597
+ # => Thu, 01 Apr 2010 00:00:00 +0000
3598
+ ```
3599
+
3600
+ WARNING: Since `DateTime` is not DST-aware you can end up in a non-existing point in time with no warning or error telling you so.
3601
+
3602
+ #### Changing Components
3603
+
3604
+ The method `change` allows you to get a new datetime which is the same as the receiver except for the given options, which may include `:year`, `:month`, `:day`, `:hour`, `:min`, `:sec`, `:offset`, `:start`:
3605
+
3606
+ ```ruby
3607
+ now = DateTime.current
3608
+ # => Tue, 08 Jun 2010 01:56:22 +0000
3609
+ now.change(year: 2011, offset: Rational(-6, 24))
3610
+ # => Wed, 08 Jun 2011 01:56:22 -0600
3611
+ ```
3612
+
3613
+ If hours are zeroed, then minutes and seconds are too (unless they have given values):
3614
+
3615
+ ```ruby
3616
+ now.change(hour: 0)
3617
+ # => Tue, 08 Jun 2010 00:00:00 +0000
3618
+ ```
3619
+
3620
+ Similarly, if minutes are zeroed, then seconds are too (unless it has given a value):
3621
+
3622
+ ```ruby
3623
+ now.change(min: 0)
3624
+ # => Tue, 08 Jun 2010 01:00:00 +0000
3625
+ ```
3626
+
3627
+ This method is not tolerant to non-existing dates, if the change is invalid `ArgumentError` is raised:
3628
+
3629
+ ```ruby
3630
+ DateTime.current.change(month: 2, day: 30)
3631
+ # => ArgumentError: invalid date
3632
+ ```
3633
+
3634
+ #### Durations
3635
+
3636
+ Durations can be added to and subtracted from datetimes:
3637
+
3638
+ ```ruby
3639
+ now = DateTime.current
3640
+ # => Mon, 09 Aug 2010 23:15:17 +0000
3641
+ now + 1.year
3642
+ # => Tue, 09 Aug 2011 23:15:17 +0000
3643
+ now - 1.week
3644
+ # => Mon, 02 Aug 2010 23:15:17 +0000
3645
+ ```
3646
+
3647
+ They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3648
+
3649
+ ```ruby
3650
+ DateTime.new(1582, 10, 4, 23) + 1.hour
3651
+ # => Fri, 15 Oct 1582 00:00:00 +0000
3652
+ ```
3653
+
3654
+ Extensions to `Time`
3655
+ --------------------
3656
+
3657
+ ### Calculations
3658
+
3659
+ NOTE: All the following methods are defined in `active_support/core_ext/time/calculations.rb`.
3660
+
3661
+ Active Support adds to `Time` many of the methods available for `DateTime`:
3662
+
3663
+ ```ruby
3664
+ past?
3665
+ today?
3666
+ future?
3667
+ yesterday
3668
+ tomorrow
3669
+ seconds_since_midnight
3670
+ change
3671
+ advance
3672
+ ago
3673
+ since (in)
3674
+ beginning_of_day (midnight, at_midnight, at_beginning_of_day)
3675
+ end_of_day
3676
+ beginning_of_hour (at_beginning_of_hour)
3677
+ end_of_hour
3678
+ beginning_of_week (at_beginning_of_week)
3679
+ end_of_week (at_end_of_week)
3680
+ monday
3681
+ sunday
3682
+ weeks_ago
3683
+ prev_week (last_week)
3684
+ next_week
3685
+ months_ago
3686
+ months_since
3687
+ beginning_of_month (at_beginning_of_month)
3688
+ end_of_month (at_end_of_month)
3689
+ prev_month (last_month)
3690
+ next_month
3691
+ beginning_of_quarter (at_beginning_of_quarter)
3692
+ end_of_quarter (at_end_of_quarter)
3693
+ beginning_of_year (at_beginning_of_year)
3694
+ end_of_year (at_end_of_year)
3695
+ years_ago
3696
+ years_since
3697
+ prev_year (last_year)
3698
+ next_year
3699
+ ```
3700
+
3701
+ They are analogous. Please refer to their documentation above and take into account the following differences:
3702
+
3703
+ * `change` accepts an additional `:usec` option.
3704
+ * `Time` understands DST, so you get correct DST calculations as in
3705
+
3706
+ ```ruby
3707
+ Time.zone_default
3708
+ # => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
3709
+
3710
+ # In Barcelona, 2010/03/28 02:00 +0100 becomes 2010/03/28 03:00 +0200 due to DST.
3711
+ t = Time.local(2010, 3, 28, 1, 59, 59)
3712
+ # => Sun Mar 28 01:59:59 +0100 2010
3713
+ t.advance(seconds: 1)
3714
+ # => Sun Mar 28 03:00:00 +0200 2010
3715
+ ```
3716
+
3717
+ * If `since` or `ago` jump to a time that can't be expressed with `Time` a `DateTime` object is returned instead.
3718
+
3719
+ #### `Time.current`
3720
+
3721
+ Active Support defines `Time.current` to be today in the current time zone. That's like `Time.now`, except that it honors the user time zone, if defined. It also defines the instance predicates `past?`, `today?`, and `future?`, all of them relative to `Time.current`.
3722
+
3723
+ When making Time comparisons using methods which honor the user time zone, make sure to use `Time.current` instead of `Time.now`. There are cases where the user time zone might be in the future compared to the system time zone, which `Time.now` uses by default. This means `Time.now.to_date` may equal `Date.yesterday`.
3724
+
3725
+ #### `all_day`, `all_week`, `all_month`, `all_quarter` and `all_year`
3726
+
3727
+ The method `all_day` returns a range representing the whole day of the current time.
3728
+
3729
+ ```ruby
3730
+ now = Time.current
3731
+ # => Mon, 09 Aug 2010 23:20:05 UTC +00:00
3732
+ now.all_day
3733
+ # => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Mon, 09 Aug 2010 23:59:59 UTC +00:00
3734
+ ```
3735
+
3736
+ Analogously, `all_week`, `all_month`, `all_quarter` and `all_year` all serve the purpose of generating time ranges.
3737
+
3738
+ ```ruby
3739
+ now = Time.current
3740
+ # => Mon, 09 Aug 2010 23:20:05 UTC +00:00
3741
+ now.all_week
3742
+ # => Mon, 09 Aug 2010 00:00:00 UTC +00:00..Sun, 15 Aug 2010 23:59:59 UTC +00:00
3743
+ now.all_week(:sunday)
3744
+ # => Sun, 16 Sep 2012 00:00:00 UTC +00:00..Sat, 22 Sep 2012 23:59:59 UTC +00:00
3745
+ now.all_month
3746
+ # => Sat, 01 Aug 2010 00:00:00 UTC +00:00..Tue, 31 Aug 2010 23:59:59 UTC +00:00
3747
+ now.all_quarter
3748
+ # => Thu, 01 Jul 2010 00:00:00 UTC +00:00..Thu, 30 Sep 2010 23:59:59 UTC +00:00
3749
+ now.all_year
3750
+ # => Fri, 01 Jan 2010 00:00:00 UTC +00:00..Fri, 31 Dec 2010 23:59:59 UTC +00:00
3751
+ ```
3752
+
3753
+ ### Time Constructors
3754
+
3755
+ Active Support defines `Time.current` to be `Time.zone.now` if there's a user time zone defined, with fallback to `Time.now`:
3756
+
3757
+ ```ruby
3758
+ Time.zone_default
3759
+ # => #<ActiveSupport::TimeZone:0x7f73654d4f38 @utc_offset=nil, @name="Madrid", ...>
3760
+ Time.current
3761
+ # => Fri, 06 Aug 2010 17:11:58 CEST +02:00
3762
+ ```
3763
+
3764
+ Analogously to `DateTime`, the predicates `past?`, and `future?` are relative to `Time.current`.
3765
+
3766
+ If the time to be constructed lies beyond the range supported by `Time` in the runtime platform, usecs are discarded and a `DateTime` object is returned instead.
3767
+
3768
+ #### Durations
3769
+
3770
+ Durations can be added to and subtracted from time objects:
3771
+
3772
+ ```ruby
3773
+ now = Time.current
3774
+ # => Mon, 09 Aug 2010 23:20:05 UTC +00:00
3775
+ now + 1.year
3776
+ # => Tue, 09 Aug 2011 23:21:11 UTC +00:00
3777
+ now - 1.week
3778
+ # => Mon, 02 Aug 2010 23:21:11 UTC +00:00
3779
+ ```
3780
+
3781
+ They translate to calls to `since` or `advance`. For example here we get the correct jump in the calendar reform:
3782
+
3783
+ ```ruby
3784
+ Time.utc(1582, 10, 3) + 5.days
3785
+ # => Mon Oct 18 00:00:00 UTC 1582
3786
+ ```
3787
+
3788
+ Extensions to `File`
3789
+ --------------------
3790
+
3791
+ ### `atomic_write`
3792
+
3793
+ With the class method `File.atomic_write` you can write to a file in a way that will prevent any reader from seeing half-written content.
3794
+
3795
+ The name of the file is passed as an argument, and the method yields a file handle opened for writing. Once the block is done `atomic_write` closes the file handle and completes its job.
3796
+
3797
+ For example, Action Pack uses this method to write asset cache files like `all.css`:
3798
+
3799
+ ```ruby
3800
+ File.atomic_write(joined_asset_path) do |cache|
3801
+ cache.write(join_asset_file_contents(asset_paths))
3802
+ end
3803
+ ```
3804
+
3805
+ To accomplish this `atomic_write` creates a temporary file. That's the file the code in the block actually writes to. On completion, the temporary file is renamed, which is an atomic operation on POSIX systems. If the target file exists `atomic_write` overwrites it and keeps owners and permissions. However there are a few cases where `atomic_write` cannot change the file ownership or permissions, this error is caught and skipped over trusting in the user/filesystem to ensure the file is accessible to the processes that need it.
3806
+
3807
+ NOTE. Due to the chmod operation `atomic_write` performs, if the target file has an ACL set on it this ACL will be recalculated/modified.
3808
+
3809
+ WARNING. Note you can't append with `atomic_write`.
3810
+
3811
+ The auxiliary file is written in a standard directory for temporary files, but you can pass a directory of your choice as second argument.
3812
+
3813
+ NOTE: Defined in `active_support/core_ext/file/atomic.rb`.
3814
+
3815
+ Extensions to `Marshal`
3816
+ -----------------------
3817
+
3818
+ ### `load`
3819
+
3820
+ Active Support adds constant autoloading support to `load`.
3821
+
3822
+ For example, the file cache store deserializes this way:
3823
+
3824
+ ```ruby
3825
+ File.open(file_name) { |f| Marshal.load(f) }
3826
+ ```
3827
+
3828
+ If the cached data refers to a constant that is unknown at that point, the autoloading mechanism is triggered and if it succeeds the deserialization is retried transparently.
3829
+
3830
+ WARNING. If the argument is an `IO` it needs to respond to `rewind` to be able to retry. Regular files respond to `rewind`.
3831
+
3832
+ NOTE: Defined in `active_support/core_ext/marshal.rb`.
3833
+
3834
+ Extensions to `Logger`
3835
+ ----------------------
3836
+
3837
+ ### `around_[level]`
3838
+
3839
+ Takes two arguments, a `before_message` and `after_message` and calls the current level method on the `Logger` instance, passing in the `before_message`, then the specified message, then the `after_message`:
3840
+
3841
+ ```ruby
3842
+ logger = Logger.new("log/development.log")
3843
+ logger.around_info("before", "after") { |logger| logger.info("during") }
3844
+ ```
3845
+
3846
+ ### `silence`
3847
+
3848
+ 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.
3849
+
3850
+ ```ruby
3851
+ logger = Logger.new("log/development.log")
3852
+ logger.silence(Logger::INFO) do
3853
+ logger.debug("In space, no one can hear you scream.")
3854
+ logger.info("Scream all you want, small mailman!")
3855
+ end
3856
+ ```
3857
+
3858
+ ### `datetime_format=`
3859
+
3860
+ Modifies the datetime format output by the formatter class associated with this logger. If the formatter class does not have a `datetime_format` method then this is ignored.
3861
+
3862
+ ```ruby
3863
+ class Logger::FormatWithTime < Logger::Formatter
3864
+ cattr_accessor(:datetime_format) { "%Y%m%d%H%m%S" }
3865
+
3866
+ def self.call(severity, timestamp, progname, msg)
3867
+ "#{timestamp.strftime(datetime_format)} -- #{String === msg ? msg : msg.inspect}\n"
3868
+ end
3869
+ end
3870
+
3871
+ logger = Logger.new("log/development.log")
3872
+ logger.formatter = Logger::FormatWithTime
3873
+ logger.info("<- is the current time")
3874
+ ```
3875
+
3876
+ NOTE: Defined in `active_support/core_ext/logger.rb`.
3877
+
3878
+ Extensions to `NameError`
3879
+ -------------------------
3880
+
3881
+ Active Support adds `missing_name?` to `NameError`, which tests whether the exception was raised because of the name passed as argument.
3882
+
3883
+ 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.
3884
+
3885
+ TIP: A symbol can represent a fully-qualified constant name as in `:"ActiveRecord::Base"`, so the behavior for symbols is defined for convenience, not because it has to be that way technically.
3886
+
3887
+ For example, when an action of `ArticlesController` is called Rails tries optimistically to use `ArticlesHelper`. 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 `articles_helper.rb` raises a `NameError` due to an actual unknown constant. That should be reraised. The method `missing_name?` provides a way to distinguish both cases:
3888
+
3889
+ ```ruby
3890
+ def default_helper_module!
3891
+ module_name = name.sub(/Controller$/, '')
3892
+ module_path = module_name.underscore
3893
+ helper module_path
3894
+ rescue MissingSourceFile => e
3895
+ raise e unless e.is_missing? "helpers/#{module_path}_helper"
3896
+ rescue NameError => e
3897
+ raise e unless e.missing_name? "#{module_name}Helper"
3898
+ end
3899
+ ```
3900
+
3901
+ NOTE: Defined in `active_support/core_ext/name_error.rb`.
3902
+
3903
+ Extensions to `LoadError`
3904
+ -------------------------
3905
+
3906
+ Active Support adds `is_missing?` to `LoadError`, and also assigns that class to the constant `MissingSourceFile` for backwards compatibility.
3907
+
3908
+ Given a path name `is_missing?` tests whether the exception was raised due to that particular file (except perhaps for the ".rb" extension).
3909
+
3910
+ For example, when an action of `ArticlesController` is called Rails tries to load `articles_helper.rb`, but that file may not exist. That's fine, the helper module is not mandatory so Rails silences a load error. But it could be the case that the helper module does exist and in turn requires another library that is missing. In that case Rails must reraise the exception. The method `is_missing?` provides a way to distinguish both cases:
3911
+
3912
+ ```ruby
3913
+ def default_helper_module!
3914
+ module_name = name.sub(/Controller$/, '')
3915
+ module_path = module_name.underscore
3916
+ helper module_path
3917
+ rescue MissingSourceFile => e
3918
+ raise e unless e.is_missing? "helpers/#{module_path}_helper"
3919
+ rescue NameError => e
3920
+ raise e unless e.missing_name? "#{module_name}Helper"
3921
+ end
3922
+ ```
3923
+
3924
+ NOTE: Defined in `active_support/core_ext/load_error.rb`.