Skip to content

Instantly share code, notes, and snippets.

@leompeters
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leompeters/cf7d1711c00f4a17cd31 to your computer and use it in GitHub Desktop.
Save leompeters/cf7d1711c00f4a17cd31 to your computer and use it in GitHub Desktop.
Action and Fragment caching supported by Rails.
Action and Fragment caching supported by Rails.cache, working like caching in HTML templates:
<!-- @see https://devcenter.heroku.com/articles/caching-strategies#fragment-caching -->
<% cache(product) do %>
<div><%= link_to product, product.name %>: <%= product.price%></div>
<div><%= do_something_comlicated%></div>
<% end %>
<!-- @see https://devcenter.heroku.com/articles/caching-strategies#fragment-caching -->
<%= render :partial => "product", :collection => @products %>
<% cache("top_products", :expires_in => 1.hour) do %>
<div id="topSellingProducts">
<% @recent_product = Product.order("units_sold DESC").limit(20) %>
<%= render :partial => "product", :collection => @recent_products %>
</div>
<% end %>
# @see https://devcenter.heroku.com/articles/caching-strategies#low-level-caching
def Product.out_of_stock
Rails.cache.fetch("out_of_stock_products", :expires_in => 5.minutes) do
Product.all.joins(:inventory).conditions.where("inventory.quantity = 0")
end
end
def competing_price
Rails.cache.fetch("/product/#{id}-#{updated_at}/comp_price", :expires_in => 12.hours) do
Competitor::API.find_price(id)
end
end
# @see https://devcenter.heroku.com/articles/caching-strategies#action-caching
class ProductsController < ActionController
before_filter :authenticate
# @see http://guides.rubyonrails.org/caching_with_rails.html#activesupport-cache-ehcachestore
caches_action :index, expires_in: 60.seconds, unless_exist: true
# caches_action :index
caches_action :show, :layout => false
def index
@products = Product.all
end
def show
@product = Product.find(params[:id])
end
def create
expire_action :action => :index
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment