Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Created April 30, 2010 23:33
Show Gist options
  • Save bradgessler/385886 to your computer and use it in GitHub Desktop.
Save bradgessler/385886 to your computer and use it in GitHub Desktop.
# Spell checking ruby env
# !!!! IMPORTANT Be sure you have iSpell installed: sudo port install ispell !!!!
require 'stringio'
begin
require 'simplecc'
rescue LoadError
# to satisfy rdoc
class Continuation #:nodoc:
end
def Continuation.create(*args, &block) # :nodoc:
cc = nil; result = callcc {|c| cc = c; block.call(cc) if block and args.empty?}
result ||= args
return *[cc, *result]
end
end
def Binding.of_caller(&block)
old_critical = Thread.critical
Thread.critical = true
count = 0
cc, result, error, extra_data = Continuation.create(nil, nil)
error.call if error
tracer = lambda do |*args|
type, context, extra_data = args[0], args[4], args
if type == "return"
count += 1
if count == 2
set_trace_func(nil)
cc.call(eval("binding", context), nil, extra_data)
end
elsif type == "line" then
nil
elsif type == "c-return" and extra_data[3] == :set_trace_func then
nil
else
set_trace_func(nil)
error_msg = "Binding.of_caller used in non-method context or " +
"trailing statements of method using it aren't in the block."
cc.call(nil, lambda { raise(ArgumentError, error_msg) }, nil)
end
end
unless result
set_trace_func(tracer)
return nil
else
Thread.critical = old_critical
case block.arity
when 1 then yield(result)
else yield(result, extra_data)
end
end
end
module Kernel
def method_missing(meth, *args)
Binding.of_caller do |binding|
meth = meth.to_s
corrected_meth = meth.split('_').inject([]) do |memo, word|
if suggestions = spell_check(word)
memo << suggestions.first
else
memo << word
end
memo
end.join('_')
if corrected_meth == meth
super
else
if eval("respond_to?('#{corrected_meth}')", binding)
puts "# Corrected #{meth} to #{corrected_meth}"
eval("send('#{corrected_meth}', *args)", binding)
# puts binding.inspect
else
puts "You typed in #{meth}. We tried to correct it to #{corrected_meth}, but that didn't work."
end
end
end
end
def spell_check(word)
buffer = ""
IO.popen "ispell", 'r+' do |pipe|
pipe.write word
pipe.close_write
until pipe.eof do
buffer << pipe.read
end
end
# Get the line with teh words on it
if match = buffer.to_a[1].match(/how about: (.+)/)
return match.captures.first.split(/, ?/)
end
end
end
class Hi
def cool_art(val)
puts "The #{val} is cool!"
end
end
h = Hi.new
h.cool_art 'mona lisa'
h.cool_fart 'picasso'
h.cool_sart 'something sweet'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment