Module: Redis::Mutex::Macro::ClassMethods

Defined in:
lib/redis/mutex/macro.rb

Instance Method Summary collapse

Instance Method Details

#auto_mutex(target, options = {}) ⇒ Object



15
16
17
# File 'lib/redis/mutex/macro.rb', line 15

def auto_mutex(target, options={})
  self.auto_mutex_methods[target] = options
end

#method_added(target) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/redis/mutex/macro.rb', line 19

def method_added(target)
  return if target.to_s =~ /^auto_mutex_methods/
  return unless self.auto_mutex_methods[target]
  without_method  = "#{target}_without_auto_mutex"
  with_method     = "#{target}_with_auto_mutex"
  after_method    = "#{target}_after_failure"
  return if method_defined?(without_method)
  options = self.auto_mutex_methods[target]

  if options[:after_failure].is_a?(Proc)
    define_method(after_method, &options[:after_failure])
  end

  define_method(with_method) do |*args|
    key = self.class.name << '#' << target.to_s

    begin
      Redis::Mutex.with_lock(key, options) do
        send(without_method, *args)
      end
    rescue Redis::Mutex::LockError
      send(after_method, *args) if respond_to?(after_method)
    end
  end

  alias_method without_method, target
  alias_method target, with_method
end