Skip to content

Instantly share code, notes, and snippets.

@nanki
Created March 28, 2011 13:15
Show Gist options
  • Save nanki/890421 to your computer and use it in GitHub Desktop.
Save nanki/890421 to your computer and use it in GitHub Desktop.
Edit ruby string by the editor.
# editor.rb
#
# $ irb -reditor
# > Editor.edit("abc") # Edit "abc" with the external editor.
# => "abc has changed"
#
# Author: @nanki / nanki at dotswitch dot net
require 'tempfile'
module Editor
def edit(string='', editor = ENV["EDITOR"] || "vim -b")
begin
tmp = Tempfile.open(%w(editor .tmp))
tmp.write string
tmp.close
if system([editor, tmp.path].join(' '))
tmp.open.read.force_encoding(string.encoding)
else
string
end
ensure
tmp.close!
end
end
class << self
include Editor
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment