rails 3.2.22.5 → 4.0.0.beta1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

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