Class: Parceira::Reader

Inherits:
Object
  • Object
show all
Defined in:
lib/parceira/reader.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  # CSV options
  col_sep:            ',',
  row_sep:            $/,
  quote_char:         '"',
  # Header
  headers:            true,
  headers_included:   true,
  key_mapping:        nil,
  file_encoding:      nil,
  # Values
  reject_blank:       true,
  reject_nil:         false,
  reject_zero:        false,
  reject_matching:    nil,
  convert_to_numeric: true,
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, options) ⇒ Reader

Returns a new instance of Reader.



24
25
26
27
# File 'lib/parceira/reader.rb', line 24

def initialize(input, options)
  @input    = input
  @options  = DEFAULT_OPTIONS.merge(options)
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



21
22
23
# File 'lib/parceira/reader.rb', line 21

def options
  @options
end

Instance Method Details

#process!Object



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
# File 'lib/parceira/reader.rb', line 30

def process!
  if input_file.nil? && @input.is_a?(String)
    data = CSV.parse(@input, csv_options) # content is already in memory. Process with CSV
    header_data = data.shift if options[:headers_included] # Remove header row
    header_keys = \
      if options[:headers] == true
        self.parse_header( header_data )
      elsif options[:headers].is_a?(Array)
        options[:headers]
      end
    data.map do |arr|
      values = parse_values(arr)
      if header_keys
        convert_to_hash(header_keys, values)
      else
        values
      end
    end
  elsif input_file.is_a?(File)
    output = []
    begin
      $/ = options[:row_sep]
      # Build header
      header_data = input_file.readline.to_s.chomp(options[:row_sep]) if options[:headers_included] # Remove header row
      header_keys = \
        if options[:headers] == true
          begin
            data = CSV.parse(header_data, self.csv_options)
            self.parse_header( data )
          rescue CSV::MalformedCSVError
          end
        elsif options[:headers].is_a?(Array)
          options[:headers]
        end

      # now on to processing all the rest of the lines in the CSV file:
      while !input_file.eof?    # we can't use f.readlines() here, because this would read the whole file into memory at once, and eof => true
        values =  begin
                    parse_values( CSV.parse(input_file.readline.chomp, csv_options) )
                  rescue CSV::MalformedCSVError
                  end
        if header_keys
          output << convert_to_hash(header_keys, values)
        else
          output << values
        end if values
      end
    ensure
      $/ = $/
    end
    output
  end
end