Skip to content

Instantly share code, notes, and snippets.

@hakobera
Forked from pablox-cl/csv2yaml.rb
Created March 21, 2012 13:43
Show Gist options
  • Save hakobera/2146983 to your computer and use it in GitHub Desktop.
Save hakobera/2146983 to your computer and use it in GitHub Desktop.
Simple Ruby CSV to YAML converter for Play framework Fixture
#!/usr/bin/env ruby
#
# Originally written by http://redartisan.com/tags/csv
# Added and minor changes by Gavin Laking
#
# "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
entity_name = ARGV[0]
filename = ARGV[1]
# first line contains the field names
src = File.read(filename, :encoding => Encoding::UTF_8)
first_line = src.split(/(\r?\n)+/)[0]
fields = first_line.split('","').collect {|f| f.unquote.chomp}
CSV.parse(src, :headers => true) do |row|
fixture = "#{ARGV[0]}(#{row[0]}):\n"
fields.each_with_index do |field, i|
fixture += " #{field}: #{row[i]}\n"
end
puts fixture; puts
end
@hakobera
Copy link
Author

How to use

$ csv2yaml.rb [EntityName] [CSV file]

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