Module: AttrCallback::Util

Defined in:
lib/attr_callback.rb

Constant Summary collapse

NoopProc =
Proc.new{}

Class Method Summary collapse

Class Method Details

.define_callback_on_class(klass, name, options = {}) ⇒ 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
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/attr_callback.rb', line 19

def define_callback_on_class(klass, name, options={})
  name = name.to_sym
  locking = options[:lock].nil? ? true : options[:lock]
  noop = options[:noop].nil? ? true : options[:noop]

  # Define the setter.  If the user specified :lock=>true, then the
  # setter will synchronize on @name_lock; otherwise, we just use
  # the standard attr_writer.
  if locking
    klass.__send__(:define_method, "#{name}=") do |value|
      AttrCallback::Util.get_or_create_mutex(self, name).synchronize {
        instance_variable_set("@#{name}", value)
      }
    end
  else
    klass.__send__(:attr_writer, name)
  end

  # Define the getter.  If the user specified :lock=>true, then the
  # getter will synchronize on @name_lock; otherwise, it won't.
  klass.__send__(:define_method, name) do |*args, &block|
    raise ArgumentError, "wrong number of arguments (#{args.length} for 0)" unless args.empty?

    if block.nil?
      if locking
        callback = AttrCallback::Util.get_or_create_mutex(self, name).synchronize { instance_variable_get("@#{name}") }
      else
        callback = instance_variable_get("@#{name}")
      end
      if noop and callback.nil?
        NoopProc
      else
        callback
      end
    else
      __send__("#{name}=", block)
    end
  end
end

.get_or_create_mutex(obj, name) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/attr_callback.rb', line 10

def get_or_create_mutex(obj, name)
  mutex = obj.instance_variable_get("@#{name}_lock")
  if mutex.nil?
    obj.instance_variable_set("@#{name}_lock", Mutex.new)
  else
    mutex
  end
end