Module: RestApi::Cacheable::ClassMethods
- Defined in:
- app/models/rest_api/cacheable.rb
Instance Method Summary collapse
-
#cached ⇒ Object
Return an equivalent to this class that will may cache the defined results.
Instance Method Details
#cached ⇒ Object
Return an equivalent to this class that will may cache the defined results
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'app/models/rest_api/cacheable.rb', line 15 def cached class_opts = if @cacheable self else parent = self Class.new(self) do #FIXME: prone to breaks, needs to be cleaner self.element_name = parent.element_name @cacheable = true @cache_opts = parent. def self.name superclass.name end def to_partial_path self.class.superclass._to_partial_path end eigenclass = (class << self; self; end) class_opts[:caches].each_pair do |m, opts| name = "#{m}_without_caching".to_sym opts ||= {} #puts "define method #{m} #{name}" eigenclass.class_eval do define_method m do |*args, &blk| key = cache_key_for(m, args) result = begin Rails.cache.fetch(key, class_opts.merge(opts)) do parent.send(m, *args, &blk).tap do |result| opts[:before].call(result) if opts[:before] end end rescue ArgumentError, TypeError => e Rails.logger.warn e parent.send(m, *args, &blk) end opts[:after].call(result) if opts[:after] result end end end end end end |