Method: Jinx::CsvIO#initialize
- Defined in:
- lib/jinx/csv/csvio.rb
#initialize(dev, opts = nil) {|value, info| ... } ⇒ CsvIO
Creates a new CsvIO for the specified source file. If a converter block is given, then it is added to the CSV converters list.
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
# File 'lib/jinx/csv/csvio.rb', line 84 def initialize(dev, opts=nil, &converter) raise ArgumentError.new("CSV input argument is missing") if dev.nil? # the CSV file open mode mode = Options.get(:mode, opts, 'r') # the CSV headers option; can be boolean or array hdr_opt = Options.get(:headers, opts) # there is a header record by default for an input CSV file hdr_opt ||= true if mode =~ /^r/ # make parent directories if necessary for an output CSV file File.makedirs(File.dirname(dev)) if String == dev and mode =~ /^w/ # if headers aren't given, then convert the input CSV header record names to underscore symbols hdr_cvtr = :symbol unless Enumerable === hdr_opt # make a custom converter custom = Proc.new { |value, info| convert(value, info, &converter) } # collect the options csv_opts = {:headers => hdr_opt, :header_converters => hdr_cvtr, :return_headers => true, :write_headers => true, :converters => custom} # Make the parent directory if necessary. FileUtils.mkdir_p(File.dirname(dev)) if String === dev and mode !~ /^r/ # open the CSV file @csv = String === dev ? FasterCSV.open(dev, mode, csv_opts) : FasterCSV.new(dev, csv_opts) # the header => field name hash: # if the header option is set to true, then read the input header line. # otherwise, parse an empty string which mimics an input header line. hdr_row = case hdr_opt when true then @csv.shift when Enumerable then ''.parse_csv(:headers => hdr_opt, :header_converters => :symbol, :return_headers => true) else raise ArgumentError.new("CSV headers option value not supported: #{hdr_opt}") end # The field value accessors consist of the header row headers converted to a symbol. @accessors = hdr_row.headers # The field names consist of the header row values. @field_names = @accessors.map { |sym| hdr_row[sym] } # the header name => symbol map @hdr_sym_hash = hdr_row.to_hash.invert end |