Sha256: c0dff2c7206ea69c4217d56fd1329c66becb894596d19f031facf8ac9b878b6e

Contents?: true

Size: 968 Bytes

Versions: 3

Compression:

Stored size: 968 Bytes

Contents

module Basic101

  class InputReader

    def initialize(input)
      line = input.read_line
      line += ',' unless line.empty?
      line += EOS
      @columns = line.parse_csv
    rescue CSV::MalformedCSVError => e
      raise BadInputFormatError, 'Invalid format'
    end

    def read_string
      end_of_input_error if @columns.empty?
      value = @columns.shift
      if value == EOS
        ''
      else
        value || ''
      end
    end

    def read_numeric
      column = next_column
      unless column =~ /^[+-]?\d+/
        raise BadInputFormatError, "Not numeric: #{column.inspect}"
      end
      column.to_f
    end

    private

    def next_column
      raise_error_if_eos
      @columns.shift || ''
    end

    def raise_error_if_eos
      if @columns.first == EOS
        end_of_input_error
      end
    end

    private

    EOS = "EOS"

    def end_of_input_error
      raise TooFewInputItemsError, "Too few items"
    end

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
basic101-0.4.0 lib/basic101/input_reader.rb
basic101-0.2.0 lib/basic101/input_reader.rb
basic101-0.1.0 lib/basic101/input_reader.rb