module Once

Usage:

  1. Connect to redis: Once.redis = Redis.new(…)

If you don't specify the redis connection, we will assume the presence of a $redis global

  1. Use to wrap a call that you want done uniquely

Once.do(name: "sending_email", params: { email: "foo@bar.com" }, within: 1.hour) do
  .. stuff that should happen only once ..
end

The combination of the name and params makes the check unique. So typically it would be the command you're executing, plus the params to that command

Constants

DEFAULT_TIME
VERSION

Public Class Methods

do(name:, params:, within: DEFAULT_TIME, &block) click to toggle source

Checks the given params to see if this is a unique string If we've seen it within the expiry period (default: 1.hour), then we will not execute the block

name: The name of the check, used as a namespace params: The params that will control whether or not the body executes

# File lib/once.rb, line 36
def do(name:, params:, within: DEFAULT_TIME, &block)
  hash = Digest::MD5.hexdigest(params.inspect)
  redis_key = "uniquecheck:#{name}:#{hash}"

  if redis.set(redis_key, true, ex: within, nx: true)
    begin
      block.call
    rescue
      redis.expire(redis_key, 0)
      raise
    end
  end
end
redis() click to toggle source
# File lib/once.rb, line 22
def redis
  @redis || $redis
end
redis=(redis) click to toggle source
# File lib/once.rb, line 26
def redis=(redis)
  @redis = redis
end