Sha256: e005205616c82006a5288cf2b5947e65a1d2bf708174d59e46413d4a67ec7965

Contents?: true

Size: 1.28 KB

Versions: 3

Compression:

Stored size: 1.28 KB

Contents

#encoding: UTF-8
module Termit
  class UserInputParser
    extend ::Delegation
    @output_manager = Termit::OutputManager.new

    delegate :display_error_info_and_quit, :display_help_and_quit, :display_version_and_quit, to: @output_manager

    def initialize user_input
      @user_input = user_input
      quit_if_required
      validate_user_input
    rescue ArgumentError
      display_error_info_and_quit
    end

    def options
      parse_input
    end

    private

    def parse_input
      {
       talk: extract_flag('t'),
       synonyms: extract_flag('s'),
       source_lang: @user_input.shift.to_sym,
       target_lang: @user_input.shift.to_sym,
       text: @user_input.join(' ')
      }
    end

    def extract_flag(symbol)
      flag_index = @user_input.index("-#{symbol}")
      flag_index ? !!@user_input.delete_at(flag_index) : false
    end

    def validate_user_input
      raise ArgumentError unless @user_input.is_a? Array
      raise ArgumentError unless @user_input.length > 1
      [0, 1].each do |index|
        raise ArgumentError unless [2, 4].include?(@user_input[index].length)
      end
    end

    def quit_if_required
      display_help_and_quit if @user_input.index("-h") || @user_input.empty?
      display_version_and_quit if @user_input.index("-v")
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
termit-2.0.8 lib/termit/user_input_parser.rb
termit-2.0.7 lib/termit/user_input_parser.rb
termit-2.0.6 lib/termit/user_input_parser.rb