Skip to content

Instantly share code, notes, and snippets.

@mmasashi
Created January 18, 2017 19:55
Show Gist options
  • Save mmasashi/edb3b4ed1cb5ce503a8781def2ddfb52 to your computer and use it in GitHub Desktop.
Save mmasashi/edb3b4ed1cb5ce503a8781def2ddfb52 to your computer and use it in GitHub Desktop.
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