-
-
Save hryk/847188224a1d2cd56e2b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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