Permalink
Browse files

Take out some special characters that sneaked in

  • Loading branch information...
1 parent 9deb327 commit 77aa8a6b815db56c530ef5270e4cd386940befac @aditya aditya committed Feb 23, 2009
Showing with 16 additions and 15 deletions.
  1. +16 −15 railties/guides/source/caching_with_rails.textile

Continuing with our Product controller example, we could rewrite it with a
sweeper such as the following:

class StoreSweeper < ActionController::Caching::Sweeper
observe Product # This sweeper is going to keep an eye on the Product model

  1. If our sweeper detects that a Product was created call this
    def after_create(product)
    expire_cache_for(product)
    end
  1. If our sweeper detects that a Product was updated call this
    def after_update(product)
    expire_cache_for(product)
    end
  1. If our sweeper detects that a Product was deleted call this
    def after_destroy(product)
    expire_cache_for(product)
    end
private def expire_cache_for(record)
  1. Expire the list page now that we added a new product
    expire_page(:controller => ‘#{record}’, :action => ‘list’)
  1. Expire a fragment
    expire_fragment(:controller => ‘#{record}’, :action => ‘recent’, :action_suffix => ‘all_products’)
    end
    end

Then we add it to our controller to tell it to call the sweeper when certain
actions are called. So, if we wanted to expire the cached content for the
list and edit actions when the create action was called, we could do the
following:

class ProductsController < ActionController

before_filter :authenticate, :only => [ :edit, :create ] caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] def list; end def create expire_page :action => :list expire_action :action => :edit end def edit; end

end

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 used the cached result set as opposed to running the query against the
database again.

For example:

class ProductsController < ActionController

before_filter :authenticate, :only => [ :edit, :create ] caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] def list
  1. Run a find query
    Product.find(:all)
  1. Run the same query again
    Product.find(:all)
    end
def create expire_page :action => :list expire_action :action => :edit end def edit; end

end

In the ‘list’ action above, the result set returned by the first
Product.find(:all) will be cached and will be used to avoid querying the
database again the second time that finder is called.

Query caches are created at the start of an action and destroyed at the end of
that action and thus persist only for the duration of the action.

Cache stores

Rails (as of 2.1) provides different stores for the cached data for action and
fragment caches. Page caches are always stored on disk.

Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to
cache strings. Some cache store implementations, like MemoryStore, are able to
cache arbitrary Ruby objects, but don‘t count on every cache store to be able
to do that.

The default cache stores provided include:

1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores
everything into memory in the same process. If you‘re running multiple Ruby on
Rails server processes (which is the case if you‘re using mongrel_cluster or
Phusion Passenger), then this means that your Rails server process instances
won‘t be able to share cache data with each other. If your application never
performs manual cache item expiry (e.g. when you‘re using generational cache
keys), then using MemoryStore is ok. Otherwise, consider carefully whether you
should be using this cache store.

MemoryStore is not only able to store strings, but also arbitrary Ruby objects.

MemoryStore is not thread-safe. Use SynchronizedMemoryStore instead if you
need thread-safety.

ActionController::Base.cache_store = :memory_store

2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk, this is
the default store and the default path for this store is: /tmp/cache. Works
well for all types of environments and allows all processes running from the
same application directory to access the cached content. If /tmp/cache does not
exist, the default store becomes MemoryStore.

ActionController::Base.cache_store = :file_store, “/path/to/cache/directory”

3) ActiveSupport::Cache::DRbStore: Cached data is stored in a separate shared
DRb process that all servers communicate with. This works for all environments
and only keeps one cache around for all processes, but requires that you run
and manage a separate DRb process.

ActionController::Base.cache_store = :drb_store, “druby://localhost:9192”

4) MemCached store: Works like DRbStore, but uses Danga’s MemCache instead.
Rails uses the bundled memcached-client gem by default. This is currently the
most popular cache store for production websites.

Special features:

  • Clustering and load balancing. One can specify multiple memcached servers,
    and MemCacheStore will load balance between all available servers. If a
    server goes down, then MemCacheStore will ignore it until it goes back
    online.
  • Time-based expiry support. See write and the :expires_in option.
  • Per-request in memory cache for all communication with the MemCache server(s).

It also accepts a hash of additional options:

  • :namespace – specifies a string that will automatically be prepended to keys when accessing the memcached store.
  • :readonly – a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
  • :multithread – a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.

The read and write methods of the MemCacheStore accept an options hash too.
When reading you can specify :raw => true to prevent the object being marshaled
(by default this is false which means the raw value in the cache is passed to
Marshal.load before being returned to you.)

When writing to the cache it is also possible to specify :raw => true means the
value is not passed to Marshal.dump before being stored in the cache (by
default this is false).

The write method also accepts an :unless_exist flag which determines whether
the memcached add (when true) or set (when false) method is used to store the
item in the cache and an :expires_in option that specifies the time-to-live for
the cached item in seconds.

ActionController::Base.cache_store = :mem_cache_store, “localhost”

5) ActiveSupport::Cache::SynchronizedMemoryStore: Like ActiveSupport::Cache::MemoryStore but thread-safe.

ActionController::Base.cache_store = :synchronized_memory_store

6) ActiveSupport::Cache::CompressedMemCacheStore: Works just like the regular
MemCacheStore but uses GZip to decompress/compress on read/write.

ActionController::Base.cache_store = :compressed_mem_cache_store, “localhost”

7) Custom store: You can define your own cache store (new in Rails 2.1)

ActionController::Base.cache_store = MyOwnStore.new(“parameter”)

Note: config.cache_store can be used in place of
ActionController::Base.cache_store in your Rails::Initializer.run block in
environment.rb

In addition to all of this, Rails also adds the ActiveRecord::Base#cache_key
method that generates a key using the class name, id and updated_at timestamp
(if available).

An example:

Rails.cache.read(“city”) # => nil
Rails.cache.write(“city”, “Duckburgh”)
Rails.cache.read(“city”) # => “Duckburgh”

Conditional GET support

Conditional GETs are a facility of the HTTP spec 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:

class ProductsController < ApplicationController

def show @product = Product.find(params[:id])
  1. If the request is stale according to the given timestamp and etag value
  2. (i.e. it needs to be processed again) then execute this block
    if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
    respond_to do |wants|
  3. … normal response processing
    end
    end
  1. If the request is fresh (i.e. it’s not modified) then you don’t need to do
  2. anything. The default render checks for this using the parameters
  3. used in the previous call to stale? and will automatically send a
  4. :not_modified. So that’s it, you’re done.
    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:

class ProductsController < ApplicationController

  1. This will automatically send back a :not_modified if the request is fresh,
  2. 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 => @article end

end

Advanced Caching

Along with the built-in mechanisms outlined above, a number of excellent
plugins exist to help with finer grained control over caching. These include
Chris Wanstrath’s excellent cache_fu plugin (more info here:
http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver’s
interlock plugin (more info here:
http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
of these plugins play nice with memcached and are a must-see for anyone
seriously considering optimizing their caching needs.

Changelog
Lighthouse ticket

February 22, 2009: Beefed up the section on cache_stores
December 27, 2008: Typo fixes
November 23, 2008: Incremental updates with various suggested changes and formatting cleanup
September 15, 2008: Initial version by Aditya Chadha

class StoreSweeper < ActionController::Caching::Sweeper
observe Product # This sweeper is going to keep an eye on the Product model

  1. If our sweeper detects that a Product was created call this
    def after_create(product)
    expire_cache_for(product)
    end
  1. If our sweeper detects that a Product was updated call this
    def after_update(product)
    expire_cache_for(product)
    end
  1. If our sweeper detects that a Product was deleted call this
    def after_destroy(product)
    expire_cache_for(product)
    end
private def expire_cache_for(record)
  1. Expire the list page now that we added a new product
    expire_page(:controller => ‘#{record}’, :action => ‘list’)
  1. Expire a fragment
    expire_fragment(:controller => ‘#{record}’, :action => ‘recent’, :action_suffix => ‘all_products’)
    end
    end

Then we add it to our controller to tell it to call the sweeper when certain
actions are called. So, if we wanted to expire the cached content for the
list and edit actions when the create action was called, we could do the
following:

class ProductsController < ActionController

before_filter :authenticate, :only => [ :edit, :create ] caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] def list; end def create expire_page :action => :list expire_action :action => :edit end def edit; end

end

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 used the cached result set as opposed to running the query against the
database again.

For example:

class ProductsController < ActionController

before_filter :authenticate, :only => [ :edit, :create ] caches_page :list caches_action :edit cache_sweeper :store_sweeper, :only => [ :create ] def list
  1. Run a find query
    Product.find(:all)
  1. Run the same query again
    Product.find(:all)
    end
def create expire_page :action => :list expire_action :action => :edit end def edit; end

end

In the ‘list’ action above, the result set returned by the first
Product.find(:all) will be cached and will be used to avoid querying the
database again the second time that finder is called.

Query caches are created at the start of an action and destroyed at the end of
that action and thus persist only for the duration of the action.

Cache stores

Rails (as of 2.1) provides different stores for the cached data for action and
fragment caches. Page caches are always stored on disk.

Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to
cache strings. Some cache store implementations, like MemoryStore, are able to
cache arbitrary Ruby objects, but don’t count on every cache store to be able
to do that.

The default cache stores provided include:

1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores
everything into memory in the same process. If you’re running multiple Ruby on
Rails server processes (which is the case if you’re using mongrel_cluster or
Phusion Passenger), then this means that your Rails server process instances
won‘t be able to share cache data with each other. If your application never
performs manual cache item expiry (e.g. when you‘re using generational cache
keys), then using MemoryStore is ok. Otherwise, consider carefully whether you
should be using this cache store.

MemoryStore is not only able to store strings, but also arbitrary Ruby objects.

MemoryStore is not thread-safe. Use SynchronizedMemoryStore instead if you
need thread-safety.

ActionController::Base.cache_store = :memory_store

2) ActiveSupport::Cache::FileStore: Cached data is stored on the disk, this is
the default store and the default path for this store is: /tmp/cache. Works
well for all types of environments and allows all processes running from the
same application directory to access the cached content. If /tmp/cache does not
exist, the default store becomes MemoryStore.

ActionController::Base.cache_store = :file_store, “/path/to/cache/directory”

3) ActiveSupport::Cache::DRbStore: Cached data is stored in a separate shared
DRb process that all servers communicate with. This works for all environments
and only keeps one cache around for all processes, but requires that you run
and manage a separate DRb process.

ActionController::Base.cache_store = :drb_store, “druby://localhost:9192”

4) MemCached store: Works like DRbStore, but uses Danga’s MemCache instead.
Rails uses the bundled memcached-client gem by default. This is currently the
most popular cache store for production websites.

Special features:

  • Clustering and load balancing. One can specify multiple memcached servers,
    and MemCacheStore will load balance between all available servers. If a
    server goes down, then MemCacheStore will ignore it until it goes back
    online.
  • Time-based expiry support. See write and the :expires_in option.
  • Per-request in memory cache for all communication with the MemCache server(s).

It also accepts a hash of additional options:

  • :namespace- specifies a string that will automatically be prepended to keys when accessing the memcached store.
  • :readonly- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
  • :multithread – a boolean value that adds thread safety to read/write operations – it is unlikely you’ll need to use this option as the Rails threadsafe! method offers the same functionality.

The read and write methods of the MemCacheStore accept an options hash too.
When reading you can specify :raw => true to prevent the object being
marshaled
(by default this is false which means the raw value in the cache is passed to
Marshal.load before being returned to you.)

When writing to the cache it is also possible to specify :raw => true means
the value is not passed to Marshal.dump before being stored in the cache (by
default this is false).

The write method also accepts an :unless_exist flag which determines whether
the memcached add (when true) or set (when false) method is used to store the
item in the cache and an :expires_in option that specifies the time-to-live
for the cached item in seconds.

ActionController::Base.cache_store = :mem_cache_store, “localhost”

5) ActiveSupport::Cache::SynchronizedMemoryStore: Like ActiveSupport::Cache::MemoryStore but thread-safe.

ActionController::Base.cache_store = :synchronized_memory_store

6) ActiveSupport::Cache::CompressedMemCacheStore: Works just like the regular
MemCacheStore but uses GZip to decompress/compress on read/write.

ActionController::Base.cache_store = :compressed_mem_cache_store, “localhost”

7) Custom store: You can define your own cache store (new in Rails 2.1)

ActionController::Base.cache_store = MyOwnStore.new(“parameter”)

Note: config.cache_store can be used in place of
ActionController::Base.cache_store in your Rails::Initializer.run block in
environment.rb

In addition to all of this, Rails also adds the ActiveRecord::Base#cache_key
method that generates a key using the class name, id and updated_at timestamp
(if available).

An example:

Rails.cache.read(“city”) # => nil
Rails.cache.write(“city”, “Duckburgh”)
Rails.cache.read(“city”) # => “Duckburgh”

Conditional GET support

Conditional GETs are a facility of the HTTP spec 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:

class ProductsController < ApplicationController

def show @product = Product.find(params[:id])
  1. If the request is stale according to the given timestamp and etag value
  2. (i.e. it needs to be processed again) then execute this block
    if stale?(:last_modified => @product.updated_at.utc, :etag => @product)
    respond_to do |wants|
  3. … normal response processing
    end
    end
  1. If the request is fresh (i.e. it’s not modified) then you don’t need to do
  2. anything. The default render checks for this using the parameters
  3. used in the previous call to stale? and will automatically send a
  4. :not_modified. So that’s it, you’re done.
    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:

class ProductsController < ApplicationController

  1. This will automatically send back a :not_modified if the request is fresh,
  2. 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 => @article end

end

Advanced Caching

Along with the built-in mechanisms outlined above, a number of excellent
plugins exist to help with finer grained control over caching. These include
Chris Wanstrath’s excellent cache_fu plugin (more info here:
http://errtheblog.com/posts/57-kickin-ass-w-cachefu) and Evan Weaver’s
interlock plugin (more info here:
http://blog.evanweaver.com/articles/2007/12/13/better-rails-caching/). Both
of these plugins play nice with memcached and are a must-see for anyone
seriously considering optimizing their caching needs.

Changelog
Lighthouse ticket

February 22, 2009: Beefed up the section on cache_stores
December 27, 2008: Typo fixes
November 23, 2008: Incremental updates with various suggested changes and formatting cleanup
September 15, 2008: Initial version by Aditya Chadha

@@ -309,14 +309,14 @@ fragment caches. Page caches are always stored on disk.
Rails 2.1 and above provide ActiveSupport::Cache::Store which can be used to
cache strings. Some cache store implementations, like MemoryStore, are able to
-cache arbitrary Ruby objects, but dont count on every cache store to be able
+cache arbitrary Ruby objects, but don't count on every cache store to be able
to do that.
The default cache stores provided include:
1) ActiveSupport::Cache::MemoryStore: A cache store implementation which stores
-everything into memory in the same process. If youre running multiple Ruby on
-Rails server processes (which is the case if youre using mongrel_cluster or
+everything into memory in the same process. If you're running multiple Ruby on
+Rails server processes (which is the case if you're using mongrel_cluster or
Phusion Passenger), then this means that your Rails server process instances
won‘t be able to share cache data with each other. If your application never
performs manual cache item expiry (e.g. when you‘re using generational cache
@@ -368,23 +368,24 @@ Special features:
It also accepts a hash of additional options:
- * :namespace - specifies a string that will automatically be prepended to keys when accessing the memcached store.
- * :readonly - a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
- * :multithread - a boolean value that adds thread safety to read/write operations - it is unlikely youll need to use this option as the Rails threadsafe! method offers the same functionality.
+ * +:namespace+- specifies a string that will automatically be prepended to keys when accessing the memcached store.
+ * +:readonly+- a boolean value that when set to true will make the store read-only, with an error raised on any attempt to write.
+ * +:multithread+ - a boolean value that adds thread safety to read/write operations - it is unlikely you'll need to use this option as the Rails threadsafe! method offers the same functionality.
The read and write methods of the MemCacheStore accept an options hash too.
-When reading you can specify :raw => true to prevent the object being marshaled
+When reading you can specify +:raw => true+ to prevent the object being
+marshaled
(by default this is false which means the raw value in the cache is passed to
Marshal.load before being returned to you.)
-When writing to the cache it is also possible to specify :raw => true means the
-value is not passed to Marshal.dump before being stored in the cache (by
+When writing to the cache it is also possible to specify +:raw => true+ means
+the value is not passed to Marshal.dump before being stored in the cache (by
default this is false).
-The write method also accepts an :unless_exist flag which determines whether
+The write method also accepts an +:unless_exist+ flag which determines whether
the memcached add (when true) or set (when false) method is used to store the
-item in the cache and an :expires_in option that specifies the time-to-live for
-the cached item in seconds.
+item in the cache and an +:expires_in+ option that specifies the time-to-live
+for the cached item in seconds.
<ruby>
@@ -442,7 +443,7 @@ identifier (etag) or last modified since timestamp matches the server’s versio
then the server only needs to send back an empty response with a not modified
status.
-It is the servers (i.e. our) responsibility to look for a last modified
+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:
@@ -468,8 +469,8 @@ class ProductsController < ApplicationController
end
</ruby>
-If you dont have any special response processing and are using the default
-rendering mechanism (i.e. youre not using respond_to or calling render
+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>

0 comments on commit 77aa8a6

Please sign in to comment.