6 - Guest User Record #393

(12/8/15)

Conditional validiations

Update all the associations when the guest user creates an account

Can not destroy the guest user since this will also destroy the associations
Create rake task to destroy old accounts not upgraded after a week
Set task as cron job using 'Whenever' gem

7 - Fragment Caching #90

(24/8/15)

Add 'cache' block to view file (with string so that it used by all URL's using view)

<% cache 'recent_products' do %>
...
<% end %>

Perform DB call within 'cache' block (so that it is not repeated unnecessarily)

Move 'find' into view via creating a method on the Model eg Product.find_recent

class Product < ActiveRecord::Base
  def self.find_recent
    find(:all, :order => 'released_at desc', :limit => 10)
  end
end

Flush cache

Extracted to separate gem in Rails 4 (www.rubytutorial.io/page-caching-with-rails4/)

Sweeper

class ModelSweeper < ActionController::Caching::Sweeper
  observer Model

  def after_save(model)
    expire_cache(model)
  end

  def after_destroy(model)
    expire_cache(model)
  end

  def expire_cache(model)
    expire_page
  end
end

When model is State then ModelSweeper would be StateSweeper in file called 'state_sweeper.rb'
Then:
class StatesController < ApplicationController
  cache_sweeper :state_sweeper, :only => [:create, :update, :destroy]
  ...
end

Create 'app/sweepers'

Tell rails to load files placed there:

config/environment.rb
  config.load_paths << "#{RAILS_ROOT}/app/sweepers"

8 - Cache Digests #387

(24/8/15)

(6/2/16)…interesting…

Add cache block to partial view

<% cache project do %>
  ...
<% end %>

Cache expires when task changes by adding to Task model

belongs_to :project, touch: true

/config/development.rb

config.action_controller.perform_caching = true

If the HTML in the cached view is changed then a version number is needed in the cache key

<% cache ['v1', project] do %>
  ...
<% end %>

If both Task and Project views are cached with version number then BOTH VERSION NUMBERS NEED TO BE CHANGED

Cache Digests gem

Means not have to manually update version number

Now part of Rails 4

Doesn't read template file on every request so need to restart server

Rake task to check nested dependencies

$ rake cache_digests:nested_dependencies TEMPLATE=projects/index

If there is mismatch between Model method name and View template then need to explicitly add 'partial' to render

<% cache project do %>
  ...
  <ul><%= render partial: 'tasks/task', collection: project.incomplete_tasks %></ul>
<% end %>