Module: Ziggy::ClassMethods

Defined in:
lib/ziggy.rb

Instance Method Summary collapse

Instance Method Details

#build_key(instance, method, args) ⇒ Object



62
63
64
65
66
67
# File 'lib/ziggy.rb', line 62

def build_key(instance, method, args)
  invocation_key = "#{method}#{ args.collect{ |a| a.to_s } }"
  keygen = @keygens[method]
  differentiator = (keygen.call(instance) unless keygen.nil?) || ""
  differentiator + invocation_key
end

#cached(*cachable_methods, &block) ⇒ Object



23
24
25
26
27
28
29
30
31
# File 'lib/ziggy.rb', line 23

def cached(*cachable_methods, &block)
  return unless Ziggy::active
  opts = (cachable_methods.pop if cachable_methods.last.kind_of? Hash) || {}
  @should_be_cached += cachable_methods
  cachable_methods.each do |m| 
    @keygens[m] = block
    @expire_after[m] = opts[:expire_after] || 2.5.minutes
  end
end

#cached?(method) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/ziggy.rb', line 37

def cached?(method)
  @cached.include? method
end

#expire_after(method) ⇒ Object



58
59
60
# File 'lib/ziggy.rb', line 58

def expire_after(method)
  @expire_after[method]
end

#method_added(method) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/ziggy.rb', line 41

def method_added(method)
  return unless should_be_cached?(method) && !cached?(method)
  @cached << method
  method_without_cache = "#{method}_without_cache".to_sym
  class_eval do 
    alias_method method_without_cache, method 
    define_method(method) do |*args|
      key = self.class.build_key(self, method, args)
      return Rails.cache.read(key) if Rails.cache.exist?(key)
      result = send(method_without_cache, *args)
      Rails.cache.write(key, result, :expires_in => self.class.expire_after(method))
      result
    end
  end
  logger.debug "Caching added to #{self}.#{method}"
end

#should_be_cached?(method) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/ziggy.rb', line 33

def should_be_cached?(method)
  @should_be_cached.include? method
end