rails 4.2.0.beta4 → 4.2.0.rc1

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