Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save potatosalad/893073 to your computer and use it in GitHub Desktop.
Save potatosalad/893073 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
#
# Originally written by http://redartisan.com/tags/csv
# Added and minor changes by Gavin Laking
# Rewritten by Andrew Bennett for Ruby 1.9
#
# Usage: ruby csv_to_fixture.rb file.csv [--json]
#
# "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'
require 'json'
require 'yaml'
input = ARGV.shift
is_file = (input.nil? ? false : File.exist?(input))
file = is_file ? input : STDIN
doc = is_file ? CSV.read(file) : CSV.parse(file.read)
fields = doc.shift
records = Hash.new
doc.each_with_index do |row, i|
record = Hash.new
fields.each_with_index do |field, j|
record[field] = row[j]
end
records["record_#{i}"] = record
end
flag = ARGV.shift unless input.nil?
flag ||= input || '--yaml'
case flag
when '--json' then
puts records.to_json
else
puts records.to_yaml
end
@Phlow
Copy link

Phlow commented Mar 2, 2020

Hello, thank you for this great script. It works for me. But is there a way to channel the output directly into a file?

@Eunesh
Copy link

Eunesh commented Feb 19, 2024

@Phlow Just open the file and write on it

case flag
when '--json' then
write_file_in_json(yourfilename, flagname, records)
else
write_file_in_yml(yourfilename, flagname, records)
end

// For yml
def write_file_in_yml(filename, flag, records)
File.open("#{filename}.#{flag}", 'w') do | f |
f.puts record.to_yaml
end
end

// For json
def write_file_in_json
(filename, flag, records)
File.open("#{filename}.#{flag}", 'w') do | f |
f.puts record.to_json
end
end

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