Skip to content

Instantly share code, notes, and snippets.

@alfanick
Created September 18, 2012 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save alfanick/3742161 to your computer and use it in GitHub Desktop.
Save alfanick/3742161 to your computer and use it in GitHub Desktop.
Simple Haml content caching
# Amadeusz Juskowiak <amadeusz@amanointeractive.com> 2012 - MIT License
# 1. Put inside helpers do .. end
# 2. Set CACHE_DIR to somewhere writable and private (like CACHE_DIR=File.dirname(__FILE__) + '/tmp'
# 3. Use it! You can use fragment_expire to remove cache with given name.
#
# Example:
# %h1 foo
# = cache_fragment(:report, 300) do
# - data = get_data_slowly
# %h2 my super extensive table generation
#
# In example above, block will be cached for 300 seconds.
#
# Remember:
# Cache entries are identified only by their name - so no matter where you access your
# :report it will be the same report! This means you have to be careful with sensible data.
# If you want cache different data in same view use something like
# "#{@user._id}/#{@basket._id}" as a key.
#
# Have fun!
def cache_fragment(name, expires, &haml)
filename = CACHE_DIR + '/' + name.to_s + '.cache'
now = Time.now
result = 'Cache Error!'
needs_caching = true
if File.file? filename
if (((now - File.mtime(filename)).to_i) >= expires)
needs_caching = true
else
needs_caching = false
result = File.read(filename)
end
end
if needs_caching
f = File.new(filename, 'w')
f.write(result = capture_haml(&haml))
f.close
end
result
end
def fragment_expire(name)
filename = CACHE_DIR + '/' + name.to_s + '.cache'
if File.file? filename
File.unlink filename rescue (return false)
return true
end
false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment