Skip to content

Instantly share code, notes, and snippets.

@reservationlive
Created February 25, 2009 15:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save reservationlive/70212 to your computer and use it in GitHub Desktop.
Save reservationlive/70212 to your computer and use it in GitHub Desktop.
Textmate/Ruby script to convert CSV to YAML
#!/usr/bin/env ruby
#
# Originally written by http://redartisan.com/tags/csv
# Added and minor changes by Gavin Laking
# Remove ::Reader and it shall work in Ruby 1.9.x
#
# "id","name","mime_type","extensions","icon_url"
# "1","unknown","unknown/unknown","||","/images/icon/file_unknown.gif"
# "2","image/tiff","image/tiff","|tiff|tif|","/images/icon/blank.png"
#
# if you want to remove the id: "number" line from the resulting YAML file
# do a find and replace for: ^( id: \"\d*\"\n) in Textmate
require 'csv'
class String
def unquote
self.gsub(/^"|"$/, '')
end
end
# first line contains the field names
line = gets
fields = line.split('","').collect {|f| f.unquote.chomp}
CSV::Reader.parse(STDIN) do |row|
fixture = "record_#{row[0]}:\n"
fields.each_with_index do |field, i|
fixture += " #{field}: \"#{row[i]}\"\n"
end
puts fixture; puts
end
@raganwald
Copy link

Ruby 1.8.x only, CSV::Writer does not exist in the Ruby 1.9.x standard library

@pablox-cl
Copy link

I made it work by deleting the ::Reader part.

@potatosalad
Copy link

Ruby 1.9 version with support for YAML and JSON fixture output available here: https://gist.github.com/893073

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