Module: Overloadable

Defined in:
lib/platypus/overload.rb

Overview

The Obverloadable mixin allows you to easily overload methods based on method signitures.

Defined Under Namespace

Classes: Signature

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(base) ⇒ Object


7
8
9
10
11
12
13
# File 'lib/platypus/overload.rb', line 7

def self.append_features(base)
  if Module==base
    super(base)
  else
    base.extend(self)
  end
end

Instance Method Details

#method_added(name) ⇒ Object


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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/platypus/overload.rb', line 24

def method_added(name)
  return if $skip

  @overload_stack  ||= []
  @overload_method ||= {}

  signature = @overload_stack.pop

  if !method_defined?("#{name}:origin")
    $skip = true
    if signature
      define_method("#{name}:origin"){|*a| raise ArgumentError }
    else
      alias_method("#{name}:origin", name)
    end
    $skip = false
  end

  if signature
    @overload_module ||= Module.new

    include @overload_module

    signature = Signature[*signature]
    @overload_method[name] ||= []
    @overload_method[name] << signature

    signame = "#{name}:#{signature.key}"

    alias_method(signame, name)

    sigs = @overload_method[name]
    $skip = true
    define_method(name) do |*args|
      #sigs.sort.each do |sig|
      s = sigs.find{ |sig| sig.match?(args) }
      if s
        __send__("#{name}:#{s.key}", *args)
      else
        __send__("#{name}:origin", *args)
      end
    end
    $skip = false
  end

end

#overload(*signature) ⇒ Object Also known as: sig

Setup an overload state.


16
17
18
# File 'lib/platypus/overload.rb', line 16

def overload(*signature)
  (@overload_stack ||= []) << signature
end