Skip to content

Instantly share code, notes, and snippets.

@iain
Created March 8, 2013 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iain/5113170 to your computer and use it in GitHub Desktop.
Save iain/5113170 to your computer and use it in GitHub Desktop.
Example of using eval in a safe way to do something cool and useful.
module CacheHelper
# Caches the block given, and prefixes the cache key with the name of the controller and action.
#
# In JBuilder, the +json+ object is a local variable and to access it, we must pass it to this method.
# Fortunately, this method requires a block, from which we can get the binding, and use that to gain
# access to the json variable. Now we don't have to pass the json variable anymore.
def json_cache(keys, &block)
json = eval("json", block.send(:binding))
json.cache! [params[:controller], params[:action]] + Array.wrap(keys), &block
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment