File: bind.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (38 lines) | stat: -rw-r--r-- 854 bytes parent folder | download
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
37
38
class Proc

  # Bind a Proc to an object returning a Method.
  #
  # The block's #to_s method (same as #inspect) is
  # used for the temporary method label defined in
  # the Object class.
  #
  #   NOTE: This dynamically loads thread.so if used.
  #   NOTE: Not so sure it is thread critical anymore.

  def bind(object=nil)
    require 'thread'

    object = object || eval("self", self)
    block  = self
    store  = Object

    begin
      old, Thread.critical = Thread.critical, true
      @n ||= 0; @n += 1
      name = "_bind_#{@n}#{block.object_id}"
      store.module_eval do
        define_method name, &block
      end
      meth = object.method(name)
    ensure
      store.module_eval do
        remove_method name #rescue nil
        #undef_method name #rescue nil
      end
      Thread.critical = old
    end

    return meth
  end

end