From 5fb84c6828cea031d829969fed1fdf52d1e94ac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juanjo=20Baz=C3=A1n?= Date: Tue, 8 Jan 2013 23:49:29 +0100 Subject: remove 'update' duplications --- guides/source/active_record_callbacks.md | 1 - guides/source/active_record_validations.md | 1 - 2 files changed, 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/active_record_callbacks.md b/guides/source/active_record_callbacks.md index 3747b00b82..516457bcd3 100644 --- a/guides/source/active_record_callbacks.md +++ b/guides/source/active_record_callbacks.md @@ -157,7 +157,6 @@ The following methods trigger callbacks: * `save!` * `save(validate: false)` * `toggle!` -* `update` * `update_attribute` * `update` * `update!` diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index a911d6b941..eaa47d4ebf 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -117,7 +117,6 @@ database only if the object is valid: * `save` * `save!` * `update` -* `update` * `update!` The bang versions (e.g. `save!`) raise an exception if the record is invalid. -- cgit v1.2.3 From 00f68c52c59e211fbc73f6061db4eaef037afded Mon Sep 17 00:00:00 2001 From: Gosha Arinich Date: Thu, 10 Jan 2013 12:59:56 +0300 Subject: update assets guide code styling * 1.9 hash syntax * proper formatting around one line blocks * do-end for multiline blocks --- guides/source/asset_pipeline.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'guides/source') diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index b302ef76c6..8dc7ba396d 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -37,9 +37,9 @@ You should use the defaults for all new applications unless you have a specific ### Main Features -The first feature of the pipeline is to concatenate assets. This is important in a production environment, because it can reduce the number of requests that a browser must make to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application. +The first feature of the pipeline is to concatenate assets. This is important in a production environment, because it can reduce the number of requests that a browser makes to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application. -Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `:cache => true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries. +Rails 2.x introduced the ability to concatenate JavaScript and CSS assets by placing `cache: true` at the end of the `javascript_include_tag` and `stylesheet_link_tag` methods. But this technique has some limitations. For example, it cannot generate the caches in advance, and it is not able to transparently include assets provided by third-party libraries. Starting with version 3.1, Rails defaults to concatenating all JavaScript files into one master `.js` file and all CSS files into one master `.css` file. As you'll learn later in this guide, you can customize this strategy to group files any way you like. In production, Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser. You can invalidate the cache by altering this fingerprint, which happens automatically whenever you change the file contents. @@ -369,8 +369,8 @@ If any of the files in the manifest have changed between requests, the server re Debug mode can also be enabled in the Rails helper methods: ```erb -<%= stylesheet_link_tag "application", :debug => true %> -<%= javascript_include_tag "application", :debug => true %> +<%= stylesheet_link_tag "application", debug: true %> +<%= javascript_include_tag "application", debug: true %> ``` The `:debug` option is redundant if debug mode is on. @@ -445,7 +445,7 @@ NOTE. If you are precompiling your assets locally, you can use `bundle install - The default matcher for compiling files includes `application.js`, `application.css` and all non-JS/CSS files (this will include all image assets automatically): ```ruby -[ Proc.new{ |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ] +[ Proc.new { |path| !%w(.js .css).include?(File.extname(path)) }, /application.(css|js)$/ ] ``` NOTE. The matcher (and other members of the precompile array; see below) is applied to final compiled file names. This means that anything that compiles to JS/CSS is excluded, as well as raw JS/CSS files; for example, `.coffee` and `.scss` files are **not** automatically included as they compile to JS/CSS. @@ -460,7 +460,7 @@ Or you can opt to precompile all assets with something like this: ```ruby # config/environments/production.rb -config.assets.precompile << Proc.new { |path| +config.assets.precompile << Proc.new do |path| if path =~ /\.(css|js)\z/ full_path = Rails.application.assets.resolve(path).to_path app_assets_path = Rails.root.join('app', 'assets').to_path @@ -474,7 +474,7 @@ config.assets.precompile << Proc.new { |path| else false end -} +end ``` NOTE. Always specify an expected compiled filename that ends with js or css, even if you want to add Sass or CoffeeScript files to the precompile array. @@ -663,7 +663,7 @@ class Transformer end ``` -To enable this, pass a `new` object to the config option in `application.rb`: +To enable this, pass a new object to the config option in `application.rb`: ```ruby config.assets.css_compressor = Transformer.new -- cgit v1.2.3 From 5ff752de1b446b5340316e3d64c377fa05e4f7e7 Mon Sep 17 00:00:00 2001 From: Benoit Caccinolo Date: Fri, 11 Jan 2013 11:38:52 +0100 Subject: Update guides/source/active_record_basics.md --- guides/source/active_record_basics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index 062bcd49f4..69d7333e6f 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -1,6 +1,6 @@ Active Record Basics ==================== - + This guide is an introduction to Active Record. After reading this guide, you will know: -- cgit v1.2.3 From 2222ebb2b0e4d1519b9d2efd3a765b71c411a27e Mon Sep 17 00:00:00 2001 From: Zachary Porter Date: Fri, 11 Jan 2013 13:53:25 -0500 Subject: Update engine application layout file path --- guides/source/engines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index f35233993c..b5af634e59 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -263,7 +263,7 @@ This helps prevent conflicts with any other engine or application that may have Finally, two files that are the assets for this resource are generated, `app/assets/javascripts/blorgh/posts.js` and `app/assets/javascripts/blorgh/posts.css`. You'll see how to use these a little later. -By default, the scaffold styling is not applied to the engine as the engine's layout file, `app/views/blorgh/application.html.erb` doesn't load it. To make this apply, insert this line into the `` tag of this layout: +By default, the scaffold styling is not applied to the engine as the engine's layout file, `app/views/layouts/blorgh/application.html.erb` doesn't load it. To make this apply, insert this line into the `` tag of this layout: ```erb <%= stylesheet_link_tag "scaffold" %> -- cgit v1.2.3 From 0a89d4db1e06d06026bc73726a47d2ef20748070 Mon Sep 17 00:00:00 2001 From: Zachary Porter Date: Fri, 11 Jan 2013 14:07:14 -0500 Subject: Fix typo in guides/source/engines.md --- guides/source/engines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index b5af634e59..649bfad100 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -288,7 +288,7 @@ Now people will only need to go to the root of the engine to see all the posts, ### Generating a comments resource -Now that the engine can to create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. +Now that the engine can create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. Run the model generator and tell it to generate a `Comment` model, with the related table having two columns: a `post_id` integer and `text` text column. -- cgit v1.2.3 From d2d07b3adea8f443296dfb67c9c568d35d1e13bc Mon Sep 17 00:00:00 2001 From: Zachary Porter Date: Fri, 11 Jan 2013 15:26:05 -0500 Subject: Fix typo in guides/source/engines.md --- guides/source/engines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index 649bfad100..0a346b28f9 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -288,7 +288,7 @@ Now people will only need to go to the root of the engine to see all the posts, ### Generating a comments resource -Now that the engine can create new blog posts, it only makes sense to add commenting functionality as well. To do get this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. +Now that the engine can create new blog posts, it only makes sense to add commenting functionality as well. To do this, you'll need to generate a comment model, a comment controller and then modify the posts scaffold to display comments and allow people to create new ones. Run the model generator and tell it to generate a `Comment` model, with the related table having two columns: a `post_id` integer and `text` text column. -- cgit v1.2.3 From c22989d32613f13b3f1b9ed234d9e76c72d60dbd Mon Sep 17 00:00:00 2001 From: Jude Arasu Date: Sun, 13 Jan 2013 09:07:39 +0530 Subject: Fix simple expression --- guides/source/working_with_javascript_in_rails.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/working_with_javascript_in_rails.md b/guides/source/working_with_javascript_in_rails.md index a7ca531123..03ef770352 100644 --- a/guides/source/working_with_javascript_in_rails.md +++ b/guides/source/working_with_javascript_in_rails.md @@ -51,7 +51,7 @@ with an id of `results`. Rails provides quite a bit of built-in support for building web pages with this technique. You rarely have to write this code yourself. The rest of this guide -will show you how Rails can help you write web sites in this manner, but it's +will show you how Rails can help you write websites in this way, but it's all built on top of this fairly simple technique. Unobtrusive JavaScript -- cgit v1.2.3 From 814c9875ec4cf01e1348d1ab1c9d12eee5a9adac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicholas=20Schultz-M=C3=B8ller?= Date: Tue, 15 Jan 2013 14:44:08 +0100 Subject: Improves documentation about Fragment Caching. [ci skip] Adds documentation for: - Aggregate cache keys, - using an ActiveRecord model as cache key and - Russian Doll Caching. --- guides/source/caching_with_rails.md | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index 0228d463cf..c91483ed77 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -86,6 +86,53 @@ This fragment is then available to all actions in the `ProductsController` using expire_fragment('all_available_products') ``` +If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method: + +```ruby +module ProductsHelper + def cache_key_for_products + count = Product.count + max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number) + "products/all-#{count}-#{max_updated_at}" + end +end +``` + +This method generates a cache key that depends on all products and can be used in the view: + +```erb +<% cache(cache_key_for_products) do %> + All available products: +<% end %> +``` + +You can also use an `ActiveRecord` model as the cache key: + +```erb +<% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> +<% end %> +``` + +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. + +You can also combine the two schemes which is called "Russian Doll Caching": + +```erb +<% cache(cache_key_for_products) do %> + All available products: + <% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> + <% end %> +<% end %> +``` + +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. + ### SQL Caching 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. -- cgit v1.2.3 From 4dcc9ddddea12cca2d4e1a6160d0d2db1dfba6f2 Mon Sep 17 00:00:00 2001 From: davetoxa Date: Wed, 16 Jan 2013 01:12:37 +0600 Subject: Revert "Improves documentation about Fragment Caching. [ci skip]" This reverts commit 814c9875ec4cf01e1348d1ab1c9d12eee5a9adac. --- guides/source/caching_with_rails.md | 47 ------------------------------------- 1 file changed, 47 deletions(-) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index c91483ed77..0228d463cf 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -86,53 +86,6 @@ This fragment is then available to all actions in the `ProductsController` using expire_fragment('all_available_products') ``` -If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method: - -```ruby -module ProductsHelper - def cache_key_for_products - count = Product.count - max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number) - "products/all-#{count}-#{max_updated_at}" - end -end -``` - -This method generates a cache key that depends on all products and can be used in the view: - -```erb -<% cache(cache_key_for_products) do %> - All available products: -<% end %> -``` - -You can also use an `ActiveRecord` model as the cache key: - -```erb -<% Product.all.each do |p| %> - <% cache(p) do %> - <%= link_to p.name, product_url(p) %> - <% end %> -<% end %> -``` - -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. - -You can also combine the two schemes which is called "Russian Doll Caching": - -```erb -<% cache(cache_key_for_products) do %> - All available products: - <% Product.all.each do |p| %> - <% cache(p) do %> - <%= link_to p.name, product_url(p) %> - <% end %> - <% end %> -<% end %> -``` - -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. - ### SQL Caching 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. -- cgit v1.2.3 From cc585c8b01105064a2e74bd4f9f5e86616a23c2b Mon Sep 17 00:00:00 2001 From: davetoxa Date: Wed, 16 Jan 2013 01:26:47 +0600 Subject: revert to 814c9875ec4cf01e1348d1ab1c9d12eee5a9adac --- guides/source/caching_with_rails.md | 44 +++++ guides/source/caching_with_rails.md~ | 349 +++++++++++++++++++++++++++++++++++ 2 files changed, 393 insertions(+) create mode 100644 guides/source/caching_with_rails.md~ (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index 0228d463cf..99150de43a 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -85,6 +85,50 @@ This fragment is then available to all actions in the `ProductsController` using ```ruby expire_fragment('all_available_products') ``` +If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method: + +```ruby +module ProductsHelper + def cache_key_for_products + count = Product.count + max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number) + "products/all-#{count}-#{max_updated_at}" + end +end +``` + +This method generates a cache key that depends on all products and can be used in the view: + +```ruby +<% cache(cache_key_for_products) do %> + All available products: +<% end %> +``` +You can also use an `ActiveRecord` model as the cache key: + +```ruby +<% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> +<% end %> +``` + +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. + +You can also combine the two schemes which is called "Russian Doll Caching": + +```ruby +<% cache(cache_key_for_products) do %> + All available products: + <% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> + <% end %> +<% end %> +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. +``` ### SQL Caching diff --git a/guides/source/caching_with_rails.md~ b/guides/source/caching_with_rails.md~ new file mode 100644 index 0000000000..99150de43a --- /dev/null +++ b/guides/source/caching_with_rails.md~ @@ -0,0 +1,349 @@ +Caching with Rails: An overview +=============================== + +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. + +After reading this guide, you will know: + +* Page, action, and fragment caching. +* Sweepers. +* Alternative cache stores. +* Conditional GET support. + +-------------------------------------------------------------------------------- + +Basic Caching +------------- + +This is an introduction to three types of caching techniques: page, action and +fragment caching. Rails provides by default fragment caching. In order to use +page and action caching, you will need to add `actionpack-page_caching` and +`actionpack-action_caching` to your Gemfile. + +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. + +```ruby +config.action_controller.perform_caching = true +``` + +### Page Caching + +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. + +INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching) + +### Action Caching + +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. + +INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching) + +### Fragment Caching + +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. + +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. + +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: + +```html+erb +<% Order.find_recent.each do |o| %> + <%= o.buyer.name %> bought <%= o.product.name %> +<% end %> + +<% cache do %> + All available products: + <% Product.all.each do |p| %> + <%= link_to p.name, product_url(p) %> + <% end %> +<% end %> +``` + +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: + +```html+erb +<% cache(action: 'recent', action_suffix: 'all_products') do %> + All available products: +``` + +and you can expire it using the `expire_fragment` method, like so: + +```ruby +expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products') +``` + +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: + +```erb +<% cache('all_available_products') do %> + All available products: +<% end %> +``` + +This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way: + +```ruby +expire_fragment('all_available_products') +``` +If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method: + +```ruby +module ProductsHelper + def cache_key_for_products + count = Product.count + max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number) + "products/all-#{count}-#{max_updated_at}" + end +end +``` + +This method generates a cache key that depends on all products and can be used in the view: + +```ruby +<% cache(cache_key_for_products) do %> + All available products: +<% end %> +``` +You can also use an `ActiveRecord` model as the cache key: + +```ruby +<% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> +<% end %> +``` + +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. + +You can also combine the two schemes which is called "Russian Doll Caching": + +```ruby +<% cache(cache_key_for_products) do %> + All available products: + <% Product.all.each do |p| %> + <% cache(p) do %> + <%= link_to p.name, product_url(p) %> + <% end %> + <% end %> +<% end %> +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. +``` + +### SQL Caching + +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. + +For example: + +```ruby +class ProductsController < ActionController + + def index + # Run a find query + @products = Product.all + + ... + + # Run the same query again + @products = Product.all + end + +end +``` + +Cache Stores +------------ + +Rails provides different stores for the cached data created by action and fragment caches. + +TIP: Page caches are always stored on disk. + +### Configuration + +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. + +```ruby +config.cache_store = :memory_store +``` + +NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block. + +You can access the cache by calling `Rails.cache`. + +### ActiveSupport::Cache::Store + +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. + +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. + +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. + +* `: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. The default value will include the application name and Rails environment. + +* `: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. + +* `: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. + +* `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache. + +* `: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. + +### ActiveSupport::Cache::MemoryStore + +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. + +```ruby +config.cache_store = :memory_store, { size: 64.megabytes } +``` + +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. + +### ActiveSupport::Cache::FileStore + +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. + +```ruby +config.cache_store = :file_store, "/path/to/cache/directory" +``` + +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. + +Note that the cache will grow until the disk is full unless you periodically clear out old entries. + +This is the default cache store implementation. + +### ActiveSupport::Cache::MemCacheStore + +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 a high performance and redundancy. + +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. + +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. + +```ruby +config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" +``` + +### ActiveSupport::Cache::EhcacheStore + +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. + +```ruby +config.cache_store = :ehcache_store +``` + +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). + +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: + +| Property | Argument Type | Description | +| --------------------------- | ------------------- | ----------------------------------------------------------- | +| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. | +| eternal | boolean | Sets whether the element is eternal. | +| timeToIdle, tti | int | Sets time to idle | +| timeToLive, ttl, expires_in | int | Sets time to Live | +| version | long | Sets the version attribute of the ElementAttributes object. | + +These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples: + +```ruby +Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds) +caches_action :index, expires_in: 60.seconds, unless_exist: true +``` + +For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) . +For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html) + +### ActiveSupport::Cache::NullStore + +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. + +```ruby +config.cache_store = :null_store +``` + +### Custom Cache Stores + +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. + +To use a custom cache store, simple set the cache store to a new instance of the class. + +```ruby +config.cache_store = MyCacheStore.new +``` + +### Cache Keys + +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. + +You can use Hashes and Arrays of values as cache keys. + +```ruby +# This is a legal cache key +Rails.cache.read(site: "mysite", owners: [owner_1, owner_2]) +``` + +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. + +Conditional GET support +----------------------- + +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. + +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. + +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: + +```ruby +class ProductsController < ApplicationController + + def show + @product = Product.find(params[:id]) + + # If the request is stale according to the given timestamp and etag value + # (i.e. it needs to be processed again) then execute this block + if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key) + respond_to do |wants| + # ... normal response processing + end + end + + # If the request is fresh (i.e. it's not modified) then you don't need to do + # anything. The default render checks for this using the parameters + # used in the previous call to stale? and will automatically send a + # :not_modified. So that's it, you're done. + end +end +``` + +Instead of a 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`: + +```ruby +class ProductsController < ApplicationController + def show + @product = Product.find(params[:id]) + respond_with(@product) if stale?(@product) + end +end +``` + +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: + +```ruby +class ProductsController < ApplicationController + + # This will automatically send back a :not_modified if the request is fresh, + # and will render the default template (product.*) if it's stale. + + def show + @product = Product.find(params[:id]) + fresh_when last_modified: @product.published_at.utc, etag: @product + end +end +``` + +Further reading +--------------- + +* [Scaling Rails Screencasts](http://railslab.newrelic.com/scaling-rails) -- cgit v1.2.3 From 3daa8e51ccebd8563926cd5ddb17dbb4156be9cb Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Tue, 15 Jan 2013 21:01:30 +0100 Subject: removes spurious file pushed in cc585c8 --- guides/source/caching_with_rails.md~ | 349 ----------------------------------- 1 file changed, 349 deletions(-) delete mode 100644 guides/source/caching_with_rails.md~ (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md~ b/guides/source/caching_with_rails.md~ deleted file mode 100644 index 99150de43a..0000000000 --- a/guides/source/caching_with_rails.md~ +++ /dev/null @@ -1,349 +0,0 @@ -Caching with Rails: An overview -=============================== - -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. - -After reading this guide, you will know: - -* Page, action, and fragment caching. -* Sweepers. -* Alternative cache stores. -* Conditional GET support. - --------------------------------------------------------------------------------- - -Basic Caching -------------- - -This is an introduction to three types of caching techniques: page, action and -fragment caching. Rails provides by default fragment caching. In order to use -page and action caching, you will need to add `actionpack-page_caching` and -`actionpack-action_caching` to your Gemfile. - -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. - -```ruby -config.action_controller.perform_caching = true -``` - -### Page Caching - -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. - -INFO: Page Caching has been removed from Rails 4. See the [actionpack-page_caching gem](https://github.com/rails/actionpack-page_caching) - -### Action Caching - -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. - -INFO: Action Caching has been removed from Rails 4. See the [actionpack-action_caching gem](https://github.com/rails/actionpack-action_caching) - -### Fragment Caching - -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. - -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. - -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: - -```html+erb -<% Order.find_recent.each do |o| %> - <%= o.buyer.name %> bought <%= o.product.name %> -<% end %> - -<% cache do %> - All available products: - <% Product.all.each do |p| %> - <%= link_to p.name, product_url(p) %> - <% end %> -<% end %> -``` - -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: - -```html+erb -<% cache(action: 'recent', action_suffix: 'all_products') do %> - All available products: -``` - -and you can expire it using the `expire_fragment` method, like so: - -```ruby -expire_fragment(controller: 'products', action: 'recent', action_suffix: 'all_products') -``` - -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: - -```erb -<% cache('all_available_products') do %> - All available products: -<% end %> -``` - -This fragment is then available to all actions in the `ProductsController` using the key and can be expired the same way: - -```ruby -expire_fragment('all_available_products') -``` -If you want to avoid expiring the fragment manually, whenever an action updates a product, you can define a helper method: - -```ruby -module ProductsHelper - def cache_key_for_products - count = Product.count - max_updated_at = Product.maximum(:updated_at).try(:utc).try(:to_s, :number) - "products/all-#{count}-#{max_updated_at}" - end -end -``` - -This method generates a cache key that depends on all products and can be used in the view: - -```ruby -<% cache(cache_key_for_products) do %> - All available products: -<% end %> -``` -You can also use an `ActiveRecord` model as the cache key: - -```ruby -<% Product.all.each do |p| %> - <% cache(p) do %> - <%= link_to p.name, product_url(p) %> - <% end %> -<% end %> -``` - -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. - -You can also combine the two schemes which is called "Russian Doll Caching": - -```ruby -<% cache(cache_key_for_products) do %> - All available products: - <% Product.all.each do |p| %> - <% cache(p) do %> - <%= link_to p.name, product_url(p) %> - <% end %> - <% end %> -<% end %> -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. -``` - -### SQL Caching - -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. - -For example: - -```ruby -class ProductsController < ActionController - - def index - # Run a find query - @products = Product.all - - ... - - # Run the same query again - @products = Product.all - end - -end -``` - -Cache Stores ------------- - -Rails provides different stores for the cached data created by action and fragment caches. - -TIP: Page caches are always stored on disk. - -### Configuration - -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. - -```ruby -config.cache_store = :memory_store -``` - -NOTE: Alternatively, you can call `ActionController::Base.cache_store` outside of a configuration block. - -You can access the cache by calling `Rails.cache`. - -### ActiveSupport::Cache::Store - -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. - -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. - -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. - -* `: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. The default value will include the application name and Rails environment. - -* `: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. - -* `: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. - -* `:expires_in` - This option sets an expiration time in seconds for the cache entry when it will be automatically removed from the cache. - -* `: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. - -### ActiveSupport::Cache::MemoryStore - -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. - -```ruby -config.cache_store = :memory_store, { size: 64.megabytes } -``` - -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. - -### ActiveSupport::Cache::FileStore - -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. - -```ruby -config.cache_store = :file_store, "/path/to/cache/directory" -``` - -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. - -Note that the cache will grow until the disk is full unless you periodically clear out old entries. - -This is the default cache store implementation. - -### ActiveSupport::Cache::MemCacheStore - -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 a high performance and redundancy. - -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. - -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. - -```ruby -config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" -``` - -### ActiveSupport::Cache::EhcacheStore - -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. - -```ruby -config.cache_store = :ehcache_store -``` - -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). - -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: - -| Property | Argument Type | Description | -| --------------------------- | ------------------- | ----------------------------------------------------------- | -| elementEvictionData | ElementEvictionData | Sets this element's eviction data instance. | -| eternal | boolean | Sets whether the element is eternal. | -| timeToIdle, tti | int | Sets time to idle | -| timeToLive, ttl, expires_in | int | Sets time to Live | -| version | long | Sets the version attribute of the ElementAttributes object. | - -These options are passed to the `write` method as Hash options using either camelCase or underscore notation, as in the following examples: - -```ruby -Rails.cache.write('key', 'value', time_to_idle: 60.seconds, timeToLive: 600.seconds) -caches_action :index, expires_in: 60.seconds, unless_exist: true -``` - -For more information about Ehcache, see [http://ehcache.org/](http://ehcache.org/) . -For more information about Ehcache for JRuby and Rails, see [http://ehcache.org/documentation/jruby.html](http://ehcache.org/documentation/jruby.html) - -### ActiveSupport::Cache::NullStore - -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. - -```ruby -config.cache_store = :null_store -``` - -### Custom Cache Stores - -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. - -To use a custom cache store, simple set the cache store to a new instance of the class. - -```ruby -config.cache_store = MyCacheStore.new -``` - -### Cache Keys - -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. - -You can use Hashes and Arrays of values as cache keys. - -```ruby -# This is a legal cache key -Rails.cache.read(site: "mysite", owners: [owner_1, owner_2]) -``` - -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. - -Conditional GET support ------------------------ - -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. - -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. - -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: - -```ruby -class ProductsController < ApplicationController - - def show - @product = Product.find(params[:id]) - - # If the request is stale according to the given timestamp and etag value - # (i.e. it needs to be processed again) then execute this block - if stale?(last_modified: @product.updated_at.utc, etag: @product.cache_key) - respond_to do |wants| - # ... normal response processing - end - end - - # If the request is fresh (i.e. it's not modified) then you don't need to do - # anything. The default render checks for this using the parameters - # used in the previous call to stale? and will automatically send a - # :not_modified. So that's it, you're done. - end -end -``` - -Instead of a 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`: - -```ruby -class ProductsController < ApplicationController - def show - @product = Product.find(params[:id]) - respond_with(@product) if stale?(@product) - end -end -``` - -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: - -```ruby -class ProductsController < ApplicationController - - # This will automatically send back a :not_modified if the request is fresh, - # and will render the default template (product.*) if it's stale. - - def show - @product = Product.find(params[:id]) - fresh_when last_modified: @product.published_at.utc, etag: @product - end -end -``` - -Further reading ---------------- - -* [Scaling Rails Screencasts](http://railslab.newrelic.com/scaling-rails) -- cgit v1.2.3 From 728f9c2eed42959d5a3e9202ba80635872738c5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicholas=20Schultz-M=C3=B8ller?= Date: Wed, 16 Jan 2013 11:44:55 +0100 Subject: Fix formatting error introduced in cc585c8. --- guides/source/caching_with_rails.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index 99150de43a..7e33edda86 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -127,9 +127,10 @@ You can also combine the two schemes which is called "Russian Doll Caching": <% end %> <% end %> <% end %> -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. ``` +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. + ### SQL Caching 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. -- cgit v1.2.3 From f58e268e38f781c618773307da4e3273ad912671 Mon Sep 17 00:00:00 2001 From: Jonathan Garvin Date: Wed, 16 Jan 2013 19:19:31 -0700 Subject: clarify awkward sentence re: email testing --- guides/source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/testing.md b/guides/source/testing.md index 7747318d32..0b3bed8dbe 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -945,7 +945,7 @@ Cheers! This is the right time to understand a little more about writing tests for your mailers. The line `ActionMailer::Base.delivery_method = :test` in `config/environments/test.rb` sets the delivery method to test mode so that email will not actually be delivered (useful to avoid spamming your users while testing) but instead it will be appended to an array (`ActionMailer::Base.deliveries`). -However often in unit tests, mails will not actually be sent, simply constructed, as in the example above, where the precise content of the email is checked against what it should be. +This way, emails are not actually sent, simply constructed. The precise content of the email can then be checked against what is expected, as in the example above. ### Functional Testing -- cgit v1.2.3 From 3fa73324c59299e4c9ac68b81fa84fd7eea8eaac Mon Sep 17 00:00:00 2001 From: Erik Johnson Date: Thu, 17 Jan 2013 14:25:18 -0700 Subject: for recommended Apache configuration of asset pipeline, use instead of , to avoid unnecessary reg ex parsing and code + # Use of ETag is discouraged when Last-Modified is present Header unset ETag FileETag None # RFC says only cache for 1 year ExpiresActive On ExpiresDefault "access plus 1 year" - + ``` For nginx: -- cgit v1.2.3 From cb60a83377ccace58f64dd626708b50efed8a999 Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Fri, 18 Jan 2013 22:18:33 +0900 Subject: "Asynchronous Mailers" will not be available in 4.0 --- guides/source/4_0_release_notes.md | 1 - 1 file changed, 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 002e1da5af..95b57ec899 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -7,7 +7,6 @@ Highlights in Rails 4.0: * Strong Parameters * Turbolinks * Russian Doll Caching -* Asynchronous Mailers These release notes cover only the major changes. To know about various bug fixes and changes, please refer to the change logs or check out the [list of commits](https://github.com/rails/rails/commits/master) in the main Rails repository on GitHub. -- cgit v1.2.3 From 46752092ef222d8ae5c1e314f18aefab8a167c05 Mon Sep 17 00:00:00 2001 From: Thomas Drake-Brockman Date: Sun, 20 Jan 2013 00:23:55 +0800 Subject: Replaced documentation for config.action_controller.raise_on_unpermitted_parameters with documentation for config.action_controller.action_on_unpermitted_params. --- guides/source/configuring.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/configuring.md b/guides/source/configuring.md index ced04bbbc0..676458f046 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -304,7 +304,7 @@ The schema dumper adds one additional configuration option: * `config.action_controller.permit_all_parameters` sets all the parameters for mass assignment to be permitted by default. The default value is `false`. -* `config.action_controller.raise_on_unpermitted_parameters` enables raising an exception if parameters that are not explicitly permitted are found. The default value is `true` in development and test environments, `false` otherwise. +* `config.action_controller.action_on_unpermitted_params` enables logging or raising an exception if parameters that are not explicitly permitted are found. Set to `:log` or `:raise` to enable. The default value is `:log` in development and test environments, and `false` in all other environments. ### Configuring Action Dispatch -- cgit v1.2.3 From 2b7a621e6a3bcbe40432d7adb75d5acdd798d1c6 Mon Sep 17 00:00:00 2001 From: Lucas Caton Date: Sat, 19 Jan 2013 15:49:28 -0200 Subject: Replacing plugin to gem --- guides/source/migrations.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/migrations.md b/guides/source/migrations.md index 617e01bd15..cefbc3b829 100644 --- a/guides/source/migrations.md +++ b/guides/source/migrations.md @@ -474,7 +474,7 @@ class ExampleMigration < ActiveRecord::Migration t.references :category end - #add a foreign key + # add a foreign key execute <<-SQL ALTER TABLE products ADD CONSTRAINT fk_products_categories @@ -1011,7 +1011,7 @@ with foreign key constraints in the database. Although Active Record does not provide any tools for working directly with such features, the `execute` method can be used to execute arbitrary SQL. You -could also use some plugin like +could also use some gem like [foreigner](https://github.com/matthuhiggins/foreigner) which add foreign key support to Active Record (including support for dumping foreign keys in `db/schema.rb`). -- cgit v1.2.3 From 03a391482aa6a9d532eb43bb3e697852e0b83618 Mon Sep 17 00:00:00 2001 From: Cyril Jouve Date: Sun, 20 Jan 2013 03:38:45 +0100 Subject: consistently inherit from ApplicationController in guides exemples --- guides/source/action_controller_overview.md | 4 ++-- guides/source/caching_with_rails.md | 2 +- guides/source/nested_model_forms.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index cc80334af3..7260a48c8c 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -58,7 +58,7 @@ Parameters You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the `params` hash in your controller: ```ruby -class ClientsController < ActionController::Base +class ClientsController < ApplicationController # This action uses query string parameters because it gets run # by an HTTP GET request, but this does not make any difference # to the way in which the parameters are accessed. The URL for @@ -479,7 +479,7 @@ In addition to "before" filters, you can also run filters after an action has be For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction: ```ruby -class ChangesController < ActionController::Base +class ChangesController < ApplicationController around_action :wrap_in_transaction, only: :show private diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index 7e33edda86..7e4253b1ba 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -138,7 +138,7 @@ Query caching is a Rails feature that caches the result set returned by each que For example: ```ruby -class ProductsController < ActionController +class ProductsController < ApplicationController def index # Run a find query diff --git a/guides/source/nested_model_forms.md b/guides/source/nested_model_forms.md index 93d8e8dfcd..b90b3bb5fc 100644 --- a/guides/source/nested_model_forms.md +++ b/guides/source/nested_model_forms.md @@ -98,7 +98,7 @@ A nested model form will _only_ be built if the associated object(s) exist. This Consider the following typical RESTful controller which will prepare a new Person instance and its `address` and `projects` associations before rendering the `new` template: ```ruby -class PeopleController < ActionController:Base +class PeopleController < ApplicationController def new @person = Person.new @person.built_address -- cgit v1.2.3 From 634a2aafbea9e50a722a9f0245d650239296f3be Mon Sep 17 00:00:00 2001 From: Brian Littmann Date: Tue, 22 Jan 2013 15:17:16 -0600 Subject: Typo fix in guides/source/engines.md --- guides/source/engines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index 0a346b28f9..bcbabc7eec 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -261,7 +261,7 @@ end This helps prevent conflicts with any other engine or application that may have a post resource as well. -Finally, two files that are the assets for this resource are generated, `app/assets/javascripts/blorgh/posts.js` and `app/assets/javascripts/blorgh/posts.css`. You'll see how to use these a little later. +Finally, two files that are the assets for this resource are generated, `app/assets/javascripts/blorgh/posts.js` and `app/assets/stylesheets/blorgh/posts.css`. You'll see how to use these a little later. By default, the scaffold styling is not applied to the engine as the engine's layout file, `app/views/layouts/blorgh/application.html.erb` doesn't load it. To make this apply, insert this line into the `` tag of this layout: -- cgit v1.2.3 From bceeeaa4bd06e526b72538bd5206a3227f6fb2cb Mon Sep 17 00:00:00 2001 From: Brian Littmann Date: Tue, 22 Jan 2013 15:59:49 -0600 Subject: Typo, grammar, and comma love. --- guides/source/engines.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index bcbabc7eec..f6c7800828 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -470,7 +470,7 @@ If you have multiple engines that need migrations copied over, use `railties:ins $ rake railties:install:migrations ``` -This command, when run for the first time will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this: +This command, when run for the first time, will copy over all the migrations from the engine. When run the next time, it will only copy over migrations that haven't been copied over already. The first run for this command will output something such as this: ```bash Copied migration [timestamp_1]_create_blorgh_posts.rb from blorgh @@ -754,7 +754,7 @@ end #### Implementing Decorator Pattern Using ActiveSupport::Concern -Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html) helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code. +Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html) which helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code. **Adding** `Post#time_since_created`
**Overriding** `Post#summary` @@ -790,7 +790,7 @@ module Blorgh::Concerns::Models::Post extend ActiveSupport::Concern # 'included do' causes the included code to be evaluated in the - # conext where it is included (post.rb), rather than be + # context where it is included (post.rb), rather than be # executed in the module's context (blorgh/concerns/models/post). included do attr_accessor :author_name @@ -840,7 +840,7 @@ Try this now by creating a new file at `app/views/blorgh/posts/index.html.erb` a ### Routes -Routes inside an engine are, by default, isolated from the application. This is done by the `isolate_namespace` call inside the `Engine` class. This essentially means that the application and its engines can have identically named routes, and that they will not clash. +Routes inside an engine are, by default, isolated from the application. This is done by the `isolate_namespace` call inside the `Engine` class. This essentially means that the application and its engines can have identically named routes and they will not clash. Routes inside an engine are drawn on the `Engine` class within `config/routes.rb`, like this: -- cgit v1.2.3 From d35b76283bb1de54907e797ebcd4f3885a28a82c Mon Sep 17 00:00:00 2001 From: Vipul A M Date: Wed, 23 Jan 2013 20:45:31 +0530 Subject: Add new DB rake tasks to the contributing section. --- guides/source/development_dependencies_install.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'guides/source') diff --git a/guides/source/development_dependencies_install.md b/guides/source/development_dependencies_install.md index db43d62fcf..6493c1e1ec 100644 --- a/guides/source/development_dependencies_install.md +++ b/guides/source/development_dependencies_install.md @@ -174,6 +174,20 @@ $ cd activerecord $ bundle exec rake postgresql:build_databases ``` +It is possible to build databases for both PostgreSQL and MySQL with + +```bash +$ cd activerecord +$ bundle exec rake db:create +``` + +You can cleanup the databases using + +```bash +$ cd activerecord +$ bundle exec rake db:drop +``` + NOTE: Using the rake task to create the test databases ensures they have the correct character set and collation. NOTE: You'll see the following warning (or localized warning) during activating HStore extension in PostgreSQL 9.1.x or earlier: "WARNING: => is deprecated as an operator". -- cgit v1.2.3 From 9133aadfe2f390efe6c931a39c8724189b1d5bff Mon Sep 17 00:00:00 2001 From: Weston Platter Date: Thu, 24 Jan 2013 02:42:21 -0600 Subject: [engines guide] reworded a run on --- guides/source/engines.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index f6c7800828..20989cc61b 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -754,10 +754,9 @@ end #### Implementing Decorator Pattern Using ActiveSupport::Concern -Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html) which helps manage load order of interlinked dependencies at run time allowing you to significantly modularize your code. +Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`](http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html). ActiveSupport::Concern manages load order of interlinked dependent modules and classes at run time allowing you to significantly modularize your code. -**Adding** `Post#time_since_created`
-**Overriding** `Post#summary` +**Adding** `Post#time_since_created` and **Overriding** `Post#summary` ```ruby # MyApp/app/models/blorgh/post.rb -- cgit v1.2.3 From 97b249112d2a66ac19828e0c3875681d4d60c08f Mon Sep 17 00:00:00 2001 From: Weston Platter Date: Thu, 24 Jan 2013 02:42:40 -0600 Subject: [engines guide] reformatted some stuff --- guides/source/engines.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'guides/source') diff --git a/guides/source/engines.md b/guides/source/engines.md index 20989cc61b..459aa8d57e 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -799,9 +799,9 @@ module Blorgh::Concerns::Models::Post private - def set_author - self.author = User.find_or_create_by(name: author_name) - end + def set_author + self.author = User.find_or_create_by(name: author_name) + end end def summary -- cgit v1.2.3 From 550299a6712cf5731f007176cb9f2135f813e9e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juanjo=20Baz=C3=A1n?= Date: Fri, 25 Jan 2013 22:53:49 +0100 Subject: fix Active Record/Action Pack Changelog links --- guides/source/4_0_release_notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'guides/source') diff --git a/guides/source/4_0_release_notes.md b/guides/source/4_0_release_notes.md index 95b57ec899..655f26e253 100644 --- a/guides/source/4_0_release_notes.md +++ b/guides/source/4_0_release_notes.md @@ -148,7 +148,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activ Action Pack ----------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) for detailed changes. ### Notable changes @@ -160,7 +160,7 @@ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railt Active Record ------------- -Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes. +Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activerecord/CHANGELOG.md) for detailed changes. ### Notable changes -- cgit v1.2.3 From 4e5a4cf4b2b52815bcba8fcd4bab52fe5a8f161b Mon Sep 17 00:00:00 2001 From: Andrew Wilcox Date: Fri, 25 Jan 2013 23:45:55 -0500 Subject: Remove mass-assignment line from guide summary --- guides/source/security.md | 1 - 1 file changed, 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/security.md b/guides/source/security.md index 3706a61431..769bd130be 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -9,7 +9,6 @@ After reading this guide, you will know: * The concept of sessions in Rails, what to put in there and popular attack methods. * How just visiting a site can be a security problem (with CSRF). * What you have to pay attention to when working with files or providing an administration interface. -* The Rails-specific mass assignment problem. * How to manage users: Logging in and out and attack methods on all layers. * And the most popular injection attack methods. -- cgit v1.2.3 From 4313461587254fd8e5b5a8ea7dfc9f0230c70ecb Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 26 Jan 2013 17:36:38 +0100 Subject: generic pass before merging docrails --- guides/source/caching_with_rails.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'guides/source') diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md index 7e4253b1ba..e52264f296 100644 --- a/guides/source/caching_with_rails.md +++ b/guides/source/caching_with_rails.md @@ -104,7 +104,7 @@ This method generates a cache key that depends on all products and can be used i All available products: <% end %> ``` -You can also use an `ActiveRecord` model as the cache key: +You can also use an Active Record model as the cache key: ```ruby <% Product.all.each do |p| %> -- cgit v1.2.3