File: prepend.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 (52 lines) | stat: -rw-r--r-- 879 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# = Prepend
#
# This is a module prepend system, which provides an elegant
# way to prepend code to the class hierarchy rather then append
# it (a la #include).
#
#   class C
#     def f
#       "f"
#     end
#   end
#
#   module M
#     def f
#       '{' + super + '}'
#     end
#   end
#
#   class C
#     prepend M
#   end
#
#   c = C.new
#   c.f  #=> "{f}"
#
# This works by overriding Class#new so that all prepended modules
# extend new instances of the class upon instantiation.
#
# If needed the original #new method has been aliased as #init.

class Class

  #
  def prepend(*mods)
    @prepend ||= []
    @prepend.concat(mods)
    @prepend
  end

  alias_method :init, :new

  def new(*args, &blk)
    o = allocate
    prepend.each do |mod|
      o.extend(mod)
    end
    o.__send__(:initialize, *args, &blk) #if private_method_defined?(:initialize)
    o
  end

end