Module: Detach::Types

Defined in:
lib/detach.rb

Overview

The Detach::Types module is inserted as a parent of the class which includes the Detach mixin. This module handles inspection and aliasing of instance methods as they are added.

Detach::Types does not need to be extended directly.

Constant Summary collapse

@@types =
nil

Instance Method Summary collapse

Instance Method Details

#[](*types) ⇒ Object

Provides list of type names to decorator.



111
112
113
# File 'lib/detach.rb', line 111

def [](*types)
  @@types = types.flatten
end

#method_added(name) ⇒ Object

Provides load-time method aliasing.

All methods added to a class which are decorated as taking specified types are aliased in a form known and searched at run-time.

Raises:

  • (ArgumentError)


118
119
120
121
122
123
124
125
126
127
128
129
130
131
# File 'lib/detach.rb', line 118

def method_added(name)
  return unless @@types

  # query the parameter info for the method just added
  p = instance_method(name).parameters.map &:first
  raise ArgumentError.new('type and parameter mismatch') unless p.size == @@types.size

  # encode our defined types with parameter info into a new name and remove the original
  n = (name.to_s + '(' + p.zip(@@types).collect {|p,t| "#{p}-#{t}" }.join(',') + ')').to_sym
  @@types = nil

  alias_method n, name unless method_defined?(n)
  define_method(name) {|*args, &block| method_missing(name, *args, &block)}
end

#takingObject

Decorator method for defining argument signature.

Example:

taking['String']
def foo(a)
end


107
108
109
# File 'lib/detach.rb', line 107

def taking
  self
end