Skip to content

Instantly share code, notes, and snippets.

@plehoux
Last active December 24, 2015 00:09
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 plehoux/6715247 to your computer and use it in GitHub Desktop.
Save plehoux/6715247 to your computer and use it in GitHub Desktop.
ActiveRecord extension to cache the result of a compute-intensive method inside a store.
module Cachemire
extend ActiveSupport::Concern
module ClassMethods
def cache_method(name, &block)
store_accessor :cache, name
instance_eval do
define_method name, &cache_wrap(&block)
end
end
private
def cache_wrap(&block)
-> do
unless value = super()
value = JSON.dump(instance_eval(&block))
send "#{__method__}=", value
save if persisted?
end
YAML.load value
end
end
end
end
ActiveRecord::Base.send(:include, Cachemire)
class Wolrd < ActiveRecord::Base
cache_method :get_population_count do
# Intense stuff...
end
end
@phildionne
Copy link

Yo voici une autre implémentation possible. C'est n'a pas exactement le même comportement par contre: https://gist.github.com/phildionne/6728341

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