Class: Jcsv::MapReader

Inherits:
Reader
  • Object
show all
Defined in:
lib/map_reader.rb

Overview

Direct Known Subclasses

MDArrayReader

Instance Attribute Summary

Attributes inherited from Reader

#chunk_size, #col_sep, #column_mapping, #comment_matches, #comment_starts, #data_labels, #dimensions_names, #filename, #headers, #ignore_empty_lines, #processed_column, #quote_char, #rows, #strings_as_keys, #suppress_warnings, #surrounding_space_need_quotes

Instance Method Summary collapse

Methods inherited from Reader

#[], #dimensions, #each

Constructor Details

#initialize(*params) ⇒ MapReader





39
40
41
42
43
# File 'lib/map_reader.rb', line 39

def initialize(*params)
  super(*params)
  @column_mapping.mapping = @headers if !@dimensions
  @map_klass = (@format == :map)? Hash : Critbit
end

Instance Method Details

#mapping=(column_mapping) ⇒ Object


Maps columns to the given names. In map reader, there is no column reordering, as this does not really make any sense, since one gets to the data through the key and not through its position in the array. If there are dimensions set, then every dimension will map to true, in order for it to be properly processed by the parsing method. Other fields can still be mapped to false, so that they are not read if desired.




54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/map_reader.rb', line 54

def mapping=(column_mapping)

  @column_mapping.mapping ||= Array.new
  
  @headers.each_with_index do |h, i|
    next if @dimensions && !@dimensions[h].nil?
    name = column_mapping[h]
    raise ArgumentError.new("'true' is not allowed as a mapping: #{column_mapping}") if
      name == true
    @column_mapping.mapping[i] = (name.nil?)? h : name
  end

end

#read(&block) ⇒ Object


read the file.




72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/map_reader.rb', line 72

def read(&block)

  # When no block given, chunks read are stored in an array and returned to the user.
  if (!block_given?)
    # if dimensions and chunk_size is 0, then do not wrap each row in an array, we
    # can access the data directly by using the dimension key
    if (@dimensions && @chunk_size == 0)
      rows = @map_klass.new
      parse_with_block do |line_no, row_no, chunk|
        rows.merge!(chunk)
      end
    else
      # chunk_size > 0, then each chunk should be a hash, and all chunks should
      # be wrapped inside an array
      rows = []
      parse_with_block do |line_no, row_no, chunk|
        rows << chunk
      end
    end
    rows
  else # block given
    parse_with_block(&block)
  end
end