Skip to content

Instantly share code, notes, and snippets.

@reinh
Created May 18, 2010 18:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save reinh/405328 to your computer and use it in GitHub Desktop.
Save reinh/405328 to your computer and use it in GitHub Desktop.
class MyView < Mustache
def cache_by_user_id
lambda do |text|
cache_key = "user:#{current_user.id}"
if value = $cache.get(cache_key)
value
else
rendered = render(text)
$cache.set(cache_key, rendered)
rendered
end
end
end
end
# assumes $cache.set returns the value that is set, which seems sensible.
def $cache.fetch(key)
get(key) || set(key, yield)
end
class MyView < Mustache
def cache_by_user_id
lambda { |text| $cache.fetch("user:#{current_user.id}"){ render(text) } }
end
end
@reinh
Copy link
Author

reinh commented May 18, 2010

if $cache had a Hashlike interface, you could also do:

def cache_by_user_id
  lambda { |text| $cache["user:#{current_user.id}"] ||= render(text) }
end

The ||= short-circuits, preventing render(text) from being called if there's a cache hit.

Ruby is so expressive for this sort of problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment