Skip to content

Instantly share code, notes, and snippets.

@novohispano
Created February 18, 2015 11:45
Show Gist options
  • Save novohispano/133101beb63fbd6dcd09 to your computer and use it in GitHub Desktop.
Save novohispano/133101beb63fbd6dcd09 to your computer and use it in GitHub Desktop.
Caching in Rails
module ApplicationHelper
def cache_key_for(model)
prefix = model.to_s.downcase.pluralize
count = model.count
max_updated_at = model.maximum(:updated_at).try(:utc).try(:to_s, :number)
"#{prefix}/all-#{count}-#{max_updated_at}"
end
end
module CacheInvalidator
extend ActiveSupport::Concern
included do
after_create :invalidate_cache
after_update :invalidate_cache
after_destroy :invalidate_cache
def invalidate_cache
Rails.cache.clear
end
end
end
<% cache(cache_key_for(Item)) do %>
<div class="container">
<div class="row">
<div class="col-sm-12">
<h1><%= @items.count %> Items</h1>
</div>
</div>
<div class="row"></div>>
<% @items.each do |item| %>
<div class="col-sm-3">
<% cache(item) do %>
<h5><%= item.name %></h5>
<%= link_to(image_tag(item.image_url), item_path(item)) %>
<p><%= item.description %></p>
<% end %>
</div>
<% end %>
</div>
<% end %>
class Item < ActiveRecord::Base
# include CacheInvalidator
# include ManyToManyAssociationsUpdater
has_many :order_items
has_many :orders, through: :order_items
after_create :update_orders
after_update :update_orders
after_destroy :update_orders
def update_orders
orders.each do |order|
order.updated_at = Time.now
order.save
end
end
end
module ManyToManyAssociationsUpdater
extend ActiveSupport::Concern
included do
after_create :update_associations
after_update :update_associations
after_destroy :update_associations
def associations
self.class.reflect_on_all_associations(:has_many).map(&:name)
end
def update_associations
associations.each { |association| update_association(association) }
end
def update_association(association)
send(association).each { |record| record.update_attributes(updated_at: Time.now) }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment