Sha256: d3bbd74612b808503009b92686f70f17fce523a20cc5b113dcb0fbddbdf77ef3

Contents?: true

Size: 799 Bytes

Versions: 1

Compression:

Stored size: 799 Bytes

Contents

require 'thread'
require 'synchronizable/version'

# Synchronizable is intended to be injected into objects via Object#extend.
# After Object#extend(Synchronizable) is performed, the object's original
# methods will become synchronized via a per-instance lock.
module Synchronizable
  IGNORABLE_METHOD_OWNERS = [Object, Kernel, BasicObject]

  def self.extended(obj)
    # immediately create object-level lock
    obj.send(:__lock)

    # redefine all user-defined methods to utilize lock
    obj.methods.each do |m|
      next if IGNORABLE_METHOD_OWNERS.include?(obj.method(m).owner)
      obj.define_singleton_method(m) do |*args, &block|
        __lock.synchronize do
          super(*args, &block)
        end
      end
    end
  end

  private

  def __lock
    @__lock ||= Mutex.new
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
synchronizable-0.0.1 lib/synchronizable.rb