rails 4.1.14.2 → 5.2.4.4
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/README.md +33 -19
- metadata +65 -313
- data/guides/CHANGELOG.md +0 -106
- data/guides/Rakefile +0 -77
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -53
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -710
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -53
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/code/getting_started/Gemfile +0 -40
- data/guides/code/getting_started/Gemfile.lock +0 -125
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -60
- data/guides/code/getting_started/public/422.html +0 -60
- data/guides/code/getting_started/public/500.html +0 -59
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -12
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -31
- data/guides/rails_guides/markdown.rb +0 -163
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -556
- data/guides/source/3_2_release_notes.md +0 -565
- data/guides/source/4_0_release_notes.md +0 -276
- data/guides/source/4_1_release_notes.md +0 -731
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -25
- data/guides/source/action_controller_overview.md +0 -1175
- data/guides/source/action_mailer_basics.md +0 -689
- data/guides/source/action_view_overview.md +0 -1602
- data/guides/source/active_model_basics.md +0 -200
- data/guides/source/active_record_basics.md +0 -373
- data/guides/source/active_record_callbacks.md +0 -410
- data/guides/source/active_record_querying.md +0 -1785
- data/guides/source/active_record_validations.md +0 -1169
- data/guides/source/active_support_core_extensions.md +0 -3817
- data/guides/source/active_support_instrumentation.md +0 -496
- data/guides/source/api_documentation_guidelines.md +0 -315
- data/guides/source/asset_pipeline.md +0 -1165
- data/guides/source/association_basics.md +0 -2229
- data/guides/source/caching_with_rails.md +0 -354
- data/guides/source/command_line.md +0 -603
- data/guides/source/configuring.md +0 -942
- data/guides/source/contributing_to_ruby_on_rails.md +0 -544
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -707
- data/guides/source/development_dependencies_install.md +0 -278
- data/guides/source/documents.yaml +0 -193
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1001
- data/guides/source/generators.md +0 -663
- data/guides/source/getting_started.md +0 -1946
- data/guides/source/i18n.md +0 -1043
- data/guides/source/index.html.erb +0 -27
- data/guides/source/initialization.md +0 -657
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -146
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -75
- data/guides/source/migrations.md +0 -1143
- data/guides/source/nested_model_forms.md +0 -225
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -248
- data/guides/source/rails_on_rack.md +0 -332
- data/guides/source/routing.md +0 -1115
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
- data/guides/source/security.md +0 -1018
- data/guides/source/testing.md +0 -1052
- data/guides/source/upgrading_ruby_on_rails.md +0 -928
- data/guides/source/working_with_javascript_in_rails.md +0 -405
- data/guides/w3c_validator.rb +0 -95
@@ -1,354 +0,0 @@
|
|
1
|
-
Caching with Rails: An overview
|
2
|
-
===============================
|
3
|
-
|
4
|
-
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.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* Page and action caching (moved to separate gems as of Rails 4).
|
9
|
-
* Fragment caching.
|
10
|
-
* Alternative cache stores.
|
11
|
-
* Conditional GET support.
|
12
|
-
|
13
|
-
--------------------------------------------------------------------------------
|
14
|
-
|
15
|
-
Basic Caching
|
16
|
-
-------------
|
17
|
-
|
18
|
-
This is an introduction to three types of caching techniques: page, action and
|
19
|
-
fragment caching. Rails provides by default fragment caching. In order to use
|
20
|
-
page and action caching, you will need to add `actionpack-page_caching` and
|
21
|
-
`actionpack-action_caching` to your Gemfile.
|
22
|
-
|
23
|
-
To start playing with caching 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.
|
24
|
-
|
25
|
-
```ruby
|
26
|
-
config.action_controller.perform_caching = true
|
27
|
-
```
|
28
|
-
|
29
|
-
### Page Caching
|
30
|
-
|
31
|
-
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.
|
32
|
-
|
33
|
-
INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method.
|
34
|
-
|
35
|
-
### Action Caching
|
36
|
-
|
37
|
-
Page Caching cannot be used for actions that have before filters - for example, pages that require authentication. This is where Action Caching comes in. Action Caching works like Page Caching except the incoming web request hits the Rails stack so that before filters can be run on it before the cache is served. This allows authentication and other restrictions to be run while still serving the result of the output from a cached copy.
|
38
|
-
|
39
|
-
INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching). See [DHH's key-based cache expiration overview](http://37signals.com/svn/posts/3113-how-key-based-cache-expiration-works) for the newly-preferred method.
|
40
|
-
|
41
|
-
### Fragment Caching
|
42
|
-
|
43
|
-
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.
|
44
|
-
|
45
|
-
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.
|
46
|
-
|
47
|
-
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:
|
48
|
-
|
49
|
-
```html+erb
|
50
|
-
<% Order.find_recent.each do |o| %>
|
51
|
-
<%= o.buyer.name %> bought <%= o.product.name %>
|
52
|
-
<% end %>
|
53
|
-
|
54
|
-
<% cache do %>
|
55
|
-
All available products:
|
56
|
-
<% Product.all.each do |p| %>
|
57
|
-
<%= link_to p.name, product_url(p) %>
|
58
|
-
<% end %>
|
59
|
-
<% end %>
|
60
|
-
```
|
61
|
-
|
62
|
-
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:
|
63
|
-
|
64
|
-
```html+erb
|
65
|
-
<% cache(action: 'recent', action_suffix: 'all_products') do %>
|
66
|
-
All available products:
|
67
|
-
```
|
68
|
-
|
69
|
-
and you can expire it using the `expire_fragment` method, like so:
|
70
|
-
|
71
|
-
```ruby
|
72
|
-
expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products')
|
73
|
-
```
|
74
|
-
|
75
|
-
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:
|
76
|
-
|
77
|
-
```erb
|
78
|
-
<% cache('all_available_products') do %>
|
79
|
-
All available products:
|
80
|
-
<% end %>
|
81
|
-
```
|
82
|
-
|
83
|
-
This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way:
|
84
|
-
|
85
|
-
```ruby
|
86
|
-
expire_fragment('all_available_products')
|
87
|
-
```
|
88
|
-
If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method:
|
89
|
-
|
90
|
-
```ruby
|
91
|
-
module ProductsHelper
|
92
|
-
def cache_key_for_products
|
93
|
-
count = Product.count
|
94
|
-
max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number)
|
95
|
-
"products/all-#{count}-#{max_updated_at}"
|
96
|
-
end
|
97
|
-
end
|
98
|
-
```
|
99
|
-
|
100
|
-
This method generates a cache key that depends on all products and can be used in the view:
|
101
|
-
|
102
|
-
```erb
|
103
|
-
<% cache(cache_key_for_products) do %>
|
104
|
-
All available products:
|
105
|
-
<% end %>
|
106
|
-
```
|
107
|
-
|
108
|
-
If you want to cache a fragment under certain condition you can use `cache_if` or `cache_unless`
|
109
|
-
|
110
|
-
```erb
|
111
|
-
<% cache_if (condition, cache_key_for_products) do %>
|
112
|
-
All available products:
|
113
|
-
<% end %>
|
114
|
-
```
|
115
|
-
|
116
|
-
You can also use an Active Record model as the cache key:
|
117
|
-
|
118
|
-
```erb
|
119
|
-
<% Product.all.each do |p| %>
|
120
|
-
<% cache(p) do %>
|
121
|
-
<%= link_to p.name, product_url(p) %>
|
122
|
-
<% end %>
|
123
|
-
<% end %>
|
124
|
-
```
|
125
|
-
|
126
|
-
Behind the scenes, a method called `cache_key` will be invoked on the model and it returns a string like `products/23-20130109142513`. The cache key includes the model name, the id and finally the updated_at timestamp. Thus it will automatically generate a new fragment when the product is updated because the key changes.
|
127
|
-
|
128
|
-
You can also combine the two schemes which is called "Russian Doll Caching":
|
129
|
-
|
130
|
-
```erb
|
131
|
-
<% cache(cache_key_for_products) do %>
|
132
|
-
All available products:
|
133
|
-
<% Product.all.each do |p| %>
|
134
|
-
<% cache(p) do %>
|
135
|
-
<%= link_to p.name, product_url(p) %>
|
136
|
-
<% end %>
|
137
|
-
<% end %>
|
138
|
-
<% end %>
|
139
|
-
```
|
140
|
-
|
141
|
-
It's called "Russian Doll Caching" because it nests multiple fragments. The advantage is that if a single product is updated, all the other inner fragments can be reused when regenerating the outer fragment.
|
142
|
-
|
143
|
-
### SQL Caching
|
144
|
-
|
145
|
-
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.
|
146
|
-
|
147
|
-
For example:
|
148
|
-
|
149
|
-
```ruby
|
150
|
-
class ProductsController < ApplicationController
|
151
|
-
|
152
|
-
def index
|
153
|
-
# Run a find query
|
154
|
-
@products = Product.all
|
155
|
-
|
156
|
-
...
|
157
|
-
|
158
|
-
# Run the same query again
|
159
|
-
@products = Product.all
|
160
|
-
end
|
161
|
-
|
162
|
-
end
|
163
|
-
```
|
164
|
-
|
165
|
-
Cache Stores
|
166
|
-
------------
|
167
|
-
|
168
|
-
Rails provides different stores for the cached data created by <b>action</b> and <b>fragment</b> caches.
|
169
|
-
|
170
|
-
TIP: Page caches are always stored on disk.
|
171
|
-
|
172
|
-
### Configuration
|
173
|
-
|
174
|
-
You can set up your application's default cache store by calling `config.cache_store=` in the Application definition inside your `config/application.rb` file or in an Application.configure block in an environment specific configuration file (i.e. `config/environments/*.rb`). The first argument will be the cache store to use and the rest of the argument will be passed as arguments to the cache store constructor.
|
175
|
-
|
176
|
-
```ruby
|
177
|
-
config.cache_store = :memory_store
|
178
|
-
```
|
179
|
-
|
180
|
-
NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block.
|
181
|
-
|
182
|
-
You can access the cache by calling `Rails.cache`.
|
183
|
-
|
184
|
-
### ActiveSupport::Cache::Store
|
185
|
-
|
186
|
-
This class provides the foundation for interacting with the cache in Rails. This is an abstract class and you cannot use it on its own. Rather you must use a concrete implementation of the class tied to a storage engine. Rails ships with several implementations documented below.
|
187
|
-
|
188
|
-
The main methods to call are `read`, `write`, `delete`, `exist?`, and `fetch`. The fetch method takes a block and will either return an existing value from the cache, or evaluate the block and write the result to the cache if no value exists.
|
189
|
-
|
190
|
-
There are some common options used by all cache implementations. These can be passed to the constructor or the various methods to interact with entries.
|
191
|
-
|
192
|
-
* `:namespace` - This option can be used to create a namespace within the cache store. It is especially useful if your application shares a cache with other applications.
|
193
|
-
|
194
|
-
* `:compress` - This option can be used to indicate that compression should be used in the cache. This can be useful for transferring large cache entries over a slow network.
|
195
|
-
|
196
|
-
* `:compress_threshold` - This options is used in conjunction with the `:compress` option to indicate a threshold under which cache entries should not be compressed. This defaults to 16 kilobytes.
|
197
|
-
|
198
|
-
* `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache.
|
199
|
-
|
200
|
-
* `:race_condition_ttl` - This option is used in conjunction with the `:expires_in` option. It will prevent race conditions when cache entries expire by preventing multiple processes from simultaneously regenerating the same entry (also known as the dog pile effect). This option sets the number of seconds that an expired entry can be reused while a new value is being regenerated. It's a good practice to set this value if you use the `:expires_in` option.
|
201
|
-
|
202
|
-
### ActiveSupport::Cache::MemoryStore
|
203
|
-
|
204
|
-
This cache store keeps entries in memory in the same Ruby process. The cache store has a bounded size specified by the `:size` options to the initializer (default is 32Mb). When the cache exceeds the allotted size, a cleanup will occur and the least recently used entries will be removed.
|
205
|
-
|
206
|
-
```ruby
|
207
|
-
config.cache_store = :memory_store, { size: 64.megabytes }
|
208
|
-
```
|
209
|
-
|
210
|
-
If you're running multiple Ruby on Rails server processes (which is the case if you're using mongrel_cluster or Phusion Passenger), then your Rails server process instances won't be able to share cache data with each other. This cache store is not appropriate for large application deployments, but can work well for small, low traffic sites with only a couple of server processes or for development and test environments.
|
211
|
-
|
212
|
-
### ActiveSupport::Cache::FileStore
|
213
|
-
|
214
|
-
This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
|
215
|
-
|
216
|
-
```ruby
|
217
|
-
config.cache_store = :file_store, "/path/to/cache/directory"
|
218
|
-
```
|
219
|
-
|
220
|
-
With this cache store, multiple server processes on the same host can share a cache. Servers processes running on different hosts could share a cache by using a shared file system, but that set up would not be ideal and is not recommended. The cache store is appropriate for low to medium traffic sites that are served off one or two hosts.
|
221
|
-
|
222
|
-
Note that the cache will grow until the disk is full unless you periodically clear out old entries.
|
223
|
-
|
224
|
-
This is the default cache store implementation.
|
225
|
-
|
226
|
-
### ActiveSupport::Cache::MemCacheStore
|
227
|
-
|
228
|
-
This cache store uses Danga's `memcached` server to provide a centralized cache for your application. Rails uses the bundled `dalli` gem by default. This is currently the most popular cache store for production websites. It can be used to provide a single, shared cache cluster with very high performance and redundancy.
|
229
|
-
|
230
|
-
When initializing the cache, you need to specify the addresses for all memcached servers in your cluster. If none is specified, it will assume memcached is running on the local host on the default port, but this is not an ideal set up for larger sites.
|
231
|
-
|
232
|
-
The `write` and `fetch` methods on this cache accept two additional options that take advantage of features specific to memcached. You can specify `:raw` to send a value directly to the server with no serialization. The value must be a string or number. You can use memcached direct operation like `increment` and `decrement` only on raw values. You can also specify `:unless_exist` if you don't want memcached to overwrite an existing entry.
|
233
|
-
|
234
|
-
```ruby
|
235
|
-
config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com"
|
236
|
-
```
|
237
|
-
|
238
|
-
### ActiveSupport::Cache::EhcacheStore
|
239
|
-
|
240
|
-
If you are using JRuby you can use Terracotta's Ehcache as the cache store for your application. Ehcache is an open source Java cache that also offers an enterprise version with increased scalability, management, and commercial support. You must first install the jruby-ehcache-rails3 gem (version 1.1.0 or later) to use this cache store.
|
241
|
-
|
242
|
-
```ruby
|
243
|
-
config.cache_store = :ehcache_store
|
244
|
-
```
|
245
|
-
|
246
|
-
When initializing the cache, you may use the `:ehcache_config` option to specify the Ehcache config file to use (where the default is "ehcache.xml" in your Rails config directory), and the :cache_name option to provide a custom name for your cache (the default is rails_cache).
|
247
|
-
|
248
|
-
In addition to the standard `:expires_in` option, the `write` method on this cache can also accept the additional `:unless_exist` option, which will cause the cache store to use Ehcache's `putIfAbsent` method instead of `put`, and therefore will not overwrite an existing entry. Additionally, the `write` method supports all of the properties exposed by the [Ehcache Element class](http://ehcache.org/apidocs/net/sf/ehcache/Element.html) , including:
|
249
|
-
|
250
|
-
| Property | Argument Type | Description |
|
251
|
-
| --------------------------- | ------------------- | ----------------------------------------------------------- |
|
252
|
-
| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. |
|
253
|
-
| eternal | boolean | Sets whether the element is eternal. |
|
254
|
-
| timeToIdle, tti | int | Sets time to idle |
|
255
|
-
| timeToLive, ttl, expires_in | int | Sets time to Live |
|
256
|
-
| version | long | Sets the version attribute of the ElementAttributes object. |
|
257
|
-
|
258
|
-
These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples:
|
259
|
-
|
260
|
-
```ruby
|
261
|
-
Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds)
|
262
|
-
caches_action :index, expires_in: 60.seconds, unless_exist: true
|
263
|
-
```
|
264
|
-
|
265
|
-
For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) .
|
266
|
-
For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html)
|
267
|
-
|
268
|
-
### ActiveSupport::Cache::NullStore
|
269
|
-
|
270
|
-
This cache store implementation is meant to be used only in development or test environments and it never stores anything. This can be very useful in development when you have code that interacts directly with `Rails.cache`, but caching may interfere with being able to see the results of code changes. With this cache store, all `fetch` and `read` operations will result in a miss.
|
271
|
-
|
272
|
-
```ruby
|
273
|
-
config.cache_store = :null_store
|
274
|
-
```
|
275
|
-
|
276
|
-
### Custom Cache Stores
|
277
|
-
|
278
|
-
You can create your own custom cache store by simply extending `ActiveSupport::Cache::Store` and implementing the appropriate methods. In this way, you can swap in any number of caching technologies into your Rails application.
|
279
|
-
|
280
|
-
To use a custom cache store, simple set the cache store to a new instance of the class.
|
281
|
-
|
282
|
-
```ruby
|
283
|
-
config.cache_store = MyCacheStore.new
|
284
|
-
```
|
285
|
-
|
286
|
-
### Cache Keys
|
287
|
-
|
288
|
-
The keys used in a cache can be any object that responds to either `:cache_key` or to `:to_param`. You can implement the `:cache_key` method on your classes if you need to generate custom keys. Active Record will generate keys based on the class name and record id.
|
289
|
-
|
290
|
-
You can use Hashes and Arrays of values as cache keys.
|
291
|
-
|
292
|
-
```ruby
|
293
|
-
# This is a legal cache key
|
294
|
-
Rails.cache.read(site: "mysite", owners: [owner_1, owner_2])
|
295
|
-
```
|
296
|
-
|
297
|
-
The keys you use on `Rails.cache` will not be the same as those actually used with the storage engine. They may be modified with a namespace or altered to fit technology backend constraints. This means, for instance, that you can't save values with `Rails.cache` and then try to pull them out with the `memcache-client` gem. However, you also don't need to worry about exceeding the memcached size limit or violating syntax rules.
|
298
|
-
|
299
|
-
Conditional GET support
|
300
|
-
-----------------------
|
301
|
-
|
302
|
-
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.
|
303
|
-
|
304
|
-
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.
|
305
|
-
|
306
|
-
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:
|
307
|
-
|
308
|
-
```ruby
|
309
|
-
class ProductsController < ApplicationController
|
310
|
-
|
311
|
-
def show
|
312
|
-
@product = Product.find(params[:id])
|
313
|
-
|
314
|
-
# If the request is stale according to the given timestamp and etag value
|
315
|
-
# (i.e. it needs to be processed again) then execute this block
|
316
|
-
if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key)
|
317
|
-
respond_to do |wants|
|
318
|
-
# ... normal response processing
|
319
|
-
end
|
320
|
-
end
|
321
|
-
|
322
|
-
# If the request is fresh (i.e. it's not modified) then you don't need to do
|
323
|
-
# anything. The default render checks for this using the parameters
|
324
|
-
# used in the previous call to stale? and will automatically send a
|
325
|
-
# :not_modified. So that's it, you're done.
|
326
|
-
end
|
327
|
-
end
|
328
|
-
```
|
329
|
-
|
330
|
-
Instead of an options hash, you can also simply pass in a model, Rails will use the `updated_at` and `cache_key` methods for setting `last_modified` and `etag`:
|
331
|
-
|
332
|
-
```ruby
|
333
|
-
class ProductsController < ApplicationController
|
334
|
-
def show
|
335
|
-
@product = Product.find(params[:id])
|
336
|
-
respond_with(@product) if stale?(@product)
|
337
|
-
end
|
338
|
-
end
|
339
|
-
```
|
340
|
-
|
341
|
-
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:
|
342
|
-
|
343
|
-
```ruby
|
344
|
-
class ProductsController < ApplicationController
|
345
|
-
|
346
|
-
# This will automatically send back a :not_modified if the request is fresh,
|
347
|
-
# and will render the default template (product.*) if it's stale.
|
348
|
-
|
349
|
-
def show
|
350
|
-
@product = Product.find(params[:id])
|
351
|
-
fresh_when last_modified: @product.published_at.utc, etag: @product
|
352
|
-
end
|
353
|
-
end
|
354
|
-
```
|
@@ -1,603 +0,0 @@
|
|
1
|
-
The Rails Command Line
|
2
|
-
======================
|
3
|
-
|
4
|
-
After reading this guide, you will know:
|
5
|
-
|
6
|
-
* How to create a Rails application.
|
7
|
-
* How to generate models, controllers, database migrations, and unit tests.
|
8
|
-
* How to start a development server.
|
9
|
-
* How to experiment with objects through an interactive shell.
|
10
|
-
* How to profile and benchmark your new creation.
|
11
|
-
|
12
|
-
--------------------------------------------------------------------------------
|
13
|
-
|
14
|
-
NOTE: This tutorial assumes you have basic Rails knowledge from reading the [Getting Started with Rails Guide](getting_started.html).
|
15
|
-
|
16
|
-
Command Line Basics
|
17
|
-
-------------------
|
18
|
-
|
19
|
-
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:
|
20
|
-
|
21
|
-
* `rails console`
|
22
|
-
* `rails server`
|
23
|
-
* `rake`
|
24
|
-
* `rails generate`
|
25
|
-
* `rails dbconsole`
|
26
|
-
* `rails new app_name`
|
27
|
-
|
28
|
-
All commands can run with ```-h or --help``` to list more information.
|
29
|
-
|
30
|
-
Let's create a simple Rails application to step through each of these commands in context.
|
31
|
-
|
32
|
-
### `rails new`
|
33
|
-
|
34
|
-
The first thing we'll want to do is create a new Rails application by running the `rails new` command after installing Rails.
|
35
|
-
|
36
|
-
INFO: You can install the rails gem by typing `gem install rails`, if you don't have it already.
|
37
|
-
|
38
|
-
```bash
|
39
|
-
$ rails new commandsapp
|
40
|
-
create
|
41
|
-
create README.rdoc
|
42
|
-
create Rakefile
|
43
|
-
create config.ru
|
44
|
-
create .gitignore
|
45
|
-
create Gemfile
|
46
|
-
create app
|
47
|
-
...
|
48
|
-
create tmp/cache
|
49
|
-
...
|
50
|
-
run bundle install
|
51
|
-
```
|
52
|
-
|
53
|
-
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.
|
54
|
-
|
55
|
-
### `rails server`
|
56
|
-
|
57
|
-
The `rails server` command launches a small web server named WEBrick which comes bundled with Ruby. You'll use this any time you want to access your application through a web browser.
|
58
|
-
|
59
|
-
With no further work, `rails server` will run our new shiny Rails app:
|
60
|
-
|
61
|
-
```bash
|
62
|
-
$ cd commandsapp
|
63
|
-
$ bin/rails server
|
64
|
-
=> Booting WEBrick
|
65
|
-
=> Rails 4.1.4 application starting in development on http://0.0.0.0:3000
|
66
|
-
=> Call with -d to detach
|
67
|
-
=> Ctrl-C to shutdown server
|
68
|
-
[2013-08-07 02:00:01] INFO WEBrick 1.3.1
|
69
|
-
[2013-08-07 02:00:01] INFO ruby 2.0.0 (2013-06-27) [x86_64-darwin11.2.0]
|
70
|
-
[2013-08-07 02:00:01] INFO WEBrick::HTTPServer#start: pid=69680 port=3000
|
71
|
-
```
|
72
|
-
|
73
|
-
With just three commands we whipped up a Rails server listening on port 3000. Go to your browser and open [http://localhost:3000](http://localhost:3000), you will see a basic Rails app running.
|
74
|
-
|
75
|
-
INFO: You can also use the alias "s" to start the server: `rails s`.
|
76
|
-
|
77
|
-
The server can be run on a different port using the `-p` option. The default development environment can be changed using `-e`.
|
78
|
-
|
79
|
-
```bash
|
80
|
-
$ bin/rails server -e production -p 4000
|
81
|
-
```
|
82
|
-
|
83
|
-
The `-b` option binds Rails to the specified IP, by default it is 0.0.0.0. You can run a server as a daemon by passing a `-d` option.
|
84
|
-
|
85
|
-
### `rails generate`
|
86
|
-
|
87
|
-
The `rails generate` command uses templates to create a whole lot of things. Running `rails generate` by itself gives a list of available generators:
|
88
|
-
|
89
|
-
INFO: You can also use the alias "g" to invoke the generator command: `rails g`.
|
90
|
-
|
91
|
-
```bash
|
92
|
-
$ bin/rails generate
|
93
|
-
Usage: rails generate GENERATOR [args] [options]
|
94
|
-
|
95
|
-
...
|
96
|
-
...
|
97
|
-
|
98
|
-
Please choose a generator below.
|
99
|
-
|
100
|
-
Rails:
|
101
|
-
assets
|
102
|
-
controller
|
103
|
-
generator
|
104
|
-
...
|
105
|
-
...
|
106
|
-
```
|
107
|
-
|
108
|
-
NOTE: You can install more generators through generator gems, portions of plugins you'll undoubtedly install, and you can even create your own!
|
109
|
-
|
110
|
-
Using generators will save you a large amount of time by writing **boilerplate code**, code that is necessary for the app to work.
|
111
|
-
|
112
|
-
Let's make our own controller with the controller generator. But what command should we use? Let's ask the generator:
|
113
|
-
|
114
|
-
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 `rails server --help`.
|
115
|
-
|
116
|
-
```bash
|
117
|
-
$ bin/rails generate controller
|
118
|
-
Usage: rails generate controller NAME [action action] [options]
|
119
|
-
|
120
|
-
...
|
121
|
-
...
|
122
|
-
|
123
|
-
Description:
|
124
|
-
...
|
125
|
-
|
126
|
-
To create a controller within a module, specify the controller name as a
|
127
|
-
path like 'parent_module/controller_name'.
|
128
|
-
|
129
|
-
...
|
130
|
-
|
131
|
-
Example:
|
132
|
-
`rails generate controller CreditCard open debit credit close`
|
133
|
-
|
134
|
-
Credit card controller with URLs like /credit_card/debit.
|
135
|
-
Controller: app/controllers/credit_card_controller.rb
|
136
|
-
Test: test/controllers/credit_card_controller_test.rb
|
137
|
-
Views: app/views/credit_card/debit.html.erb [...]
|
138
|
-
Helper: app/helpers/credit_card_helper.rb
|
139
|
-
```
|
140
|
-
|
141
|
-
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.
|
142
|
-
|
143
|
-
```bash
|
144
|
-
$ bin/rails generate controller Greetings hello
|
145
|
-
create app/controllers/greetings_controller.rb
|
146
|
-
route get "greetings/hello"
|
147
|
-
invoke erb
|
148
|
-
create app/views/greetings
|
149
|
-
create app/views/greetings/hello.html.erb
|
150
|
-
invoke test_unit
|
151
|
-
create test/controllers/greetings_controller_test.rb
|
152
|
-
invoke helper
|
153
|
-
create app/helpers/greetings_helper.rb
|
154
|
-
invoke test_unit
|
155
|
-
create test/helpers/greetings_helper_test.rb
|
156
|
-
invoke assets
|
157
|
-
invoke coffee
|
158
|
-
create app/assets/javascripts/greetings.js.coffee
|
159
|
-
invoke scss
|
160
|
-
create app/assets/stylesheets/greetings.css.scss
|
161
|
-
```
|
162
|
-
|
163
|
-
What all did this generate? It made sure a bunch of directories were in our application, and created a controller file, a view file, a functional test file, a helper for the view, a JavaScript file and a stylesheet file.
|
164
|
-
|
165
|
-
Check out the controller and modify it a little (in `app/controllers/greetings_controller.rb`):
|
166
|
-
|
167
|
-
```ruby
|
168
|
-
class GreetingsController < ApplicationController
|
169
|
-
def hello
|
170
|
-
@message = "Hello, how are you today?"
|
171
|
-
end
|
172
|
-
end
|
173
|
-
```
|
174
|
-
|
175
|
-
Then the view, to display our message (in `app/views/greetings/hello.html.erb`):
|
176
|
-
|
177
|
-
```erb
|
178
|
-
<h1>A Greeting for You!</h1>
|
179
|
-
<p><%= @message %></p>
|
180
|
-
```
|
181
|
-
|
182
|
-
Fire up your server using `rails server`.
|
183
|
-
|
184
|
-
```bash
|
185
|
-
$ bin/rails server
|
186
|
-
=> Booting WEBrick...
|
187
|
-
```
|
188
|
-
|
189
|
-
The URL will be [http://localhost:3000/greetings/hello](http://localhost:3000/greetings/hello).
|
190
|
-
|
191
|
-
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.
|
192
|
-
|
193
|
-
Rails comes with a generator for data models too.
|
194
|
-
|
195
|
-
```bash
|
196
|
-
$ bin/rails generate model
|
197
|
-
Usage:
|
198
|
-
rails generate model NAME [field[:type][:index] field[:type][:index]] [options]
|
199
|
-
|
200
|
-
...
|
201
|
-
|
202
|
-
Active Record options:
|
203
|
-
[--migration] # Indicates when to generate migration
|
204
|
-
# Default: true
|
205
|
-
|
206
|
-
...
|
207
|
-
|
208
|
-
Description:
|
209
|
-
Create rails files for model generator.
|
210
|
-
```
|
211
|
-
|
212
|
-
NOTE: For a list of available field types, refer to the [API documentation](http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/TableDefinition.html#method-i-column) for the column method for the `TableDefinition` class.
|
213
|
-
|
214
|
-
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.
|
215
|
-
|
216
|
-
We will set up a simple resource called "HighScore" that will keep track of our highest score on video games we play.
|
217
|
-
|
218
|
-
```bash
|
219
|
-
$ bin/rails generate scaffold HighScore game:string score:integer
|
220
|
-
invoke active_record
|
221
|
-
create db/migrate/20130717151933_create_high_scores.rb
|
222
|
-
create app/models/high_score.rb
|
223
|
-
invoke test_unit
|
224
|
-
create test/models/high_score_test.rb
|
225
|
-
create test/fixtures/high_scores.yml
|
226
|
-
invoke resource_route
|
227
|
-
route resources :high_scores
|
228
|
-
invoke scaffold_controller
|
229
|
-
create app/controllers/high_scores_controller.rb
|
230
|
-
invoke erb
|
231
|
-
create app/views/high_scores
|
232
|
-
create app/views/high_scores/index.html.erb
|
233
|
-
create app/views/high_scores/edit.html.erb
|
234
|
-
create app/views/high_scores/show.html.erb
|
235
|
-
create app/views/high_scores/new.html.erb
|
236
|
-
create app/views/high_scores/_form.html.erb
|
237
|
-
invoke test_unit
|
238
|
-
create test/controllers/high_scores_controller_test.rb
|
239
|
-
invoke helper
|
240
|
-
create app/helpers/high_scores_helper.rb
|
241
|
-
invoke test_unit
|
242
|
-
create test/helpers/high_scores_helper_test.rb
|
243
|
-
invoke jbuilder
|
244
|
-
create app/views/high_scores/index.json.jbuilder
|
245
|
-
create app/views/high_scores/show.json.jbuilder
|
246
|
-
invoke assets
|
247
|
-
invoke coffee
|
248
|
-
create app/assets/javascripts/high_scores.js.coffee
|
249
|
-
invoke scss
|
250
|
-
create app/assets/stylesheets/high_scores.css.scss
|
251
|
-
invoke scss
|
252
|
-
identical app/assets/stylesheets/scaffolds.css.scss
|
253
|
-
```
|
254
|
-
|
255
|
-
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.
|
256
|
-
|
257
|
-
The migration requires that we **migrate**, that is, run some Ruby code (living in that `20130717151933_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.
|
258
|
-
|
259
|
-
```bash
|
260
|
-
$ bin/rake db:migrate
|
261
|
-
== CreateHighScores: migrating ===============================================
|
262
|
-
-- create_table(:high_scores)
|
263
|
-
-> 0.0017s
|
264
|
-
== CreateHighScores: migrated (0.0019s) ======================================
|
265
|
-
```
|
266
|
-
|
267
|
-
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.
|
268
|
-
|
269
|
-
Let's see the interface Rails created for us.
|
270
|
-
|
271
|
-
```bash
|
272
|
-
$ bin/rails server
|
273
|
-
```
|
274
|
-
|
275
|
-
Go to your browser and open [http://localhost:3000/high_scores](http://localhost:3000/high_scores), now we can create new high scores (55,160 on Space Invaders!)
|
276
|
-
|
277
|
-
### `rails console`
|
278
|
-
|
279
|
-
The `console` command lets you interact with your Rails application from the command line. On the underside, `rails 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.
|
280
|
-
|
281
|
-
INFO: You can also use the alias "c" to invoke the console: `rails c`.
|
282
|
-
|
283
|
-
You can specify the environment in which the `console` command should operate.
|
284
|
-
|
285
|
-
```bash
|
286
|
-
$ bin/rails console staging
|
287
|
-
```
|
288
|
-
|
289
|
-
If you wish to test out some code without changing any data, you can do that by invoking `rails console --sandbox`.
|
290
|
-
|
291
|
-
```bash
|
292
|
-
$ bin/rails console --sandbox
|
293
|
-
Loading development environment in sandbox (Rails 4.1.4)
|
294
|
-
Any modifications you make will be rolled back on exit
|
295
|
-
irb(main):001:0>
|
296
|
-
```
|
297
|
-
|
298
|
-
### `rails dbconsole`
|
299
|
-
|
300
|
-
`rails 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.
|
301
|
-
|
302
|
-
INFO: You can also use the alias "db" to invoke the dbconsole: `rails db`.
|
303
|
-
|
304
|
-
### `rails runner`
|
305
|
-
|
306
|
-
`runner` runs Ruby code in the context of Rails non-interactively. For instance:
|
307
|
-
|
308
|
-
```bash
|
309
|
-
$ bin/rails runner "Model.long_running_method"
|
310
|
-
```
|
311
|
-
|
312
|
-
INFO: You can also use the alias "r" to invoke the runner: `rails r`.
|
313
|
-
|
314
|
-
You can specify the environment in which the `runner` command should operate using the `-e` switch.
|
315
|
-
|
316
|
-
```bash
|
317
|
-
$ bin/rails runner -e staging "Model.long_running_method"
|
318
|
-
```
|
319
|
-
|
320
|
-
### `rails destroy`
|
321
|
-
|
322
|
-
Think of `destroy` as the opposite of `generate`. It'll figure out what generate did, and undo it.
|
323
|
-
|
324
|
-
INFO: You can also use the alias "d" to invoke the destroy command: `rails d`.
|
325
|
-
|
326
|
-
```bash
|
327
|
-
$ bin/rails generate model Oops
|
328
|
-
invoke active_record
|
329
|
-
create db/migrate/20120528062523_create_oops.rb
|
330
|
-
create app/models/oops.rb
|
331
|
-
invoke test_unit
|
332
|
-
create test/models/oops_test.rb
|
333
|
-
create test/fixtures/oops.yml
|
334
|
-
```
|
335
|
-
```bash
|
336
|
-
$ bin/rails destroy model Oops
|
337
|
-
invoke active_record
|
338
|
-
remove db/migrate/20120528062523_create_oops.rb
|
339
|
-
remove app/models/oops.rb
|
340
|
-
invoke test_unit
|
341
|
-
remove test/models/oops_test.rb
|
342
|
-
remove test/fixtures/oops.yml
|
343
|
-
```
|
344
|
-
|
345
|
-
Rake
|
346
|
-
----
|
347
|
-
|
348
|
-
Rake is Ruby Make, 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.
|
349
|
-
|
350
|
-
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.
|
351
|
-
|
352
|
-
To get the full backtrace for running rake task you can pass the option
|
353
|
-
```--trace``` to command line, for example ```rake db:create --trace```.
|
354
|
-
|
355
|
-
```bash
|
356
|
-
$ bin/rake --tasks
|
357
|
-
rake about # List versions of all Rails frameworks and the environment
|
358
|
-
rake assets:clean # Remove compiled assets
|
359
|
-
rake assets:precompile # Compile all the assets named in config.assets.precompile
|
360
|
-
rake db:create # Create the database from config/database.yml for the current Rails.env
|
361
|
-
...
|
362
|
-
rake log:clear # Truncates all *.log files in log/ to zero bytes (specify which logs with LOGS=test,development)
|
363
|
-
rake middleware # Prints out your Rack middleware stack
|
364
|
-
...
|
365
|
-
rake tmp:clear # Clear session, cache, and socket files from tmp/ (narrow w/ tmp:sessions:clear, tmp:cache:clear, tmp:sockets:clear)
|
366
|
-
rake tmp:create # Creates tmp directories for sessions, cache, sockets, and pids
|
367
|
-
```
|
368
|
-
INFO: You can also use ```rake -T``` to get the list of tasks.
|
369
|
-
|
370
|
-
### `about`
|
371
|
-
|
372
|
-
`rake about` gives information about 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. It 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.
|
373
|
-
|
374
|
-
```bash
|
375
|
-
$ bin/rake about
|
376
|
-
About your application's environment
|
377
|
-
Ruby version 1.9.3 (x86_64-linux)
|
378
|
-
RubyGems version 1.3.6
|
379
|
-
Rack version 1.3
|
380
|
-
Rails version 4.1.4
|
381
|
-
JavaScript Runtime Node.js (V8)
|
382
|
-
Active Record version 4.1.4
|
383
|
-
Action Pack version 4.1.4
|
384
|
-
Action View version 4.1.4
|
385
|
-
Action Mailer version 4.1.4
|
386
|
-
Active Support version 4.1.4
|
387
|
-
Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag
|
388
|
-
Application root /home/foobar/commandsapp
|
389
|
-
Environment development
|
390
|
-
Database adapter sqlite3
|
391
|
-
Database schema version 20110805173523
|
392
|
-
```
|
393
|
-
|
394
|
-
### `assets`
|
395
|
-
|
396
|
-
You can precompile the assets in `app/assets` using `rake assets:precompile` and remove those compiled assets using `rake assets:clean`.
|
397
|
-
|
398
|
-
### `db`
|
399
|
-
|
400
|
-
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.
|
401
|
-
|
402
|
-
More information about migrations can be found in the [Migrations](migrations.html) guide.
|
403
|
-
|
404
|
-
### `doc`
|
405
|
-
|
406
|
-
The `doc:` namespace has the tools to generate documentation for your app, API documentation, guides. Documentation can also be stripped which is mainly useful for slimming your codebase, like if you're writing a Rails application for an embedded platform.
|
407
|
-
|
408
|
-
* `rake doc:app` generates documentation for your application in `doc/app`.
|
409
|
-
* `rake doc:guides` generates Rails guides in `doc/guides`.
|
410
|
-
* `rake doc:rails` generates API documentation for Rails in `doc/api`.
|
411
|
-
|
412
|
-
### `notes`
|
413
|
-
|
414
|
-
`rake notes` will search through your code for comments beginning with FIXME, OPTIMIZE or TODO. The search is done in files with extension `.builder`, `.rb`, `.erb`, `.haml` and `.slim` for both default and custom annotations.
|
415
|
-
|
416
|
-
```bash
|
417
|
-
$ bin/rake notes
|
418
|
-
(in /home/foobar/commandsapp)
|
419
|
-
app/controllers/admin/users_controller.rb:
|
420
|
-
* [ 20] [TODO] any other way to do this?
|
421
|
-
* [132] [FIXME] high priority for next deploy
|
422
|
-
|
423
|
-
app/models/school.rb:
|
424
|
-
* [ 13] [OPTIMIZE] refactor this code to make it faster
|
425
|
-
* [ 17] [FIXME]
|
426
|
-
```
|
427
|
-
|
428
|
-
If you are looking for a specific annotation, say FIXME, you can use `rake notes:fixme`. Note that you have to lower case the annotation's name.
|
429
|
-
|
430
|
-
```bash
|
431
|
-
$ bin/rake notes:fixme
|
432
|
-
(in /home/foobar/commandsapp)
|
433
|
-
app/controllers/admin/users_controller.rb:
|
434
|
-
* [132] high priority for next deploy
|
435
|
-
|
436
|
-
app/models/school.rb:
|
437
|
-
* [ 17]
|
438
|
-
```
|
439
|
-
|
440
|
-
You can also use custom annotations in your code and list them using `rake notes:custom` by specifying the annotation using an environment variable `ANNOTATION`.
|
441
|
-
|
442
|
-
```bash
|
443
|
-
$ bin/rake notes:custom ANNOTATION=BUG
|
444
|
-
(in /home/foobar/commandsapp)
|
445
|
-
app/models/post.rb:
|
446
|
-
* [ 23] Have to fix this one before pushing!
|
447
|
-
```
|
448
|
-
|
449
|
-
NOTE. When using specific annotations and custom annotations, the annotation name (FIXME, BUG etc) is not displayed in the output lines.
|
450
|
-
|
451
|
-
By default, `rake notes` will look in the `app`, `config`, `lib`, `bin` and `test` directories. If you would like to search other directories, you can provide them as a comma separated list in an environment variable `SOURCE_ANNOTATION_DIRECTORIES`.
|
452
|
-
|
453
|
-
```bash
|
454
|
-
$ export SOURCE_ANNOTATION_DIRECTORIES='spec,vendor'
|
455
|
-
$ bin/rake notes
|
456
|
-
(in /home/foobar/commandsapp)
|
457
|
-
app/models/user.rb:
|
458
|
-
* [ 35] [FIXME] User should have a subscription at this point
|
459
|
-
spec/models/user_spec.rb:
|
460
|
-
* [122] [TODO] Verify the user that has a subscription works
|
461
|
-
```
|
462
|
-
|
463
|
-
### `routes`
|
464
|
-
|
465
|
-
`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.
|
466
|
-
|
467
|
-
### `test`
|
468
|
-
|
469
|
-
INFO: A good description of unit testing in Rails is given in [A Guide to Testing Rails Applications](testing.html)
|
470
|
-
|
471
|
-
Rails comes with a test suite called Minitest. Rails owes its stability to the use of tests. The tasks available in the `test:` namespace helps in running the different tests you will hopefully write.
|
472
|
-
|
473
|
-
### `tmp`
|
474
|
-
|
475
|
-
The `Rails.root/tmp` directory is, like 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.
|
476
|
-
|
477
|
-
The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory:
|
478
|
-
|
479
|
-
* `rake tmp:cache:clear` clears `tmp/cache`.
|
480
|
-
* `rake tmp:sessions:clear` clears `tmp/sessions`.
|
481
|
-
* `rake tmp:sockets:clear` clears `tmp/sockets`.
|
482
|
-
* `rake tmp:clear` clears all the three: cache, sessions and sockets.
|
483
|
-
* `rake tmp:create` creates tmp directories for sessions, cache, sockets, and pids.
|
484
|
-
|
485
|
-
### Miscellaneous
|
486
|
-
|
487
|
-
* `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.
|
488
|
-
* `rake secret` will give you a pseudo-random key to use for your session secret.
|
489
|
-
* `rake time:zones:all` lists all the timezones Rails knows about.
|
490
|
-
|
491
|
-
### Custom Rake Tasks
|
492
|
-
|
493
|
-
Custom rake tasks have a `.rake` extension and are placed in
|
494
|
-
`Rails.root/lib/tasks`. You can create these custom rake tasks with the
|
495
|
-
`bin/rails generate task` command.
|
496
|
-
|
497
|
-
```ruby
|
498
|
-
desc "I am short, but comprehensive description for my cool task"
|
499
|
-
task task_name: [:prerequisite_task, :another_task_we_depend_on] do
|
500
|
-
# All your magic here
|
501
|
-
# Any valid Ruby code is allowed
|
502
|
-
end
|
503
|
-
```
|
504
|
-
|
505
|
-
To pass arguments to your custom rake task:
|
506
|
-
|
507
|
-
```ruby
|
508
|
-
task :task_name, [:arg_1] => [:pre_1, :pre_2] do |t, args|
|
509
|
-
# You can use args from here
|
510
|
-
end
|
511
|
-
```
|
512
|
-
|
513
|
-
You can group tasks by placing them in namespaces:
|
514
|
-
|
515
|
-
```ruby
|
516
|
-
namespace :db do
|
517
|
-
desc "This task does nothing"
|
518
|
-
task :nothing do
|
519
|
-
# Seriously, nothing
|
520
|
-
end
|
521
|
-
end
|
522
|
-
```
|
523
|
-
|
524
|
-
Invocation of the tasks will look like:
|
525
|
-
|
526
|
-
```bash
|
527
|
-
$ bin/rake task_name
|
528
|
-
$ bin/rake "task_name[value 1]" # entire argument string should be quoted
|
529
|
-
$ bin/rake db:nothing
|
530
|
-
```
|
531
|
-
|
532
|
-
NOTE: If your need to interact with your application models, perform database queries and so on, your task should depend on the `environment` task, which will load your application code.
|
533
|
-
|
534
|
-
The Rails Advanced Command Line
|
535
|
-
-------------------------------
|
536
|
-
|
537
|
-
More advanced use of the command line is focused around finding useful (even surprising at times) options in the utilities, and fitting those to your needs and specific work flow. Listed here are some tricks up Rails' sleeve.
|
538
|
-
|
539
|
-
### Rails with Databases and SCM
|
540
|
-
|
541
|
-
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.
|
542
|
-
|
543
|
-
Let's see what a `--git` option and a `--database=postgresql` option will do for us:
|
544
|
-
|
545
|
-
```bash
|
546
|
-
$ mkdir gitapp
|
547
|
-
$ cd gitapp
|
548
|
-
$ git init
|
549
|
-
Initialized empty Git repository in .git/
|
550
|
-
$ rails new . --git --database=postgresql
|
551
|
-
exists
|
552
|
-
create app/controllers
|
553
|
-
create app/helpers
|
554
|
-
...
|
555
|
-
...
|
556
|
-
create tmp/cache
|
557
|
-
create tmp/pids
|
558
|
-
create Rakefile
|
559
|
-
add 'Rakefile'
|
560
|
-
create README.rdoc
|
561
|
-
add 'README.rdoc'
|
562
|
-
create app/controllers/application_controller.rb
|
563
|
-
add 'app/controllers/application_controller.rb'
|
564
|
-
create app/helpers/application_helper.rb
|
565
|
-
...
|
566
|
-
create log/test.log
|
567
|
-
add 'log/test.log'
|
568
|
-
```
|
569
|
-
|
570
|
-
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:
|
571
|
-
|
572
|
-
```bash
|
573
|
-
$ cat config/database.yml
|
574
|
-
# PostgreSQL. Versions 8.2 and up are supported.
|
575
|
-
#
|
576
|
-
# Install the pg driver:
|
577
|
-
# gem install pg
|
578
|
-
# On OS X with Homebrew:
|
579
|
-
# gem install pg -- --with-pg-config=/usr/local/bin/pg_config
|
580
|
-
# On OS X with MacPorts:
|
581
|
-
# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
|
582
|
-
# On Windows:
|
583
|
-
# gem install pg
|
584
|
-
# Choose the win32 build.
|
585
|
-
# Install PostgreSQL and put its /bin directory on your path.
|
586
|
-
#
|
587
|
-
# Configure Using Gemfile
|
588
|
-
# gem 'pg'
|
589
|
-
#
|
590
|
-
development:
|
591
|
-
adapter: postgresql
|
592
|
-
encoding: unicode
|
593
|
-
database: gitapp_development
|
594
|
-
pool: 5
|
595
|
-
username: gitapp
|
596
|
-
password:
|
597
|
-
...
|
598
|
-
...
|
599
|
-
```
|
600
|
-
|
601
|
-
It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database.
|
602
|
-
|
603
|
-
NOTE. 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 new` command to generate the basis of your app.
|