Created
January 20, 2012 22:23
-
-
Save sgonyea/1649964 to your computer and use it in GitHub Desktop.
Mixin to add support for expiring keys within 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.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 |
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 '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