lib/transcriptic/helpers.rb in transcriptic-0.1.2 vs lib/transcriptic/helpers.rb in transcriptic-0.1.3

- old
+ new

@@ -30,10 +30,20 @@ def deprecate(version) display "!!! DEPRECATION WARNING: This command will be removed in version #{version}" display end + def format_with_bang(message) + return '' if message.to_s.strip == "" + " ! " + message.split("\n").join("\n ! ") + end + + def output_with_bang(message="", new_line=true) + return if message.to_s.strip == "" + display(format_with_bang(message), new_line) + end + def error(msg) STDERR.puts(msg) exit 1 end @@ -273,9 +283,64 @@ class << base alias_method :error, :error_without_failure end end end + + def string_distance(first, last) + distances = [] # 0x0s + 0.upto(first.length) do |index| + distances << [index] + [0] * last.length + end + distances[0] = 0.upto(last.length).to_a + 1.upto(last.length) do |last_index| + 1.upto(first.length) do |first_index| + first_char = first[first_index - 1, 1] + last_char = last[last_index - 1, 1] + if first_char == last_char + distances[first_index][last_index] = distances[first_index - 1][last_index - 1] # noop + else + distances[first_index][last_index] = [ + distances[first_index - 1][last_index], # deletion + distances[first_index][last_index - 1], # insertion + distances[first_index - 1][last_index - 1] # substitution + ].min + 1 # cost + if first_index > 1 && last_index > 1 + first_previous_char = first[first_index - 2, 1] + last_previous_char = last[last_index - 2, 1] + if first_char == last_previous_char && first_previous_char == last_char + distances[first_index][last_index] = [ + distances[first_index][last_index], + distances[first_index - 2][last_index - 2] + 1 # transposition + ].min + end + end + end + end + end + distances[first.length][last.length] + end + + def suggestion(actual, possibilities) + distances = Hash.new {|hash,key| hash[key] = []} + + possibilities.each do |suggestion| + distances[string_distance(actual, suggestion)] << suggestion + end + + minimum_distance = distances.keys.min + if minimum_distance < 4 + suggestions = distances[minimum_distance].sort + if suggestions.length == 1 + "Perhaps you meant `#{suggestions.first}`." + else + "Perhaps you meant #{suggestions[0...-1].map {|suggestion| "`#{suggestion}`"}.join(', ')} or `#{suggestions.last}`." + end + else + nil + end + end + end end unless String.method_defined?(:shellescape) class String \ No newline at end of file