Module: CacheableAttr

Defined in:
lib/cacheable_attr.rb,
lib/cacheable_attr/version.rb

Constant Summary collapse

VERSION =
'0.1.0'

Instance Method Summary collapse

Instance Method Details

#cacheable_attr(*attributes) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/cacheable_attr.rb', line 10

def cacheable_attr(*attributes)
  opts = { ttl: 60 }
  opts = opts.merge(attributes.pop) if attributes.last.is_a?(Hash)
  
  attributes.each do |attribute|
    define_method attribute do
      if !instance_variable_defined?("@#{attribute}_updated_at") || (opts[:ttl] != nil && Time.now >= instance_variable_get("@#{attribute}_updated_at") + opts[:ttl])
        value = send("#{attribute}_uncached")
        instance_variable_set("@#{attribute}", value)
        instance_variable_set("@#{attribute}_updated_at", Time.now)
      end
      
      instance_variable_get("@#{attribute}")
    end
  end
end