railties 3.0.0.beta

Sign up to get free protection for your applications and to get access to all the features.
Files changed (334) hide show
  1. data/CHANGELOG +2201 -0
  2. data/README +286 -0
  3. data/bin/rails +11 -0
  4. data/builtin/rails_info/rails/info.rb +147 -0
  5. data/builtin/rails_info/rails/info_controller.rb +15 -0
  6. data/builtin/rails_info/rails/info_helper.rb +2 -0
  7. data/builtin/routes.rb +3 -0
  8. data/guides/files/javascripts/code_highlighter.js +188 -0
  9. data/guides/files/javascripts/guides.js +7 -0
  10. data/guides/files/javascripts/highlighters.js +90 -0
  11. data/guides/files/stylesheets/main.css +441 -0
  12. data/guides/files/stylesheets/print.css +52 -0
  13. data/guides/files/stylesheets/reset.css +43 -0
  14. data/guides/files/stylesheets/style.css +13 -0
  15. data/guides/files/stylesheets/syntax.css +31 -0
  16. data/guides/images/belongs_to.png +0 -0
  17. data/guides/images/book_icon.gif +0 -0
  18. data/guides/images/bullet.gif +0 -0
  19. data/guides/images/chapters_icon.gif +0 -0
  20. data/guides/images/check_bullet.gif +0 -0
  21. data/guides/images/credits_pic_blank.gif +0 -0
  22. data/guides/images/csrf.png +0 -0
  23. data/guides/images/customized_error_messages.png +0 -0
  24. data/guides/images/error_messages.png +0 -0
  25. data/guides/images/feature_tile.gif +0 -0
  26. data/guides/images/footer_tile.gif +0 -0
  27. data/guides/images/fxn.png +0 -0
  28. data/guides/images/grey_bullet.gif +0 -0
  29. data/guides/images/habtm.png +0 -0
  30. data/guides/images/has_many.png +0 -0
  31. data/guides/images/has_many_through.png +0 -0
  32. data/guides/images/has_one.png +0 -0
  33. data/guides/images/has_one_through.png +0 -0
  34. data/guides/images/header_backdrop.png +0 -0
  35. data/guides/images/header_tile.gif +0 -0
  36. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  37. data/guides/images/i18n/demo_translated_en.png +0 -0
  38. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  39. data/guides/images/i18n/demo_translation_missing.png +0 -0
  40. data/guides/images/i18n/demo_untranslated.png +0 -0
  41. data/guides/images/icons/README +5 -0
  42. data/guides/images/icons/callouts/1.png +0 -0
  43. data/guides/images/icons/callouts/10.png +0 -0
  44. data/guides/images/icons/callouts/11.png +0 -0
  45. data/guides/images/icons/callouts/12.png +0 -0
  46. data/guides/images/icons/callouts/13.png +0 -0
  47. data/guides/images/icons/callouts/14.png +0 -0
  48. data/guides/images/icons/callouts/15.png +0 -0
  49. data/guides/images/icons/callouts/2.png +0 -0
  50. data/guides/images/icons/callouts/3.png +0 -0
  51. data/guides/images/icons/callouts/4.png +0 -0
  52. data/guides/images/icons/callouts/5.png +0 -0
  53. data/guides/images/icons/callouts/6.png +0 -0
  54. data/guides/images/icons/callouts/7.png +0 -0
  55. data/guides/images/icons/callouts/8.png +0 -0
  56. data/guides/images/icons/callouts/9.png +0 -0
  57. data/guides/images/icons/caution.png +0 -0
  58. data/guides/images/icons/example.png +0 -0
  59. data/guides/images/icons/home.png +0 -0
  60. data/guides/images/icons/important.png +0 -0
  61. data/guides/images/icons/next.png +0 -0
  62. data/guides/images/icons/note.png +0 -0
  63. data/guides/images/icons/prev.png +0 -0
  64. data/guides/images/icons/tip.png +0 -0
  65. data/guides/images/icons/up.png +0 -0
  66. data/guides/images/icons/warning.png +0 -0
  67. data/guides/images/nav_arrow.gif +0 -0
  68. data/guides/images/polymorphic.png +0 -0
  69. data/guides/images/posts_index.png +0 -0
  70. data/guides/images/rails_guides_logo.gif +0 -0
  71. data/guides/images/rails_logo_remix.gif +0 -0
  72. data/guides/images/rails_welcome.png +0 -0
  73. data/guides/images/session_fixation.png +0 -0
  74. data/guides/images/tab_grey.gif +0 -0
  75. data/guides/images/tab_info.gif +0 -0
  76. data/guides/images/tab_note.gif +0 -0
  77. data/guides/images/tab_red.gif +0 -0
  78. data/guides/images/tab_yellow.gif +0 -0
  79. data/guides/images/tab_yellow.png +0 -0
  80. data/guides/images/validation_error_messages.png +0 -0
  81. data/guides/rails_guides.rb +44 -0
  82. data/guides/rails_guides/generator.rb +178 -0
  83. data/guides/rails_guides/helpers.rb +34 -0
  84. data/guides/rails_guides/indexer.rb +55 -0
  85. data/guides/rails_guides/levenshtein.rb +31 -0
  86. data/guides/rails_guides/textile_extensions.rb +41 -0
  87. data/guides/source/2_2_release_notes.textile +422 -0
  88. data/guides/source/2_3_release_notes.textile +610 -0
  89. data/guides/source/3_0_release_notes.textile +560 -0
  90. data/guides/source/action_controller_overview.textile +783 -0
  91. data/guides/source/action_mailer_basics.textile +437 -0
  92. data/guides/source/action_view_overview.textile +1481 -0
  93. data/guides/source/active_record_basics.textile +204 -0
  94. data/guides/source/active_record_querying.textile +961 -0
  95. data/guides/source/active_support_core_extensions.textile +1835 -0
  96. data/guides/source/activerecord_validations_callbacks.textile +1127 -0
  97. data/guides/source/ajax_on_rails.textile +342 -0
  98. data/guides/source/association_basics.textile +1816 -0
  99. data/guides/source/caching_with_rails.textile +390 -0
  100. data/guides/source/command_line.textile +589 -0
  101. data/guides/source/configuring.textile +290 -0
  102. data/guides/source/contribute.textile +71 -0
  103. data/guides/source/contributing_to_rails.textile +272 -0
  104. data/guides/source/credits.textile.erb +52 -0
  105. data/guides/source/debugging_rails_applications.textile +709 -0
  106. data/guides/source/form_helpers.textile +768 -0
  107. data/guides/source/generators.textile +378 -0
  108. data/guides/source/getting_started.textile +1310 -0
  109. data/guides/source/i18n.textile +879 -0
  110. data/guides/source/index.textile.erb +124 -0
  111. data/guides/source/layout.html.erb +103 -0
  112. data/guides/source/layouts_and_rendering.textile +979 -0
  113. data/guides/source/migrations.textile +591 -0
  114. data/guides/source/nested_model_forms.textile +222 -0
  115. data/guides/source/performance_testing.textile +531 -0
  116. data/guides/source/plugins.textile +1512 -0
  117. data/guides/source/rails_application_templates.textile +238 -0
  118. data/guides/source/rails_on_rack.textile +306 -0
  119. data/guides/source/routing.textile +903 -0
  120. data/guides/source/security.textile +984 -0
  121. data/guides/source/testing.textile +946 -0
  122. data/lib/generators/erb.rb +8 -0
  123. data/lib/generators/erb/controller/controller_generator.rb +21 -0
  124. data/lib/generators/erb/controller/templates/view.html.erb +2 -0
  125. data/lib/generators/erb/mailer/mailer_generator.rb +20 -0
  126. data/lib/generators/erb/mailer/templates/view.text.erb +3 -0
  127. data/lib/generators/erb/scaffold/scaffold_generator.rb +53 -0
  128. data/lib/generators/erb/scaffold/templates/_form.html.erb +13 -0
  129. data/lib/generators/erb/scaffold/templates/edit.html.erb +6 -0
  130. data/lib/generators/erb/scaffold/templates/index.html.erb +27 -0
  131. data/lib/generators/erb/scaffold/templates/layout.html.erb +16 -0
  132. data/lib/generators/erb/scaffold/templates/new.html.erb +5 -0
  133. data/lib/generators/erb/scaffold/templates/show.html.erb +10 -0
  134. data/lib/generators/rails/app/USAGE +9 -0
  135. data/lib/generators/rails/app/app_generator.rb +262 -0
  136. data/lib/generators/rails/app/templates/Gemfile +34 -0
  137. data/lib/generators/rails/app/templates/README +243 -0
  138. data/lib/generators/rails/app/templates/Rakefile +10 -0
  139. data/lib/generators/rails/app/templates/app/controllers/application_controller.rb +3 -0
  140. data/lib/generators/rails/app/templates/app/helpers/application_helper.rb +2 -0
  141. data/lib/generators/rails/app/templates/app/models/.empty_directory +0 -0
  142. data/lib/generators/rails/app/templates/app/views/layouts/.empty_directory +0 -0
  143. data/lib/generators/rails/app/templates/config.ru +4 -0
  144. data/lib/generators/rails/app/templates/config/application.rb +51 -0
  145. data/lib/generators/rails/app/templates/config/boot.rb +17 -0
  146. data/lib/generators/rails/app/templates/config/databases/frontbase.yml +28 -0
  147. data/lib/generators/rails/app/templates/config/databases/ibm_db.yml +71 -0
  148. data/lib/generators/rails/app/templates/config/databases/mysql.yml +60 -0
  149. data/lib/generators/rails/app/templates/config/databases/oracle.yml +39 -0
  150. data/lib/generators/rails/app/templates/config/databases/postgresql.yml +51 -0
  151. data/lib/generators/rails/app/templates/config/databases/sqlite3.yml +22 -0
  152. data/lib/generators/rails/app/templates/config/environment.rb +5 -0
  153. data/lib/generators/rails/app/templates/config/environments/development.rb.tt +19 -0
  154. data/lib/generators/rails/app/templates/config/environments/production.rb.tt +33 -0
  155. data/lib/generators/rails/app/templates/config/environments/test.rb.tt +29 -0
  156. data/lib/generators/rails/app/templates/config/initializers/backtrace_silencers.rb +7 -0
  157. data/lib/generators/rails/app/templates/config/initializers/cookie_verification_secret.rb.tt +7 -0
  158. data/lib/generators/rails/app/templates/config/initializers/inflections.rb +10 -0
  159. data/lib/generators/rails/app/templates/config/initializers/mime_types.rb +5 -0
  160. data/lib/generators/rails/app/templates/config/initializers/session_store.rb.tt +15 -0
  161. data/lib/generators/rails/app/templates/config/locales/en.yml +5 -0
  162. data/lib/generators/rails/app/templates/config/routes.rb +58 -0
  163. data/lib/generators/rails/app/templates/db/seeds.rb +7 -0
  164. data/lib/generators/rails/app/templates/doc/README_FOR_APP +2 -0
  165. data/lib/generators/rails/app/templates/gitignore +4 -0
  166. data/lib/generators/rails/app/templates/public/404.html +26 -0
  167. data/lib/generators/rails/app/templates/public/422.html +26 -0
  168. data/lib/generators/rails/app/templates/public/500.html +26 -0
  169. data/lib/generators/rails/app/templates/public/favicon.ico +0 -0
  170. data/lib/generators/rails/app/templates/public/images/rails.png +0 -0
  171. data/lib/generators/rails/app/templates/public/index.html +278 -0
  172. data/lib/generators/rails/app/templates/public/javascripts/application.js +2 -0
  173. data/lib/generators/rails/app/templates/public/javascripts/controls.js +963 -0
  174. data/lib/generators/rails/app/templates/public/javascripts/dragdrop.js +973 -0
  175. data/lib/generators/rails/app/templates/public/javascripts/effects.js +1128 -0
  176. data/lib/generators/rails/app/templates/public/javascripts/prototype.js +4320 -0
  177. data/lib/generators/rails/app/templates/public/javascripts/rails.js +110 -0
  178. data/lib/generators/rails/app/templates/public/robots.txt +5 -0
  179. data/lib/generators/rails/app/templates/public/stylesheets/.empty_directory +0 -0
  180. data/lib/generators/rails/app/templates/script/rails +9 -0
  181. data/lib/generators/rails/app/templates/test/fixtures/.empty_directory +0 -0
  182. data/lib/generators/rails/app/templates/test/functional/.empty_directory +0 -0
  183. data/lib/generators/rails/app/templates/test/integration/.empty_directory +0 -0
  184. data/lib/generators/rails/app/templates/test/performance/browsing_test.rb +9 -0
  185. data/lib/generators/rails/app/templates/test/test_helper.rb +13 -0
  186. data/lib/generators/rails/app/templates/test/unit/.empty_directory +0 -0
  187. data/lib/generators/rails/controller/USAGE +18 -0
  188. data/lib/generators/rails/controller/controller_generator.rb +14 -0
  189. data/lib/generators/rails/controller/templates/controller.rb +7 -0
  190. data/lib/generators/rails/generator/USAGE +11 -0
  191. data/lib/generators/rails/generator/generator_generator.rb +25 -0
  192. data/lib/generators/rails/generator/templates/%file_name%_generator.rb.tt +5 -0
  193. data/lib/generators/rails/generator/templates/USAGE.tt +8 -0
  194. data/lib/generators/rails/generator/templates/templates/.empty_directory +0 -0
  195. data/lib/generators/rails/helper/USAGE +17 -0
  196. data/lib/generators/rails/helper/helper_generator.rb +13 -0
  197. data/lib/generators/rails/helper/templates/helper.rb +2 -0
  198. data/lib/generators/rails/integration_test/USAGE +10 -0
  199. data/lib/generators/rails/integration_test/integration_test_generator.rb +7 -0
  200. data/lib/generators/rails/mailer/USAGE +15 -0
  201. data/lib/generators/rails/mailer/mailer_generator.rb +14 -0
  202. data/lib/generators/rails/mailer/templates/mailer.rb +16 -0
  203. data/lib/generators/rails/metal/USAGE +8 -0
  204. data/lib/generators/rails/metal/metal_generator.rb +11 -0
  205. data/lib/generators/rails/metal/templates/metal.rb +12 -0
  206. data/lib/generators/rails/migration/USAGE +29 -0
  207. data/lib/generators/rails/migration/migration_generator.rb +8 -0
  208. data/lib/generators/rails/model/USAGE +30 -0
  209. data/lib/generators/rails/model/model_generator.rb +8 -0
  210. data/lib/generators/rails/model_subclass/model_subclass_generator.rb +12 -0
  211. data/lib/generators/rails/observer/USAGE +12 -0
  212. data/lib/generators/rails/observer/observer_generator.rb +7 -0
  213. data/lib/generators/rails/performance_test/USAGE +10 -0
  214. data/lib/generators/rails/performance_test/performance_test_generator.rb +7 -0
  215. data/lib/generators/rails/plugin/USAGE +13 -0
  216. data/lib/generators/rails/plugin/plugin_generator.rb +47 -0
  217. data/lib/generators/rails/plugin/templates/MIT-LICENSE.tt +20 -0
  218. data/lib/generators/rails/plugin/templates/README.tt +13 -0
  219. data/lib/generators/rails/plugin/templates/Rakefile.tt +10 -0
  220. data/lib/generators/rails/plugin/templates/init.rb +1 -0
  221. data/lib/generators/rails/plugin/templates/install.rb +1 -0
  222. data/lib/generators/rails/plugin/templates/lib/%file_name%.rb.tt +1 -0
  223. data/lib/generators/rails/plugin/templates/lib/tasks/%file_name%_tasks.rake.tt +4 -0
  224. data/lib/generators/rails/plugin/templates/uninstall.rb +1 -0
  225. data/lib/generators/rails/resource/USAGE +23 -0
  226. data/lib/generators/rails/resource/resource_generator.rb +34 -0
  227. data/lib/generators/rails/scaffold/USAGE +29 -0
  228. data/lib/generators/rails/scaffold/scaffold_generator.rb +13 -0
  229. data/lib/generators/rails/scaffold_controller/USAGE +20 -0
  230. data/lib/generators/rails/scaffold_controller/scaffold_controller_generator.rb +27 -0
  231. data/lib/generators/rails/scaffold_controller/templates/controller.rb +85 -0
  232. data/lib/generators/rails/session_migration/USAGE +8 -0
  233. data/lib/generators/rails/session_migration/session_migration_generator.rb +8 -0
  234. data/lib/generators/rails/stylesheets/USAGE +5 -0
  235. data/lib/generators/rails/stylesheets/stylesheets_generator.rb +9 -0
  236. data/lib/generators/rails/stylesheets/templates/scaffold.css +61 -0
  237. data/lib/generators/test_unit.rb +8 -0
  238. data/lib/generators/test_unit/controller/controller_generator.rb +14 -0
  239. data/lib/generators/test_unit/controller/templates/functional_test.rb +8 -0
  240. data/lib/generators/test_unit/helper/helper_generator.rb +13 -0
  241. data/lib/generators/test_unit/helper/templates/helper_test.rb +4 -0
  242. data/lib/generators/test_unit/integration/integration_generator.rb +13 -0
  243. data/lib/generators/test_unit/integration/templates/integration_test.rb +10 -0
  244. data/lib/generators/test_unit/mailer/mailer_generator.rb +21 -0
  245. data/lib/generators/test_unit/mailer/templates/fixture +3 -0
  246. data/lib/generators/test_unit/mailer/templates/functional_test.rb +22 -0
  247. data/lib/generators/test_unit/model/model_generator.rb +24 -0
  248. data/lib/generators/test_unit/model/templates/fixtures.yml +23 -0
  249. data/lib/generators/test_unit/model/templates/unit_test.rb +8 -0
  250. data/lib/generators/test_unit/observer/observer_generator.rb +13 -0
  251. data/lib/generators/test_unit/observer/templates/unit_test.rb +8 -0
  252. data/lib/generators/test_unit/performance/performance_generator.rb +13 -0
  253. data/lib/generators/test_unit/performance/templates/performance_test.rb +9 -0
  254. data/lib/generators/test_unit/plugin/plugin_generator.rb +13 -0
  255. data/lib/generators/test_unit/plugin/templates/%file_name%_test.rb.tt +8 -0
  256. data/lib/generators/test_unit/plugin/templates/test_helper.rb +3 -0
  257. data/lib/generators/test_unit/scaffold/scaffold_generator.rb +18 -0
  258. data/lib/generators/test_unit/scaffold/templates/functional_test.rb +47 -0
  259. data/lib/rails.rb +95 -0
  260. data/lib/rails/all.rb +14 -0
  261. data/lib/rails/application.rb +125 -0
  262. data/lib/rails/application/bootstrap.rb +85 -0
  263. data/lib/rails/application/configurable.rb +19 -0
  264. data/lib/rails/application/configuration.rb +86 -0
  265. data/lib/rails/application/finisher.rb +49 -0
  266. data/lib/rails/application/metal_loader.rb +50 -0
  267. data/lib/rails/application/railties.rb +31 -0
  268. data/lib/rails/application/routes_reloader.rb +46 -0
  269. data/lib/rails/backtrace_cleaner.rb +54 -0
  270. data/lib/rails/code_statistics.rb +107 -0
  271. data/lib/rails/commands.rb +72 -0
  272. data/lib/rails/commands/application.rb +13 -0
  273. data/lib/rails/commands/console.rb +55 -0
  274. data/lib/rails/commands/dbconsole.rb +104 -0
  275. data/lib/rails/commands/destroy.rb +9 -0
  276. data/lib/rails/commands/generate.rb +9 -0
  277. data/lib/rails/commands/performance/benchmarker.rb +23 -0
  278. data/lib/rails/commands/performance/profiler.rb +46 -0
  279. data/lib/rails/commands/plugin.rb +542 -0
  280. data/lib/rails/commands/runner.rb +51 -0
  281. data/lib/rails/commands/server.rb +75 -0
  282. data/lib/rails/commands/update.rb +9 -0
  283. data/lib/rails/configuration.rb +191 -0
  284. data/lib/rails/console/app.rb +33 -0
  285. data/lib/rails/console/helpers.rb +5 -0
  286. data/lib/rails/console/sandbox.rb +6 -0
  287. data/lib/rails/deprecation.rb +62 -0
  288. data/lib/rails/dispatcher.rb +24 -0
  289. data/lib/rails/engine.rb +130 -0
  290. data/lib/rails/engine/configurable.rb +25 -0
  291. data/lib/rails/engine/configuration.rb +49 -0
  292. data/lib/rails/generators.rb +289 -0
  293. data/lib/rails/generators/actions.rb +309 -0
  294. data/lib/rails/generators/active_model.rb +78 -0
  295. data/lib/rails/generators/base.rb +362 -0
  296. data/lib/rails/generators/generated_attribute.rb +48 -0
  297. data/lib/rails/generators/migration.rb +64 -0
  298. data/lib/rails/generators/named_base.rb +95 -0
  299. data/lib/rails/generators/resource_helpers.rb +80 -0
  300. data/lib/rails/generators/test_case.rb +239 -0
  301. data/lib/rails/initializable.rb +97 -0
  302. data/lib/rails/paths.rb +144 -0
  303. data/lib/rails/performance_test_help.rb +3 -0
  304. data/lib/rails/plugin.rb +64 -0
  305. data/lib/rails/rack.rb +8 -0
  306. data/lib/rails/rack/debugger.rb +23 -0
  307. data/lib/rails/rack/log_tailer.rb +33 -0
  308. data/lib/rails/rack/logger.rb +34 -0
  309. data/lib/rails/rack/static.rb +5 -0
  310. data/lib/rails/railtie.rb +74 -0
  311. data/lib/rails/railtie/configurable.rb +23 -0
  312. data/lib/rails/railtie/configuration.rb +9 -0
  313. data/lib/rails/railties_path.rb +1 -0
  314. data/lib/rails/ruby_version_check.rb +10 -0
  315. data/lib/rails/rubyprof_ext.rb +35 -0
  316. data/lib/rails/source_annotation_extractor.rb +102 -0
  317. data/lib/rails/subscriber.rb +108 -0
  318. data/lib/rails/subscriber/test_helper.rb +98 -0
  319. data/lib/rails/tasks.rb +16 -0
  320. data/lib/rails/tasks/annotations.rake +20 -0
  321. data/lib/rails/tasks/documentation.rake +96 -0
  322. data/lib/rails/tasks/framework.rake +69 -0
  323. data/lib/rails/tasks/log.rake +9 -0
  324. data/lib/rails/tasks/middleware.rake +7 -0
  325. data/lib/rails/tasks/misc.rake +71 -0
  326. data/lib/rails/tasks/routes.rake +17 -0
  327. data/lib/rails/tasks/statistics.rake +16 -0
  328. data/lib/rails/tasks/tmp.rake +37 -0
  329. data/lib/rails/test_help.rb +30 -0
  330. data/lib/rails/test_unit/railtie.rb +17 -0
  331. data/lib/rails/test_unit/testing.rake +130 -0
  332. data/lib/rails/version.rb +9 -0
  333. data/lib/rails/webrick_server.rb +156 -0
  334. metadata +427 -0
@@ -0,0 +1,390 @@
1
+ h2. Caching with Rails: An overview
2
+
3
+ This guide will teach you what you need to know about avoiding that expensive round-trip to your database and returning what you need to return to the web clients in the shortest time possible.
4
+
5
+ After reading this guide, you should be able to use and configure:
6
+
7
+ * Page, action, and fragment caching
8
+ * Sweepers
9
+ * Alternative cache stores
10
+ * Conditional GET support
11
+
12
+ endprologue.
13
+
14
+ h3. Basic Caching
15
+
16
+ This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins.
17
+
18
+ To start playing with testing you'll want to ensure that +config.action_controller.perform_caching+ is set to +true+ if you're running in development mode. This flag is normally set in the corresponding +config/environments/*.rb+ and caching is disabled by default for development and test, and enabled for production.
19
+
20
+ <ruby>
21
+ config.action_controller.perform_caching = true
22
+ </ruby>
23
+
24
+ h4. Page Caching
25
+
26
+ Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can't be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.
27
+
28
+ So, how do you enable this super-fast cache behavior? Simple, let's say you have a controller called +ProductsController+ and an +index+ action that lists all the products
29
+
30
+ <ruby>
31
+ class ProductsController < ActionController
32
+
33
+ caches_page :index
34
+
35
+ def index
36
+ @products = Products.all
37
+ end
38
+
39
+ end
40
+ </ruby>
41
+
42
+ The first time anyone requests +/products+, Rails will generate a file called +products.html+ and the webserver will then look for that file before it passes the next request for +/products+ to your Rails application.
43
+
44
+ By default, the page cache directory is set to +Rails.public_path+ (which is usually set to the +public+ folder) and this can be configured by changing the configuration setting +config.action_controller.page_cache_directory+. Changing the default from +public+ helps avoid naming conflicts, since you may want to put other static html in +public+, but changing this will require web server reconfiguration to let the web server know where to serve the cached files from.
45
+
46
+ The Page Caching mechanism will automatically add a +.html+ extension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the configuration setting +config.action_controller.page_cache_extension+.
47
+
48
+ In order to expire this page when a new product is added we could extend our example controller like this:
49
+
50
+ <ruby>
51
+ class ProductsController < ActionController
52
+
53
+ caches_page :index
54
+
55
+ def index
56
+ @products = Products.all
57
+ end
58
+
59
+ def create
60
+ expire_page :action => :list
61
+ end
62
+
63
+ end
64
+ </ruby>
65
+
66
+ If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.
67
+
68
+ Note: Page caching ignores all parameters. For example +/products?page=1+ will be written out to the filesystem as +products.html+ with no reference to the +page+ parameter. Thus, if someone requests +/products?page=2+ later, they will get the cached first page. Be careful when page caching GET parameters in the URL!
69
+
70
+ INFO: Page caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
71
+
72
+ h4. Action Caching
73
+
74
+ One of the issues with Page Caching is that you cannot use it for pages that require to restrict access somehow. This is where Action Caching comes in. Action Caching works like Page Caching except for the fact that the incoming web request does go from the webserver to the Rails stack and Action Pack so that before filters can be run on it before the cache is served. This allows authentication and other restriction to be run while still serving the result of the output from a cached copy.
75
+
76
+ Clearing the cache works in the exact same way as with Page Caching.
77
+
78
+ Let's say you only wanted authenticated users to call actions on +ProductsController+.
79
+
80
+ <ruby>
81
+ class ProductsController < ActionController
82
+
83
+ before_filter :authenticate
84
+ caches_action :index
85
+
86
+ def index
87
+ @products = Product.all
88
+ end
89
+
90
+ def create
91
+ expire_action :action => :index
92
+ end
93
+
94
+ end
95
+ </ruby>
96
+
97
+ You can also use +:if+ (or +:unless+) to pass a Proc that specifies when the action should be cached. Also, you can use +:layout => false+ to cache without layout so that dynamic information in the layout such as logged in user info or the number of items in the cart can be left uncached. This feature is available as of Rails 2.2.
98
+
99
+ You can modify the default action cache path by passing a +:cache_path+ option. This will be passed directly to +ActionCachePath.path_for+. This is handy for actions with multiple possible routes that should be cached differently. If a block is given, it is called with the current controller instance.
100
+
101
+ Finally, if you are using memcached, you can also pass +:expires_in+. In fact, all parameters not used by +caches_action+ are sent to the underlying cache store.
102
+
103
+ INFO: Action caching runs in an after filter. Thus, invalid requests won't generate spurious cache entries as long as you halt them. Typically, a redirection in some before filter that checks request preconditions does the job.
104
+
105
+ h4. Fragment Caching
106
+
107
+ Life would be perfect if we could get away with caching the entire contents of a page or action and serving it out to the world. Unfortunately, dynamic web applications usually build pages with a variety of components not all of which have the same caching characteristics. In order to address such a dynamically created page where different parts of the page need to be cached and expired differently Rails provides a mechanism called Fragment Caching.
108
+
109
+ Fragment Caching allows a fragment of view logic to be wrapped in a cache block and served out of the cache store when the next request comes in.
110
+
111
+ As an example, if you wanted to show all the orders placed on your website in real time and didn't want to cache that part of the page, but did want to cache the part of the page which lists all products available, you could use this piece of code:
112
+
113
+ <ruby>
114
+ <% Order.find_recent.each do |o| %>
115
+ <%= o.buyer.name %> bought <% o.product.name %>
116
+ <% end %>
117
+
118
+ <% cache do %>
119
+ All available products:
120
+ <% Product.all.each do |p| %>
121
+ <%= link_to p.name, product_url(p) %>
122
+ <% end %>
123
+ <% end %>
124
+ </ruby>
125
+
126
+ The cache block in our example will bind to the action that called it and is written out to the same place as the Action Cache, which means that if you want to cache multiple fragments per action, you should provide an +action_suffix+ to the cache call:
127
+
128
+ <ruby>
129
+ <% cache(:action => 'recent', :action_suffix => 'all_products') do %>
130
+ All available products:
131
+ </ruby>
132
+
133
+ and you can expire it using the +expire_fragment+ method, like so:
134
+
135
+ <ruby>
136
+ expire_fragment(:controller => 'products', :action => 'recent', :action_suffix => 'all_products')
137
+ </ruby>
138
+
139
+ If you don't want the cache block to bind to the action that called it, You can also use globally keyed fragments by calling the +cache+ method with a key, like so:
140
+
141
+ <ruby>
142
+ <% cache('all_available_products') do %>
143
+ All available products:
144
+ <% end %>
145
+ </ruby>
146
+
147
+ This fragment is then available to all actions in the +ProductsController+ using the key and can be expired the same way:
148
+
149
+ <ruby>
150
+ expire_fragment('all_available_products')
151
+ </ruby>
152
+
153
+ h4. Sweepers
154
+
155
+ Cache sweeping is a mechanism which allows you to get around having a ton of +expire_{page,action,fragment}+ calls in your code. It does this by moving all the work required to expire cached content into a +ActionController::Caching::Sweeper+ class. This class is an Observer and looks for changes to an object via callbacks, and when a change occurs it expires the caches associated with that object in an around or after filter.
156
+
157
+ Continuing with our Product controller example, we could rewrite it with a sweeper like this:
158
+
159
+ <ruby>
160
+ class ProductSweeper < ActionController::Caching::Sweeper
161
+ observe Product # This sweeper is going to keep an eye on the Product model
162
+
163
+ # If our sweeper detects that a Product was created call this
164
+ def after_create(product)
165
+ expire_cache_for(product)
166
+ end
167
+
168
+ # If our sweeper detects that a Product was updated call this
169
+ def after_update(product)
170
+ expire_cache_for(product)
171
+ end
172
+
173
+ # If our sweeper detects that a Product was deleted call this
174
+ def after_destroy(product)
175
+ expire_cache_for(product)
176
+ end
177
+
178
+ private
179
+ def expire_cache_for(product)
180
+ # Expire the index page now that we added a new product
181
+ expire_page(:controller => 'products', :action => 'index')
182
+
183
+ # Expire a fragment
184
+ expire_fragment('all_available_products')
185
+ end
186
+ end
187
+ </ruby>
188
+
189
+ You may notice that the actual product gets passed to the sweeper, so if we were caching the edit action for each product, we could add an expire method which specifies the page we want to expire:
190
+
191
+ <ruby>
192
+ expire_action(:controller => 'products', :action => 'edit', :id => product)
193
+ </ruby>
194
+
195
+ Then we add it to our controller to tell it to call the sweeper when certain actions are called. So, if we wanted to expire the cached content for the list and edit actions when the create action was called, we could do the following:
196
+
197
+ <ruby>
198
+ class ProductsController < ActionController
199
+
200
+ before_filter :authenticate
201
+ caches_action :index
202
+ cache_sweeper :product_sweeper
203
+
204
+ def index
205
+ @products = Product.all
206
+ end
207
+
208
+ end
209
+ </ruby>
210
+
211
+ h4. SQL Caching
212
+
213
+ Query caching is a Rails feature that caches the result set returned by each query so that if Rails encounters the same query again for that request, it will use the cached result set as opposed to running the query against the database again.
214
+
215
+ For example:
216
+
217
+ <ruby>
218
+ class ProductsController < ActionController
219
+
220
+ def index
221
+ # Run a find query
222
+ @products = Product.all
223
+
224
+ ...
225
+
226
+ # Run the same query again
227
+ @products = Product.all
228
+ end
229
+
230
+ end
231
+ </ruby>
232
+
233
+ The second time the same query is run against the database, it's not actually going to hit the database. The first time the result is returned from the query it is stored in the query cache (in memory) and the second time it's pulled from memory.
234
+
235
+ However, it's important to note that query caches are created at the start of an action and destroyed at the end of that action and thus persist only for the duration of the action. If you'd like to store query results in a more persistent fashion, you can in Rails by using low level caching.
236
+
237
+ h3. Cache Stores
238
+
239
+ Rails provides different stores for the cached data created by action and fragment caches. Page caches are always stored on disk.
240
+
241
+ Rails 2.1 and above provide +ActiveSupport::Cache::Store+ which can be used to cache strings. Some cache store implementations, like +MemoryStore+, are able to cache arbitrary Ruby objects, but don't count on every cache store to be able to do that.
242
+
243
+ The default cache stores provided with Rails include:
244
+
245
+ 1) +ActiveSupport::Cache::MemoryStore+: A cache store implementation which stores everything into memory in the same process. If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then this means that your Rails server process instances won't be able to share cache data with each other. If your application never performs manual cache item expiry (e.g. when you‘re using generational cache keys), then using +MemoryStore+ is ok. Otherwise, consider carefully whether you should be using this cache store.
246
+
247
+ +MemoryStore+ is not only able to store strings, but also arbitrary Ruby objects.
248
+
249
+ +MemoryStore+ is not thread-safe. Use +SynchronizedMemoryStore+ instead if you need thread-safety.
250
+
251
+ <ruby>
252
+ ActionController::Base.cache_store = :memory_store
253
+ </ruby>
254
+
255
+ 2) +ActiveSupport::Cache::FileStore+: Cached data is stored on the disk, this is the default store and the default path for this store is +tmp/cache+. Works well for all types of environments and allows all processes running from the same application directory to access the cached content. If +tmp/cache+ does not exist, the default store becomes +MemoryStore+.
256
+
257
+ <ruby>
258
+ ActionController::Base.cache_store = :file_store, "/path/to/cache/directory"
259
+ </ruby>
260
+
261
+ 3) +ActiveSupport::Cache::DRbStore+: Cached data is stored in a separate shared DRb process that all servers communicate with. This works for all environments and only keeps one cache around for all processes, but requires that you run and manage a separate DRb process.
262
+
263
+ <ruby>
264
+ ActionController::Base.cache_store = :drb_store, "druby://localhost:9192"
265
+ </ruby>
266
+
267
+ 4) +ActiveSupport::Cache::MemCacheStore+: Works like +DRbStore+, but uses Danga's +memcached+ instead. Rails uses the bundled +memcached-client+ gem by default. This is currently the most popular cache store for production websites.
268
+
269
+ Special features:
270
+
271
+ * Clustering and load balancing. One can specify multiple memcached servers, and +MemCacheStore+ will load balance between all available servers. If a server goes down, then +MemCacheStore+ will ignore it until it goes back online.
272
+ * Time-based expiry support. See +write+ and the +:expires_in+ option.
273
+ * Per-request in memory cache for all communication with the +memcached+ server(s).
274
+
275
+ It also accepts a hash of additional options:
276
+
277
+ * +:namespace+: specifies a string that will automatically be prepended to keys when accessing the memcached store.
278
+ * +:readonly+: a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
279
+ * +:multithread+: a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality.
280
+
281
+ The read and write methods of the +MemCacheStore+ accept an options hash too. When reading you can specify +:raw => true+ to prevent the object being marshaled (by default this is false which means the raw value in the cache is passed to +Marshal.load+ before being returned to you.)
282
+
283
+ When writing to the cache it is also possible to specify +:raw => true+ means the value is not passed to +Marshal.dump+ before being stored in the cache (by default this is false).
284
+
285
+ The write method also accepts an +:unless_exist+ flag which determines whether the memcached add (when true) or set (when false) method is used to store the item in the cache and an +:expires_in+ option that specifies the time-to-live for the cached item in seconds.
286
+
287
+ <ruby>
288
+ ActionController::Base.cache_store = :mem_cache_store, "localhost"
289
+ </ruby>
290
+
291
+ 5) +ActiveSupport::Cache::SynchronizedMemoryStore+: Like +MemoryStore+ but thread-safe.
292
+
293
+ <ruby>
294
+ ActionController::Base.cache_store = :synchronized_memory_store
295
+ </ruby>
296
+
297
+ 6) +ActiveSupport::Cache::CompressedMemCacheStore+: Works just like the regular +MemCacheStore+ but uses GZip to decompress/compress on read/write.
298
+
299
+ <ruby>
300
+ ActionController::Base.cache_store = :compressed_mem_cache_store, "localhost"
301
+ </ruby>
302
+
303
+ 7) Custom store: You can define your own cache store (new in Rails 2.1).
304
+
305
+ <ruby>
306
+ ActionController::Base.cache_store = MyOwnStore.new("parameter")
307
+ </ruby>
308
+
309
+ NOTE: +config.cache_store+ can be used in place of +ActionController::Base.cache_store+ in your +Rails::Initializer.run+ block in +environment.rb+
310
+
311
+ In addition to all of this, Rails also adds the +ActiveRecord::Base#cache_key+ method that generates a key using the class name, +id+ and +updated_at+ timestamp (if available).
312
+
313
+ You can access these cache stores at a low level for storing queries and other objects. Here's an example:
314
+
315
+ <ruby>
316
+ Rails.cache.read("city") # => nil
317
+ Rails.cache.write("city", "Duckburgh")
318
+ Rails.cache.read("city") # => "Duckburgh"
319
+ </ruby>
320
+
321
+ h3. Conditional GET support
322
+
323
+ Conditional GETs are a feature of the HTTP specification that provide a way for web servers to tell browsers that the response to a GET request hasn't changed since the last request and can be safely pulled from the browser cache.
324
+
325
+ They work by using the +HTTP_IF_NONE_MATCH+ and +HTTP_IF_MODIFIED_SINCE+ headers to pass back and forth both a unique content identifier and the timestamp of when the content was last changed. If the browser makes a request where the content identifier (etag) or last modified since timestamp matches the server’s version then the server only needs to send back an empty response with a not modified status.
326
+
327
+ It is the server's (i.e. our) responsibility to look for a last modified timestamp and the if-none-match header and determine whether or not to send back the full response. With conditional-get support in Rails this is a pretty easy task:
328
+
329
+ <ruby>
330
+ class ProductsController < ApplicationController
331
+
332
+ def show
333
+ @product = Product.find(params[:id])
334
+
335
+ # If the request is stale according to the given timestamp and etag value
336
+ # (i.e. it needs to be processed again) then execute this block
337
+ if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
338
+ respond_to do |wants|
339
+ # ... normal response processing
340
+ end
341
+ end
342
+
343
+ # If the request is fresh (i.e. it's not modified) then you don't need to do
344
+ # anything. The default render checks for this using the parameters
345
+ # used in the previous call to stale? and will automatically send a
346
+ # :not_modified. So that's it, you're done.
347
+ end
348
+ </ruby>
349
+
350
+ If you don't have any special response processing and are using the default rendering mechanism (i.e. you're not using respond_to or calling render yourself) then you’ve got an easy helper in fresh_when:
351
+
352
+ <ruby>
353
+ class ProductsController < ApplicationController
354
+
355
+ # This will automatically send back a :not_modified if the request is fresh,
356
+ # and will render the default template (product.*) if it's stale.
357
+
358
+ def show
359
+ @product = Product.find(params[:id])
360
+ fresh_when :last_modified => @product.published_at.utc, :etag => @product
361
+ end
362
+ end
363
+ </ruby>
364
+
365
+ h3. Advanced Caching
366
+
367
+ Along with the built-in mechanisms outlined above, a number of excellent plugins exist to help with finer grained control over caching. These include Chris Wanstrath's excellent cache_fu plugin (more info "here": http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver's interlock plugin (more info "here": http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both of these plugins play nice with memcached and are a must-see for anyone
368
+ seriously considering optimizing their caching needs.
369
+
370
+ Also the new "Cache money":http://github.com/nkallen/cache-money/tree/master plugin is supposed to be mad cool.
371
+
372
+ h3. References
373
+
374
+ * "Scaling Rails Screencasts":http://railslab.newrelic.com/scaling-rails
375
+ * "RailsEnvy, Rails Caching Tutorial, Part 1":http://www.railsenvy.com/2007/2/28/rails-caching-tutorial
376
+ * "RailsEnvy, Rails Caching Tutorial, Part 2":http://www.railsenvy.com/2007/3/20/ruby-on-rails-caching-tutorial-part-2
377
+ * "ActiveSupport::Cache documentation":http://api.rubyonrails.org/classes/ActiveSupport/Cache.html
378
+ * "Rails 2.1 integrated caching tutorial":http://thewebfellas.com/blog/2008/6/9/rails-2-1-now-with-better-integrated-caching
379
+
380
+
381
+ h3. Changelog
382
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/10-guide-to-caching
383
+
384
+ * May 02, 2009: Formatting cleanups
385
+ * April 26, 2009: Clean up typos in submitted patch
386
+ * April 1, 2009: Made a bunch of small fixes
387
+ * February 22, 2009: Beefed up the section on cache_stores
388
+ * December 27, 2008: Typo fixes
389
+ * November 23, 2008: Incremental updates with various suggested changes and formatting cleanup
390
+ * September 15, 2008: Initial version by Aditya Chadha
@@ -0,0 +1,589 @@
1
+ h2. A Guide to The Rails Command Line
2
+
3
+ Rails comes with every command line tool you'll need to
4
+
5
+ * Create a Rails application
6
+ * Generate models, controllers, database migrations, and unit tests
7
+ * Start a development server
8
+ * Mess with objects through an interactive shell
9
+ * Profile and benchmark your new creation
10
+
11
+ NOTE: This tutorial assumes you have basic Rails knowledge from reading the "Getting Started with Rails Guide":getting_started.html.
12
+
13
+ endprologue.
14
+
15
+ h3. Command Line Basics
16
+
17
+ There are a few commands that are absolutely critical to your everyday usage of Rails. In the order of how much you'll probably use them are:
18
+
19
+ * console
20
+ * server
21
+ * rake
22
+ * generate
23
+ * rails
24
+
25
+ Let's create a simple Rails application to step through each of these commands in context.
26
+
27
+ h4. +rails+
28
+
29
+ The first thing we'll want to do is create a new Rails application by running the +rails+ command after installing Rails.
30
+
31
+ WARNING: You know you need the rails gem installed by typing +gem install rails+ first, right? Okay, okay, just making sure.
32
+
33
+ <shell>
34
+ $ rails commandsapp
35
+
36
+ create
37
+ create app/controllers
38
+ create app/helpers
39
+ create app/models
40
+ ...
41
+ ...
42
+ create log/production.log
43
+ create log/development.log
44
+ create log/test.log
45
+ </shell>
46
+
47
+ Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You've got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.
48
+
49
+ INFO: This output will seem very familiar when we get to the +generate+ command. Creepy foreshadowing!
50
+
51
+ h4. +server+
52
+
53
+ Let's try it! The +server+ command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to view your work through a web browser.
54
+
55
+ INFO: WEBrick isn't your only option for serving Rails. We'll get to that in a later section.
56
+
57
+ Without any prodding of any kind, +server+ will run our new shiny Rails app:
58
+
59
+ <shell>
60
+ $ cd commandsapp
61
+ $ ./script/server
62
+ => Booting WEBrick...
63
+ => Rails 2.2.0 application started on http://0.0.0.0:3000
64
+ => Ctrl-C to shutdown server; call with --help for options
65
+ [2008-11-04 10:11:38] INFO WEBrick 1.3.1
66
+ [2008-11-04 10:11:38] INFO ruby 1.8.5 (2006-12-04) [i486-linux]
67
+ [2008-11-04 10:11:38] INFO WEBrick::HTTPServer#start: pid=18994 port=3000
68
+ </shell>
69
+
70
+ WHOA. With just three commands we whipped up a Rails server listening on port 3000. Go! Go right now to your browser and go to http://localhost:3000. I'll wait.
71
+
72
+ See? Cool! It doesn't do much yet, but we'll change that.
73
+
74
+ h4. +generate+
75
+
76
+ The +generate+ command uses templates to create a whole lot of things. You can always find out what's available by running +generate+ by itself. Let's do that:
77
+
78
+ <shell>
79
+ $ ./script/generate
80
+ Usage: ./script/generate generator [options] [args]
81
+
82
+ ...
83
+ ...
84
+
85
+ Installed Generators
86
+ Built-in: controller, integration_test, mailer, migration, model, observer, performance_test, plugin, resource, scaffold, session_migration
87
+
88
+ ...
89
+ ...
90
+ </shell>
91
+
92
+ NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
93
+
94
+ Using generators will save you a large amount of time by writing *boilerplate code* for you -- necessary for the darn thing to work, but not necessary for you to spend time writing. That's what we have computers for, right?
95
+
96
+ Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
97
+
98
+ INFO: All Rails console utilities have help text. As with most *NIX utilities, you can try adding +--help+ or +-h+ to the end, for example +./script/server --help+.
99
+
100
+ <shell>
101
+ $ ./script/generate controller
102
+ Usage: ./script/generate controller ControllerName [options]
103
+
104
+ ...
105
+ ...
106
+
107
+ Example:
108
+ ./script/generate controller CreditCard open debit credit close
109
+
110
+ Credit card controller with URLs like /credit_card/debit.
111
+ Controller: app/controllers/credit_card_controller.rb
112
+ Views: app/views/credit_card/debit.html.erb [...]
113
+ Helper: app/helpers/credit_card_helper.rb
114
+ Test: test/functional/credit_card_controller_test.rb
115
+
116
+ Modules Example:
117
+ ./script/generate controller 'admin/credit_card' suspend late_fee
118
+
119
+ Credit card admin controller with URLs /admin/credit_card/suspend.
120
+ Controller: app/controllers/admin/credit_card_controller.rb
121
+ Views: app/views/admin/credit_card/debit.html.erb [...]
122
+ Helper: app/helpers/admin/credit_card_helper.rb
123
+ Test: test/functional/admin/credit_card_controller_test.rb
124
+ </shell>
125
+
126
+ Ah, the controller generator is expecting parameters in the form of +generate controller ControllerName action1 action2+. Let's make a +Greetings+ controller with an action of *hello*, which will say something nice to us.
127
+
128
+ <shell>
129
+ $ ./script/generate controller Greetings hello
130
+ exists app/controllers/
131
+ exists app/helpers/
132
+ create app/views/greetings
133
+ exists test/functional/
134
+ create app/controllers/greetings_controller.rb
135
+ create test/functional/greetings_controller_test.rb
136
+ create app/helpers/greetings_helper.rb
137
+ create app/views/greetings/hello.html.erb
138
+ </shell>
139
+
140
+ Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.
141
+
142
+ Let's check out the controller and modify it a little (in +app/controllers/greetings_controller.rb+):
143
+
144
+ <ruby>
145
+ class GreetingsController < ApplicationController
146
+ def hello
147
+ @message = "Hello, how are you today? I am exuberant!"
148
+ end
149
+
150
+ end
151
+ </ruby>
152
+
153
+ Then the view, to display our nice message (in +app/views/greetings/hello.html.erb+):
154
+
155
+ <html>
156
+ <h1>A Greeting for You!</h1>
157
+ <p><%= @message %></p>
158
+ </html>
159
+
160
+ Deal. Go check it out in your browser. Fire up your server. Remember? +./script/server+ at the root of your Rails application should do it.
161
+
162
+ <shell>
163
+ $ ./script/server
164
+ => Booting WEBrick...
165
+ </shell>
166
+
167
+ WARNING: Make sure that you do not have any "tilde backup" files in +app/views/(controller)+, or else WEBrick will _not_ show the expected output. This seems to be a *bug* in Rails 2.3.0.
168
+
169
+ The URL will be +http://localhost:3000/greetings/hello+. I'll wait for you to be suitably impressed.
170
+
171
+ INFO: With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the *index* action of that controller.
172
+
173
+ "What about data, though?", you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name?
174
+
175
+ <shell>
176
+ $ ./script/generate model
177
+ Usage: ./script/generate model ModelName [field:type, field:type]
178
+
179
+ ...
180
+
181
+ Examples:
182
+ ./script/generate model account
183
+
184
+ creates an Account model, test, fixture, and migration:
185
+ Model: app/models/account.rb
186
+ Test: test/unit/account_test.rb
187
+ Fixtures: test/fixtures/accounts.yml
188
+ Migration: db/migrate/XXX_add_accounts.rb
189
+
190
+ ./script/generate model post title:string body:text published:boolean
191
+
192
+ creates a Post model with a string title, text body, and published flag.
193
+ </shell>
194
+
195
+ But instead of generating a model directly (which we'll be doing later), let's set up a scaffold. A *scaffold* in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.
196
+
197
+ Let's set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
198
+
199
+ <shell>
200
+ $ ./script/generate scaffold HighScore game:string score:integer
201
+ exists app/models/
202
+ exists app/controllers/
203
+ exists app/helpers/
204
+ create app/views/high_scores
205
+ create app/views/layouts/
206
+ exists test/functional/
207
+ create test/unit/
208
+ create public/stylesheets/
209
+ create app/views/high_scores/index.html.erb
210
+ create app/views/high_scores/show.html.erb
211
+ create app/views/high_scores/new.html.erb
212
+ create app/views/high_scores/edit.html.erb
213
+ create app/views/layouts/high_scores.html.erb
214
+ create public/stylesheets/scaffold.css
215
+ create app/controllers/high_scores_controller.rb
216
+ create test/functional/high_scores_controller_test.rb
217
+ create app/helpers/high_scores_helper.rb
218
+ route map.resources :high_scores
219
+ dependency model
220
+ exists app/models/
221
+ exists test/unit/
222
+ create test/fixtures/
223
+ create app/models/high_score.rb
224
+ create test/unit/high_score_test.rb
225
+ create test/fixtures/high_scores.yml
226
+ exists db/migrate
227
+ create db/migrate/20081217071914_create_high_scores.rb
228
+ </shell>
229
+
230
+ Taking it from the top - the generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the +high_scores+ table and fields), takes care of the route for the *resource*, and new tests for everything.
231
+
232
+ The migration requires that we *migrate*, that is, run some Ruby code (living in that +20081217071914_create_high_scores.rb+) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the +rake db:migrate+ command. We'll talk more about Rake in-depth in a little while.
233
+
234
+ CAUTION: Hey. Install the sqlite3-ruby gem while you're at it. +gem install sqlite3-ruby+
235
+
236
+ <shell>
237
+ $ rake db:migrate
238
+ (in /home/commandsapp)
239
+ CreateHighScores: migrating
240
+ create_table(:high_scores)
241
+ -> 0.0070s
242
+ CreateHighScores: migrated (0.0077s)
243
+ </shell>
244
+
245
+ INFO: Let's talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We'll make one in a moment.
246
+
247
+ Let's see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores
248
+
249
+ We can create new high scores (55,160 on Space Invaders!)
250
+
251
+ h4. +console+
252
+
253
+ The +console+ command lets you interact with your Rails application from the command line. On the underside, +script/console+ uses IRB, so if you've ever used it, you'll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.
254
+
255
+ h4. +dbconsole+
256
+
257
+ +dbconsole+ figures out which database you're using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.
258
+
259
+ h4. +plugin+
260
+
261
+ The +plugin+ command simplifies plugin management; think a miniature version of the Gem utility. Let's walk through installing a plugin. You can call the sub-command *discover*, which sifts through repositories looking for plugins, or call *source* to add a specific repository of plugins, or you can specify the plugin location directly.
262
+
263
+ Let's say you're creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn't it be great if we could override the behavior of a model to never actually take its record out of the database, but *instead*, just set a field?
264
+
265
+ There is such a thing! The plugin we're installing is called "acts_as_paranoid", and it lets models implement a "deleted_at" column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out "deleted" things.
266
+
267
+ <shell>
268
+ $ ./script/plugin install http://svn.techno-weenie.net/projects/plugins/acts_as_paranoid
269
+ + ./CHANGELOG
270
+ + ./MIT-LICENSE
271
+ ...
272
+ ...
273
+ </shell>
274
+
275
+ h4. +runner+
276
+
277
+ <tt>runner</tt> runs Ruby code in the context of Rails non-interactively. For instance:
278
+
279
+ <shell>
280
+ $ ./script/runner "Model.long_running_method"
281
+ </shell>
282
+
283
+ h4. +destroy+
284
+
285
+ Think of +destroy+ as the opposite of +generate+. It'll figure out what generate did, and undo it. Believe you-me, the creation of this tutorial used this command many times!
286
+
287
+ <shell>
288
+ $ ./script/generate model Oops
289
+ exists app/models/
290
+ exists test/unit/
291
+ exists test/fixtures/
292
+ create app/models/oops.rb
293
+ create test/unit/oops_test.rb
294
+ create test/fixtures/oops.yml
295
+ exists db/migrate
296
+ create db/migrate/20081221040817_create_oops.rb
297
+ $ ./script/destroy model Oops
298
+ notempty db/migrate
299
+ notempty db
300
+ rm db/migrate/20081221040817_create_oops.rb
301
+ rm test/fixtures/oops.yml
302
+ rm test/unit/oops_test.rb
303
+ rm app/models/oops.rb
304
+ notempty test/fixtures
305
+ notempty test
306
+ notempty test/unit
307
+ notempty test
308
+ notempty app/models
309
+ notempty app
310
+ </shell>
311
+
312
+ h4. +about+
313
+
314
+ Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application's folder, the current Rails environment name, your app's database adapter, and schema version! +about+ is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.
315
+
316
+ <shell>
317
+ $ ./script/about
318
+ About your application's environment
319
+ Ruby version 1.8.6 (i486-linux)
320
+ RubyGems version 1.3.1
321
+ Rails version 2.2.0
322
+ Active Record version 2.2.0
323
+ Action Pack version 2.2.0
324
+ Active Resource version 2.2.0
325
+ Action Mailer version 2.2.0
326
+ Active Support version 2.2.0
327
+ Edge Rails revision unknown
328
+ Application root /home/commandsapp
329
+ Environment development
330
+ Database adapter sqlite3
331
+ Database schema version 20081217073400
332
+ </shell>
333
+
334
+ h3. The Rails Advanced Command Line
335
+
336
+ The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
337
+
338
+ h4. Rails with Databases and SCM
339
+
340
+ When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.
341
+
342
+ Let's see what a +--git+ option and a +--database=postgresql+ option will do for us:
343
+
344
+ <shell>
345
+ $ mkdir gitapp
346
+ $ cd gitapp
347
+ $ git init
348
+ Initialized empty Git repository in .git/
349
+ $ rails . --git --database=postgresql
350
+ exists
351
+ create app/controllers
352
+ create app/helpers
353
+ ...
354
+ ...
355
+ create tmp/cache
356
+ create tmp/pids
357
+ create Rakefile
358
+ add 'Rakefile'
359
+ create README
360
+ add 'README'
361
+ create app/controllers/application_controller_.rb
362
+ add 'app/controllers/application_controller_.rb'
363
+ create app/helpers/application_helper.rb
364
+ ...
365
+ create log/test.log
366
+ add 'log/test.log'
367
+ </shell>
368
+
369
+ We had to create the *gitapp* directory and initialize an empty git repository before Rails would add files it created to our repository. Let's see what it put in our database configuration:
370
+
371
+ <shell>
372
+ $ cat config/database.yml
373
+ # PostgreSQL. Versions 7.4 and 8.x are supported.
374
+ #
375
+ # Install the ruby-postgres driver:
376
+ # gem install ruby-postgres
377
+ # On Mac OS X:
378
+ # gem install ruby-postgres -- --include=/usr/local/pgsql
379
+ # On Windows:
380
+ # gem install ruby-postgres
381
+ # Choose the win32 build.
382
+ # Install PostgreSQL and put its /bin directory on your path.
383
+ development:
384
+ adapter: postgresql
385
+ encoding: unicode
386
+ database: gitapp_development
387
+ pool: 5
388
+ username: gitapp
389
+ password:
390
+ ...
391
+ ...
392
+ </shell>
393
+
394
+ It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database. The only catch with using the SCM options is that you have to make your application's directory first, then initialize your SCM, then you can run the +rails+ command to generate the basis of your app.
395
+
396
+ h4. +server+ with Different Backends
397
+
398
+ Many people have created a large number different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!).
399
+
400
+ NOTE: For more details on the Rack integration, see "Rails on Rack":rails_on_rack.html.
401
+
402
+ To use a different server, just install its gem, then use its name for the first parameter to +script/server+:
403
+
404
+ <shell>
405
+ $ sudo gem install mongrel
406
+ Building native extensions. This could take a while...
407
+ Building native extensions. This could take a while...
408
+ Successfully installed gem_plugin-0.2.3
409
+ Successfully installed fastthread-1.0.1
410
+ Successfully installed cgi_multipart_eof_fix-2.5.0
411
+ Successfully installed mongrel-1.1.5
412
+ ...
413
+ ...
414
+ Installing RDoc documentation for mongrel-1.1.5...
415
+ $ script/server mongrel
416
+ => Booting Mongrel (use 'script/server webrick' to force WEBrick)
417
+ => Rails 2.2.0 application starting on http://0.0.0.0:3000
418
+ ...
419
+ </shell>
420
+
421
+ h4. The Rails Generation: Generators
422
+
423
+ INFO: For a good rundown on generators, see "Understanding Generators":http://wiki.rubyonrails.org/rails/pages/UnderstandingGenerators. A lot of its material is presented here.
424
+
425
+ Generators are code that generates code. Let's experiment by building one. Our generator will generate a text file.
426
+
427
+ The Rails generator by default looks in these places for available generators, where Rails.root is the root of your Rails application, like /home/foobar/commandsapp:
428
+
429
+ * Rails.root/lib/generators
430
+ * Rails.root/vendor/generators
431
+ * Inside any plugin with a directory like "generators" or "rails_generators"
432
+ * ~/.rails/generators
433
+ * Inside any Gem you have installed with a name ending in "_generator"
434
+ * Inside *any* Gem installed with a "rails_generators" path, and a file ending in "_generator.rb"
435
+ * Finally, the builtin Rails generators (controller, model, mailer, etc.)
436
+
437
+ Let's try the fourth option (in our home directory), which will be easy to clean up later:
438
+
439
+ <shell>
440
+ $ mkdir -p ~/.rails/generators/tutorial_test/templates
441
+ $ touch ~/.rails/generators/tutorial_test/templates/tutorial.erb
442
+ $ touch ~/.rails/generators/tutorial_test/tutorial_test_generator.rb
443
+ </shell>
444
+
445
+ We'll fill +tutorial_test_generator.rb+ out with:
446
+
447
+ <ruby>
448
+ class TutorialTestGenerator < Rails::Generator::Base
449
+ def initialize(*runtime_args)
450
+ super(*runtime_args)
451
+ @tut_args = runtime_args
452
+ end
453
+
454
+ def manifest
455
+ record do |m|
456
+ m.directory "public"
457
+ m.template "tutorial.erb", File.join("public", "tutorial.txt"),
458
+ :assigns => { :args => @tut_args }
459
+ end
460
+ end
461
+ end
462
+ </ruby>
463
+
464
+ We take whatever args are supplied, save them to an instance variable, and literally copying from the Rails source, implement a +manifest+ method, which calls +record+ with a block, and we:
465
+
466
+ * Check there's a *public* directory. You bet there is.
467
+ * Run the ERb template called "tutorial.erb".
468
+ * Save it into "Rails.root/public/tutorial.txt".
469
+ * Pass in the arguments we saved through the +:assign+ parameter.
470
+
471
+ Next we'll build the template:
472
+
473
+ <shell>
474
+ $ cat ~/.rails/generators/tutorial_test/templates/tutorial.erb
475
+ I'm a template!
476
+
477
+ I got assigned some args:
478
+ <%= require 'pp'; PP.pp(args, "") %>
479
+ </shell>
480
+
481
+ Then we'll make sure it got included in the list of available generators:
482
+
483
+ <shell>
484
+ $ ./script/generate
485
+ ...
486
+ ...
487
+ Installed Generators
488
+ User: tutorial_test
489
+ </shell>
490
+
491
+ SWEET! Now let's generate some text, yeah!
492
+
493
+ <shell>
494
+ $ ./script/generate tutorial_test arg1 arg2 arg3
495
+ exists public
496
+ create public/tutorial.txt
497
+ </shell>
498
+
499
+ And the result:
500
+
501
+ <shell>
502
+ $ cat public/tutorial.txt
503
+ I'm a template!
504
+
505
+ I got assigned some args:
506
+ [["arg1", "arg2", "arg3"],
507
+ {:collision=>:ask,
508
+ :quiet=>false,
509
+ :generator=>"tutorial_test",
510
+ :command=>:create}]
511
+ </shell>
512
+
513
+ Tada!
514
+
515
+ h4. Rake is Ruby Make
516
+
517
+ Rake is a standalone Ruby utility that replaces the Unix utility 'make', and uses a 'Rakefile' and +.rake+ files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.
518
+
519
+ You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing +rake --tasks+. Each task has a description, and should help you find the thing you need.
520
+
521
+ <shell>
522
+ rake --tasks
523
+ (in /home/developer/commandsapp)
524
+ rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
525
+ rake db:charset # Retrieves the charset for the current environment's database
526
+ rake db:collation # Retrieves the collation for the current environment's database
527
+ rake db:create # Create the database defined in config/database.yml for the current RAILS_ENV
528
+ ...
529
+ ...
530
+ rake tmp:pids:clear # Clears all files in tmp/pids
531
+ rake tmp:sessions:clear # Clears all files in tmp/sessions
532
+ rake tmp:sockets:clear # Clears all files in tmp/sockets
533
+ </shell>
534
+
535
+ Let's take a look at some of these 80 or so rake tasks.
536
+
537
+ h5. +db:+ Database
538
+
539
+ The most common tasks of the +db:+ Rake namespace are +migrate+ and +create+, and it will pay off to try out all of the migration rake tasks (+up+, +down+, +redo+, +reset+). +rake db:version+ is useful when troubleshooting, telling you the current version of the database.
540
+
541
+ h5. +doc:+ Documentation
542
+
543
+ If you want to strip out or rebuild any of the Rails documentation (including this guide!), the +doc:+ namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
544
+
545
+ h5. +gems:+ Ruby gems
546
+
547
+ You can specify which gems your application uses, and +rake gems:install+ will install them for you. Look at your environment.rb to learn how with the *config.gem* directive.
548
+
549
+ NOTE: +gems:unpack+ will unpack, that is internalize your application's Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run +rake gems:install+, or finding and installing the gems your application uses.
550
+
551
+ h5. +notes:+ Code note enumeration
552
+
553
+ These tasks will search through your code for commented lines beginning with "FIXME", "OPTIMIZE", "TODO", or any custom annotation (like XXX) and show you them.
554
+
555
+ h5. +rails:+ Rails-specific tasks
556
+
557
+ In addition to the +gems:unpack+ task above, you can also unpack the Rails backend specific gems into vendor/rails by calling +rake rails:freeze:gems+, to unpack the version of Rails you are currently using, or +rake rails:freeze:edge+ to unpack the most recent (cutting, bleeding edge) version.
558
+
559
+ When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can "thaw" by running +rake rails:unfreeze+.
560
+
561
+ After upgrading Rails, it is useful to run +rails:update+, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous).
562
+
563
+ h5. +test:+ Rails tests
564
+
565
+ INFO: A good description of unit testing in Rails is given in "A Guide to Testing Rails Applications":testing.html
566
+
567
+ Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.
568
+
569
+ The +test:+ namespace helps in running the different tests you will (hopefully!) write.
570
+
571
+ h5. +time:+ Timezones
572
+
573
+ You can list all the timezones Rails knows about with +rake time:zones:all+, which is useful just in day-to-day life.
574
+
575
+ h5. +tmp:+ Temporary files
576
+
577
+ The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. The +tmp:+ namespace tasks will help you clear them if you need to if they've become overgrown, or create them in case of an +rm -rf *+ gone awry.
578
+
579
+ h5. Miscellaneous Tasks
580
+
581
+ +rake stats+ is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
582
+
583
+ +rake secret+ will give you a psuedo-random key to use for your session secret.
584
+
585
+ +rake routes+ will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you're trying to get familiar with.
586
+
587
+ h3. Changelog
588
+
589
+ "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213/tickets/29