Module: MaybeYouMeant::ObjectExtentions::InstanceMethods

Defined in:
lib/maybeyoumeant/object_extensions.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object

Calls a nearby method if one is found. If no nearby method is found the original method_missing is called, which raises a NoMethodError.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/maybeyoumeant/object_extensions.rb', line 26

def method_missing(method, *args, &block)
  # Don't handle methods on the ignore list.
  return super if IGNORE_LIST.include?(method)

  nearby = nearby_method(method)

  return super unless MaybeYouMeant::Config.call_nearby && nearby

  if MaybeYouMeant::Config.ask_user
    print MaybeYouMeant::ObjectExtentions.user_confirmation(nearby)
    choice = gets
    return super if !choice || choice =~ /^n/i
  end

  MaybeYouMeant.tweak_history(method, nearby)

  send(nearby, *args, &block)
end

Instance Method Details

#nearby_method(name) ⇒ Object

Returns the closest matching method to methods already defined on the object.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/maybeyoumeant/object_extensions.rb', line 46

def nearby_method(name)
  max_distance = 2
  max_distance = 1 if name.to_s.length <= 3

  distance = {}
  nearby_methods = self.methods.select do |method|
    d = MaybeYouMeant::Levenshtein.distance(name.to_s, method.to_s, max_distance + 1)
    distance[method] = d if d <= max_distance
    d <= max_distance
  end
  return nil if nearby_methods.empty?
  nearby_methods.sort! do |method, other|
    distance[method] <=> distance[other]
  end
  nearby_methods[0]
end