info | twitter | github
J-_-L | Writings on Ruby Programming
08.03.11 12.03.11
5 comments

Small Ruby CLI Improvements (Part 4): Edit Ruby Objects Using yaml

hints · irb · ruby

Somehow, I stumbled upon this useful little script by _why: Update

Lovely, Simple, Prismatic I say it’s prismatic because this little snippy marries a few of my true loves together. Allow users to edit Ruby objects in YAML using your editor of choice.

Listing 1
/48/aorta.rb ruby
 1
2
3
4
5
6
7
8
9
10
11
12
13
# why the luck stiff's "object aorta"
# http://rubyforge.org/snippet/detail.php?type=snippet&id=22

require 'yaml'
def aorta( obj )
  tempfile = File.join('/tmp',"yobj_#{ Time.now.to_i }")
  File.open( tempfile, 'w' ) { |f| f << obj.to_yaml }
  system( "#{ ENV['EDITOR'] || 'vi' } #{ tempfile }" )
  return obj unless File.exists?( tempfile )
  content = YAML::load( File.open( tempfile ) )
  File.delete( tempfile )
  content
end

Update: I’ve added this functionality to the interactive_editor gem, which is – thanks to github – now available with version 0.0.7 :D

[2,3,4].vim #=> [2,3,42]

Creative Commons License

Comments

10.03.11

scragz

I miss _why ><;

11.03.11

mkorfmann

Me too :( . But fractions of his work, like this one, never let him die :) .

15.03.11

andy

This looks cool!
Tried running [1,2,3].vim in IRB and got the error below. Just running 'vim' from the IRB prompt works ok.
Using Ubuntu / Ruby 1.8.7
TypeError: can't convert Tempfile into String
from /home/andyl/.gems/ruby/1.8/gems/interactive_editor-0.0.7/lib/interactive_editor.rb:35:in `initialize'
from /home/andyl/.gems/ruby/1.8/gems/interactive_editor-0.0.7/lib/interactive_editor.rb:35:in `open'
from /home/andyl/.gems/ruby/1.8/gems/interactive_editor-0.0.7/lib/interactive_editor.rb:35:in `edit'
from /home/andyl/.gems/ruby/1.8/gems/interactive_editor-0.0.7/lib/interactive_editor.rb:59:in `edit'
from /home/andyl/.gems/ruby/1.8/gems/interactive_editor-0.0.7/lib/interactive_editor.rb:96:in `vim'
from (irb):6

18.03.11

J-_-L

Oops, I'll fix that. Btw, no problems with 1.9 ;)

28.03.11

J-_-L

0.0.8 fixes the 1.8 issue