MemCacheStore and FileStore in Ruby on Rails

Posted by Bhushan Ahire | Posted in Rails | Posted on 03-09-2007

0

This allows to expire cached fragments by ttl. Example usage (in views):

<% cache("name", :ttl => 7.days) do %>

  ... some database-heavy stuff ...
<% end %>

Put the following in environment.rb or in lib/.

class ActionController::Caching::Fragments::MemCacheStore
  def write(name, value, options=nil)

    if options.is_a?(Hash) && options.has_key?(:ttl)

      ttl = options[:ttl]
    else
      ttl = 0

    end
    @data.set(name, value, ttl)

  end
end

module ActionView::Helpers::CacheHelper
  def cache(name = {}, options = nil, &block)

    @controller.cache_erb_fragment(block, name, options)
  end

end

class ActionController::Caching::Fragments::UnthreadedFileStore
  def read(name, options = nil)
    if options.is_a?(Hash) && options.has_key?(:ttl)

      ttl = options[:ttl]
    else
      ttl = 0

    end

    fn = real_file_path(name)

    # if cache expired act as if file doesn't exist

    return if ttl > 0 && File.exists?(fn) && (File.mtime(fn) < (Time.now - ttl))

    File.open(fn, 'rb') { |f| f.read } rescue nil

  end
end