Caching

merb-cache plugin is part of the merb-more package

Much of this info compiled from merb-cache rdoc—contribute!!

merb-cache currently supports: Implemented cache stores:

Example configuration


  Merb::Plugins.config[:merb_cache] = {
    :cache_html_directory => Merb.dir_for(:public),

    #:store => "database",
    #:table_name => "merb_cache",

    #:disable => "development", # disable merb-cache in development
    #:disable => true, # disable merb-cache in all environments

    :store => "file",
    :cache_directory => Merb.root_path("tmp/cache"),

    #:store => "memcache",
    #:host => "127.0.0.1:11211",
    #:namespace => "merb_cache",
    #:no_tracking => "false",

    #:store => "memory",
    # store could be: file, memcache, memory, database, dummy, ...
  }

Example Code

controller


  class Users < Merb::Controller
    cache_page :list
    # this will cache the action in public/cache/list.html
    # by default or to whatever you pointed :cache_html_directory
    # to in plugin configuration
    # this cache entry will never expire (no expiration provided)
    # for permanent caching you could set your lighty/nginx so as to handle
    # the .html file directly
    # for multiple page caching:
    # cache_pages :archives, [:list, 5]

    cache_action :show, 10
    # this will cache the action using the cache store
    # this cache entry will expire in 10 minutes
    # for multiple action caching:
    # cache_actions :archives, [:list, 5], :some_action

    # example of persisted entities caching using some keys convention
    def list
      unless @users = cache_get("active_users")
        @users = User.all(:active => true)
        cache_set("active_users", @users)
        # object caching can be used to avoid pulling huge amounts of data
        # from the database.
        # you could have called cache_set with an expiration time as well:
        # cache_set("active_users", @users, 10)
      end
      render
    end

    def create
      # do validation and creation...

      expire_page(:list)
      render
    end

    def update
      # do update...
      expire_action(:action => "archives", :controller => "users")
    end

    def destroy
      # destroy object...
      expire("active_users")
      # see fragment caching examples above
      expire("user_archives")
      # redirect
    end

    def archives
      @archives = User.archives unless cached?("users_archives")
      render
    end

    def index
      render
    end
  end

views/users/index.html.erb


  <!-- this entry will expire in 10 minutes -->
  <%- cache "online_users_count", 10 do %>
   <div>some expensive queries or calculations</div>
  <% end -%>

views/users/archive.html.erb


  <%- cache "users_archives" do %>
   <div>cache invalidated somewhere in controller when necessary</div>
  <% end -%>

Edit Page | History | Version: