Skip to content

Instantly share code, notes, and snippets.

@RyanScottLewis
Created June 25, 2012 05:55
Show Gist options
  • Select an option

  • Save RyanScottLewis/2986896 to your computer and use it in GitHub Desktop.

Select an option

Save RyanScottLewis/2986896 to your computer and use it in GitHub Desktop.
Cacheable attributes
module CacheableAttr
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
end
# ================================================================================= #
# = EXAMPLE ======================================================================= #
# ================================================================================= #
class NumberGenerator
extend CacheableAttr
cacheable_attr :num1, ttl: 3
cacheable_attr :num2, ttl: 0
cacheable_attr :num3, ttl: nil
def num1_uncached
rand(100)
end
def num2_uncached
rand(100)
end
def num3_uncached
rand(100)
end
end
num_gen = NumberGenerator.new
puts "The first number will change every 3 seconds"
puts "The second number will change every single call"
puts "The third number will never change"
puts ""
loop do
puts "[#{Time.now}] #{'%02d' % num_gen.num1} - #{'%02d' % num_gen.num2} - #{'%02d' % num_gen.num3}"
sleep 0.5
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment