railties 3.2.22.5 → 4.0.0.beta1

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