Skip to content

Instantly share code, notes, and snippets.

@guilleiguaran
Created August 4, 2011 17:02
Show Gist options
  • Save guilleiguaran/1125636 to your computer and use it in GitHub Desktop.
Save guilleiguaran/1125636 to your computer and use it in GitHub Desktop.
Expiring values with Ohm
module Ohm
module Expiring
def self.included(base)
base.send(:extend, ClassMethods)
end
module ClassMethods
def expire(ttl)
@@expire = ttl.to_i
end
def create(*args)
object = super(*args)
if !object.new? && @@expire
Ohm.redis.expire(object.key, @@expire)
Ohm.redis.expire("#{object.key}:_indices", @@expire)
end
object
end
end
end
end
require 'ohm/expiring'
class Measurement < Ohm::Model
include Ohm::Expiring
attribute :value
expire 1.minute
end
jruby-1.6.3 :003 > Measurement.create(:value => 1)
=> #<Measurement:11 value=1>
jruby-1.6.3 :004 > Measurement[11]
=> #<Measurement:11 value="1">
#### wait a minute ####
jruby-1.6.3 :005 > Measurement[11]
=> #<Measurement:11 value=nil>
@abevoelker
Copy link

Very nice! Is there a way to make the entire model expire (instead of every value), i.e. return nil on the last Measurement[11] call in the console output example?

@szymon-jez
Copy link

@abevoelker You can give the Ohm Expire gem a try https://github.com/joseairosa/ohm-expire

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment