Skip to content

Instantly share code, notes, and snippets.

@hryk
Created May 7, 2014 10:17
Show Gist options
  • Save hryk/847188224a1d2cd56e2b to your computer and use it in GitHub Desktop.
Save hryk/847188224a1d2cd56e2b to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "csv"
require "json"
require "yaml"
def help(msg = "")
puts msg
puts <<-EOF
csv2 something converter
csv2 FORMAT FILEPATH
Supported formats are:
#{supported_formats.map { |i| " - #{i}" }.join("\n")}
EOF
true
end
def supported_formats
formats = []
Object.private_instance_methods(false).each do |method|
match = /convert_(\w+)/.match(method.to_s)
formats << match[1] if match
end
formats
end
def convert_yaml(data)
YAML.dump(data)
end
def convert_json(data)
JSON.dump(data)
end
def convert(format, path)
data = []
CSV.open(path, headers: true, return_headers: true) do |csv|
csv.each { |row| data << row.to_hash }
end
__send__ "convert_#{format}".to_sym, data
end
def main
help && exit(1) if ARGV.size < 2
to, path = ARGV[0], ARGV[1]
help("Unsupported format") && exit(1) unless supported_formats.include?(to)
help("No such file: #{path}") && exit(1) unless FileTest.exist?(path)
puts convert(to, path)
end
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment