Created
January 18, 2017 19:55
-
-
Save mmasashi/edb3b4ed1cb5ce503a8781def2ddfb52 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
require 'msgpack' | |
require 'json' | |
def usage | |
puts <<EOT | |
usage: ruby msgpack_util.rb <option> <input-file-path> [<output-file-path>] | |
option: | |
-d, --decode: Decode msgpack formatted data into JSON formatted data | |
-e, --encode: Encode JSON formatted data into msgpack formatted data | |
EOT | |
exit 1 | |
end | |
def decode(input, output) | |
open_output(output) do |o| | |
u = MessagePack::Unpacker.new(File.open(input)) | |
u.each do |obj| | |
o.puts obj.to_json | |
end | |
end | |
end | |
def encode(input, output) | |
open_output(output) do |o| | |
File.new(input).each_line do |line| | |
j = JSON.parse(line) | |
o.print j.to_msgpack | |
end | |
end | |
end | |
def open_output(output) | |
o = output ? File.new(output, 'w') : $stdout | |
yield o | |
ensure | |
o.close if o && o.kind_of?(File) | |
end | |
usage if ARGV.size < 2 | |
input_file_path = ARGV[1] | |
output_file_path = ARGV[2] | |
case ARGV[0] | |
when '-d', '--decode' | |
decode(input_file_path, output_file_path) | |
when '-e', '--encode' | |
encode(input_file_path, output_file_path) | |
else | |
usage | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment