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.



9
10
11
12
13
14
15
# File 'lib/maybeyoumeant/object_extensions.rb', line 9

def method_missing(method, *args, &block)
  nearby = nearby_method(method)
  # MaybeYouMeant.log { "Maybe you meant to call #{nearby}?" } if nearby
  return super unless MaybeYouMeant::Config.call_nearby && nearby
  MaybeYouMeant.tweak_history(method, nearby)
  return send(nearby, *args, &block)
end

Instance Method Details

#nearby_method(name) ⇒ Object

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/maybeyoumeant/object_extensions.rb', line 18

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)
    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