class SwitchDb::OptionParser
Constants
- REQUIRED_KEYS
Public Class Methods
new(argv)
click to toggle source
# File lib/switch_db/option_parser.rb, line 13 def initialize(argv) @original_argv = argv @options = {} end
Public Instance Methods
parse!(argv = @original_argv.clone)
click to toggle source
# File lib/switch_db/option_parser.rb, line 18 def parse!(argv = @original_argv.clone) @options[:command] = argv[0] # rubocop:disable Lint/EmptyWhen case @options[:command] when 'list' # Do nothing when 'config' parse_config_argv(argv[1..-1]) when 'store', 'restore', 'rm' @options[:name] = argv[1] parse_argv(argv) else parse_argv(argv) end # rubocop:enable Lint/EmptyWhen validate_option! @options end
Private Instance Methods
parse_argv(argv)
click to toggle source
# File lib/switch_db/option_parser.rb, line 67 def parse_argv(argv) argv.each_with_index do |raw_key, index| next unless raw_key.start_with?('--') key = raw_key.gsub(/^--/, '') next_index = index + 1 value = argv[next_index] unless argv[next_index].to_s.start_with?('--') parse_option(key, value) end end
parse_config_argv(argv)
click to toggle source
# File lib/switch_db/option_parser.rb, line 58 def parse_config_argv(argv) key_values = argv.select { |key_value| key_value.include?(':') } key_values.each do |key_value| key, value = key_value.split(':') @options[key.to_sym] = value.to_s end end
parse_option(option_name, value)
click to toggle source
# File lib/switch_db/option_parser.rb, line 78 def parse_option(option_name, value) case option_name when 'database_names' @options[:database_names] = value.to_s.split(/(?:,|\s+)/) when 'help' puts banner exit else print_error("'--#{option_name}' is unknown option.") end end
print_error(message)
click to toggle source
# File lib/switch_db/option_parser.rb, line 90 def print_error(message) $stderr.puts("switch_db: #{message} See 'switch_db --help'") exit end
validate_option!()
click to toggle source
# File lib/switch_db/option_parser.rb, line 42 def validate_option! required_keys = REQUIRED_KEYS[@options[:command].to_s.to_sym] if required_keys.nil? print_error("'#{@options[:command]}' is unknown command.") elsif required_keys.include?(:name) && @options[:name].to_s.empty? print_error("<name> is empty.") else required_keys.select { |name| name.to_s.start_with?('--') }.each do |name| name = name.to_s.gsub(/^--/, '').to_sym value = @options[name] print_error("'--#{name}' option is empty.") if value.nil? || value.empty? end end end