Module: Methodsolver

Defined in:
lib/methodsolver.rb,
lib/methodsolver/version.rb

Constant Summary collapse

VERSION =
"0.0.3"

Class Method Summary collapse

Class Method Details

.call(options = {}, &block) ⇒ Object

Raises:

  • (ArgumentError)


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
# File 'lib/methodsolver.rb', line 6

def self.call(options = {}, &block)
  raise ArgumentError, 'no block given' unless block_given?

  # Detect missing method, ie placeholder:

  begin
    Object.class_eval('def method_missing(name, *args); throw :undefined_method, [self, name]; end')
    reciever, placeholder = catch :undefined_method do
      block.call
      raise ArgumentError, 'no missing method found'
    end
  ensure
    Object.class_eval('remove_method :method_missing')
  end

  # Find methods that pass the block:

  results = methods_for(reciever).select do |name|
    method = reciever.method(name) rescue next
    begin
      method.owner.class_eval("alias #{placeholder.inspect} #{name.inspect}")
      true === block.call
    rescue
      false
    ensure
      method.owner.class_eval("remove_method #{placeholder.inspect}")
    end
  end

  # Optionally return a hash with metadata:

  if options[:metadata]
    { reciever: reciever, placeholder: placeholder, results: results }
  else
    results
  end
end