Module: Tins::Deflect

Extended by:
ThreadLocal
Included in:
Object
Defined in:
lib/tins/dslkit.rb

Overview

See examples/recipe.rb and examples/recipe2.rb how this works at the moment.

Defined Under Namespace

Classes: DeflectError, Deflector, DeflectorCollection

Constant Summary collapse

@@sync =
Sync.new

Class Method Summary collapse

Instance Method Summary collapse

Methods included from ThreadLocal

instance_thread_local, thread_local

Class Method Details

.deflect?(from, id) ⇒ Boolean

Return true if method id is deflected from class from, otherwise return false.

Returns:

  • (Boolean)


384
385
386
# File 'lib/tins/dslkit.rb', line 384

def self.deflect?(from, id)
  Deflect.deflecting && Deflect.deflecting.member?(from, id)
end

Instance Method Details

#deflect(from, id, deflector) ⇒ Object

Start deflecting method calls named id to the from class using the Deflector instance deflector. After that yield to the given block and stop deflecting again.



397
398
399
400
401
402
403
404
405
406
# File 'lib/tins/dslkit.rb', line 397

def deflect(from, id, deflector)
  @@sync.synchronize do
    begin
      deflect_start(from, id, deflector)
      yield
    ensure
      deflect_stop(from, id)
    end
  end
end

#deflect?(from, id) ⇒ Boolean

Return true if method id is deflected from class from, otherwise return false.

Returns:

  • (Boolean)


390
391
392
# File 'lib/tins/dslkit.rb', line 390

def deflect?(from, id)
  Deflect.deflect?(from, id)
end

#deflect_start(from, id, deflector) ⇒ Object

Start deflecting method calls named id to the from class using the Deflector instance deflector.



364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# File 'lib/tins/dslkit.rb', line 364

def deflect_start(from, id, deflector)
  @@sync.synchronize do
    Deflect.deflecting ||= DeflectorCollection.new
    Deflect.deflecting.member?(from, id) and
      raise DeflectError, "#{from}##{id} is already deflected"
    Deflect.deflecting.add(from, id, deflector)
    from.class_eval do
      define_method(id) do |*args|
        if Deflect.deflecting and d = Deflect.deflecting.find(self.class, id)
          d.call(self, id, *args)
        else
          super(*args)
        end
      end
    end
  end
end

#deflect_stop(from, id) ⇒ Object

Stop deflection method calls named id to class from.



409
410
411
412
413
414
415
# File 'lib/tins/dslkit.rb', line 409

def deflect_stop(from, id)
  @@sync.synchronize do
    Deflect.deflecting.delete(from, id) or
      raise DeflectError, "#{from}##{id} is not deflected from"
    from.instance_eval { remove_method id }
  end
end