Last active
December 24, 2015 00:09
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Wolrd < ActiveRecord::Base | |
cache_method :get_population_count do | |
# Intense stuff... | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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