Created
February 22, 2012 09:08
-
-
Save ckazu/1883509 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module TypoFixer | |
| def self.included(base) | |
| base.class_eval do | |
| alias_method :method_missing_without_fix_typo, :method_missing | |
| alias_method :method_missing, :method_missing_with_fix_typo | |
| end | |
| end | |
| def method_missing_with_fix_typo(name, *args) | |
| if name && method = find_method(name) | |
| $stderr.puts "WARNING: execute `#{name}` as `#{method}` for #{self}" | |
| return send(method, *args) | |
| elsif method = find_method_with_only_one_typo(name) | |
| $stdout.print "WARNING: execute `#{name}` as `#{method}`? [Y/n] " | |
| return send(method, *args) if ($stdin.getc == 'Y') | |
| end | |
| method_missing_without_fix_typo(name, *args) | |
| end | |
| private | |
| def find_method_with_only_one_typo name | |
| self.class.instance_methods.each do |method| | |
| next unless method.size == name.size | |
| return method if(method.to_s.split(//) - name.to_s.split(//)).size == 1 | |
| end | |
| nil | |
| end | |
| def find_method name | |
| name.to_s.split(//).permutation.each do |candidate| | |
| _candidate = candidate.join | |
| return _candidate if respond_to?(_candidate, true) | |
| end | |
| nil | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment