Skip to content

Instantly share code, notes, and snippets.

@arunjax
Created July 22, 2011 17:35
Show Gist options
  • Select an option

  • Save arunjax/1099930 to your computer and use it in GitHub Desktop.

Select an option

Save arunjax/1099930 to your computer and use it in GitHub Desktop.
Editing large strings using vi from rails console or irb
load 'irb_editor.rb'
c = Contest.first
c.description # => Prints the original description
c.description.edit! # => This launches the vi editor. Edit the content in the editor and type :wq
c.save!
# Ability to edit a large string using your favourite editor - vi
require 'tempfile'
class IrbEditor
TMP_FILE_NAME = "irb_tempfile"
# Right now it supports vi only. Other possible values:
# => 'mate -w'
# => 'nane'
# => 'emacs'
EDITOR_COMMAND = 'vi'
attr_accessor :file
def initialize
self.file = Tempfile.new([TMP_FILE_NAME, '.rb'])
end
def edit(value)
File.open(self.file.path, 'w') { |f| f.puts(value) }
system("#{EDITOR_COMMAND} #{self.file.path}")
return self
end
def read
IO.read(self.file.path).chomp
end
end
# Extending the string class itself!
String.class_eval do
IRB.conf[:irb_editor] = IrbEditor.new
def edit!
self.replace(self.edit)
end
def edit
IRB.conf[:irb_editor].edit(self).read
end
end
@inkel

inkel commented Jul 25, 2011

Copy link
Copy Markdown

I'd rather use ENV['EDITOR'] instead of hardcoding the editor

@jeffkreeftmeijer

Copy link
Copy Markdown

I'd love to see the ability to update the whole record instead of just one attribute at a time too. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment