Skip to content
This repository
tree: b185d157fe
Fetching contributors…

Cannot retrieve contributors at this time

file 36 lines (35 sloc) 1.5 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
class Module
  # Synchronize access around a method, delegating synchronization to a
  # particular mutex. A mutex (either a Mutex, or any object that responds to
  # #synchronize and yields to a block) must be provided as a final :with option.
  # The :with option should be a symbol or string, and can represent a method,
  # constant, or instance or class variable.
  # Example:
  # class SharedCache
  # @@lock = Mutex.new
  # def expire
  # ...
  # end
  # synchronize :expire, :with => :@@lock
  # end
  def synchronize(*methods)
    options = methods.extract_options!
    unless options.is_a?(Hash) && with = options[:with]
      raise ArgumentError, "Synchronization needs a mutex. Supply an options hash with a :with key as the last argument (e.g. synchronize :hello, :with => :@mutex)."
    end

    methods.each do |method|
      aliased_method, punctuation = method.to_s.sub(/([?!=])$/, ''), $1
      if instance_methods.include?("#{aliased_method}_without_synchronization#{punctuation}")
        raise ArgumentError, "#{method} is already synchronized. Double synchronization is not currently supported."
      end
      module_eval(<<-EOS, __FILE__, __LINE__)
def #{aliased_method}_with_synchronization#{punctuation}(*args, &block)
#{with}.synchronize do
#{aliased_method}_without_synchronization#{punctuation}(*args,&block)
end
end
EOS
      alias_method_chain method, :synchronization
    end
  end
end
Something went wrong with that request. Please try again.