Module: Methodsolver

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

Constant Summary collapse

BLACKLIST =
[:cycle]
VERSION =
"0.0.2"

Class Method Summary collapse

Class Method Details

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

def self.call(&block)
  raise ArgumentError, 'no block given' unless block_given?
  begin
    Object.class_eval('def method_missing(name, *args); throw :method_missing, [self, name]; end')
    method_missing = catch :method_missing do block.call; nil end
  ensure
    Object.class_eval('remove_method :method_missing')
  end
  raise ArgumentError, 'no missing method found' unless method_missing
  object, message = method_missing
  found = methods_for(object).select do |each|
    begin
      object.class.class_eval("alias #{message.inspect} #{each.inspect}")
      true === block.call
    rescue
      false
    ensure
      object.class.class_eval("remove_method #{message.inspect}")
    end
  end
  return object, found
end

.methods_for(object) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/methodsolver.rb', line 31

def self.methods_for(object)
  object.class.ancestors
    .take_while { |a| Object != a }
    .flat_map { |a| a.instance_methods(all = false) }
    .concat(%w(
      ! !=  == !~  <=> ===  =~ class eql? equal?
      instance_of? is_a? kind_of? hash nil? to_s
    ))
    .map(&:to_sym)
    .uniq
    .- BLACKLIST
end