1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
#!/usr/bin/env ruby
require "qr4r"
require "optparse"
class CmdlineOpts
@opts = nil
ALLOWED_FORMATS = %w[jpg jpeg gif tif tiff png].freeze
attr_reader :options
class Options
attr_accessor :format, :border, :pixel_size, :verbose
def to_h
{ format: format, border: border, pixel_size: pixel_size, verbose: verbose }
end
end
def initialize(args)
@options = Options.new
@options.format = "gif"
@options.border = 0
@options.pixel_size = 10
@options.verbose = false
@opts = setup_options
@opts.parse!(args)
end
# rubocop:disable Metrics/MethodLength
def setup_options
OptionParser.new do |opts|
opts.banner = "Usage: $0 [options] outfile the stuff to encode"
opts.separator ""
# Mandatory argument.
opts.on("-f",
"--format FILE_FORMAT",
ALLOWED_FORMATS,
"Output qrcode image format (default: gif)",
" (#{ALLOWED_FORMATS.join ", "})") do |fmt|
@options.format = fmt
end
opts.on("-b", "--border N",
"Render with a border of this size") do |border|
@options.border = border.to_i
end
opts.on("-p", "--pixelsize N",
"Size for each qrcode pixel") do |px|
@options.pixel_size = px.to_i
end
opts.on("-v", "--[no-]verbose", "Be verbose") do |v|
@options.verbose = v
end
# No argument, shows at tail. This will print an options summary.
# Try it and see!
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
opts
end
# rubocop:enable Metrics/MethodLength
end
def help
puts @opts
end
end
cmd_options = CmdlineOpts.new(ARGV)
if ARGV.length < 2
cmd_options.help
else
outfile = ARGV.shift
to_encode = ARGV.join " "
options = cmd_options.options
if options.verbose
print "Encoding \"#{to_encode}\" to file #{outfile}"
print " with border #{options.border}" if options.border.positive?
print " and pixel_size #{options.pixel_size}"
puts " and format #{options.format}"
end
Qr4r.encode(to_encode, outfile, cmd_options.options.to_h)
end
|