Created
August 4, 2011 17:02
-
-
Save guilleiguaran/1125636 to your computer and use it in GitHub Desktop.
Expiring values with Ohm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'ohm/expiring' | |
class Measurement < Ohm::Model | |
include Ohm::Expiring | |
attribute :value | |
expire 1.minute | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice! Is there a way to make the entire model expire (instead of every value), i.e. return
nil
on the lastMeasurement[11]
call in the console output example?