Skip to content

Instantly share code, notes, and snippets.

@sgonyea
Created January 20, 2012 22:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sgonyea/1649964 to your computer and use it in GitHub Desktop.
Save sgonyea/1649964 to your computer and use it in GitHub Desktop.
Mixin to add support for expiring keys within Ohm
module Ohm
module Expiring
def self.included(base)
base.instance_exec {
include InstanceMethods
extend ClassMethods
}
end
module InstanceMethods
attr_accessor :expiration
def initialize(*args)
super(*args)
self.expiration ||= self.class.expiration
end
def create(*args)
super(*args)
set_expiration if valid? and expires?
end
def set_expiration
Ohm.redis.expire(key, expiration)
Ohm.redis.expire("#{key}:_indices", expiration)
end
def expires?
Integer === expiration
end
end
module ClassMethods
def expiration
@expires ||= nil
end
def expires(ttl)
@expires = ttl.to_i
end
alias :expire :expires
end
end
end
require 'spec_helper'
describe Ohm::Expiring do
class ExpiringModel < Ohm::Model
include Ohm::Expiring
attribute :value
expires 1.minute
end
describe '#initialize' do
it "should set the expiration" do
em = ExpiringModel.new
em.expiration.should == 1.minute.to_i
end
end
context 'When being persisted' do
it "should have an expiration > 0" do
em = ExpiringModel.create(:value => "Foo")
Ohm.redis.ttl(em.key).should be > 0
end
it "should have an expiration <= 1 minute" do
em = ExpiringModel.create(:value => "Foo")
Ohm.redis.ttl(em.key).should be <= 1.minute.to_i
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment