Chris@0: #!/usr/local/bin/ruby -w
Chris@0:
Chris@0: # = faster_csv.rb -- Faster CSV Reading and Writing
Chris@0: #
Chris@0: # Created by James Edward Gray II on 2005-10-31.
Chris@0: # Copyright 2005 Gray Productions. All rights reserved.
Chris@0: #
Chris@0: # See FasterCSV for documentation.
Chris@0:
Chris@0: if RUBY_VERSION >= "1.9"
Chris@0: abort <<-VERSION_WARNING.gsub(/^\s+/, "")
Chris@0: Please switch to Ruby 1.9's standard CSV library. It's FasterCSV plus
Chris@0: support for Ruby 1.9's m17n encoding engine.
Chris@0: VERSION_WARNING
Chris@0: end
Chris@0:
Chris@0: require "forwardable"
Chris@0: require "English"
Chris@0: require "enumerator"
Chris@0: require "date"
Chris@0: require "stringio"
Chris@0:
Chris@0: #
Chris@0: # This class provides a complete interface to CSV files and data. It offers
Chris@0: # tools to enable you to read and write to and from Strings or IO objects, as
Chris@0: # needed.
Chris@0: #
Chris@0: # == Reading
Chris@0: #
Chris@0: # === From a File
Chris@0: #
Chris@0: # ==== A Line at a Time
Chris@0: #
Chris@0: # FasterCSV.foreach("path/to/file.csv") do |row|
Chris@0: # # use row here...
Chris@0: # end
Chris@0: #
Chris@0: # ==== All at Once
Chris@0: #
Chris@0: # arr_of_arrs = FasterCSV.read("path/to/file.csv")
Chris@0: #
Chris@0: # === From a String
Chris@0: #
Chris@0: # ==== A Line at a Time
Chris@0: #
Chris@0: # FasterCSV.parse("CSV,data,String") do |row|
Chris@0: # # use row here...
Chris@0: # end
Chris@0: #
Chris@0: # ==== All at Once
Chris@0: #
Chris@0: # arr_of_arrs = FasterCSV.parse("CSV,data,String")
Chris@0: #
Chris@0: # == Writing
Chris@0: #
Chris@0: # === To a File
Chris@0: #
Chris@0: # FasterCSV.open("path/to/file.csv", "w") do |csv|
Chris@0: # csv << ["row", "of", "CSV", "data"]
Chris@0: # csv << ["another", "row"]
Chris@0: # # ...
Chris@0: # end
Chris@0: #
Chris@0: # === To a String
Chris@0: #
Chris@0: # csv_string = FasterCSV.generate do |csv|
Chris@0: # csv << ["row", "of", "CSV", "data"]
Chris@0: # csv << ["another", "row"]
Chris@0: # # ...
Chris@0: # end
Chris@0: #
Chris@0: # == Convert a Single Line
Chris@0: #
Chris@0: # csv_string = ["CSV", "data"].to_csv # to CSV
Chris@0: # csv_array = "CSV,String".parse_csv # from CSV
Chris@0: #
Chris@0: # == Shortcut Interface
Chris@0: #
Chris@0: # FCSV { |csv_out| csv_out << %w{my data here} } # to $stdout
Chris@0: # FCSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String
Chris@0: # FCSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr
Chris@0: #
Chris@0: class FasterCSV
Chris@0: # The version of the installed library.
Chris@0: VERSION = "1.5.0".freeze
Chris@0:
Chris@0: #
Chris@0: # A FasterCSV::Row is part Array and part Hash. It retains an order for the
Chris@0: # fields and allows duplicates just as an Array would, but also allows you to
Chris@0: # access fields by name just as you could if they were in a Hash.
Chris@0: #
Chris@0: # All rows returned by FasterCSV will be constructed from this class, if
Chris@0: # header row processing is activated.
Chris@0: #
Chris@0: class Row
Chris@0: #
Chris@0: # Construct a new FasterCSV::Row from +headers+ and +fields+, which are
Chris@0: # expected to be Arrays. If one Array is shorter than the other, it will be
Chris@0: # padded with +nil+ objects.
Chris@0: #
Chris@0: # The optional +header_row+ parameter can be set to +true+ to indicate, via
Chris@0: # FasterCSV::Row.header_row?() and FasterCSV::Row.field_row?(), that this is
Chris@0: # a header row. Otherwise, the row is assumes to be a field row.
Chris@0: #
Chris@0: # A FasterCSV::Row object supports the following Array methods through
Chris@0: # delegation:
Chris@0: #
Chris@0: # * empty?()
Chris@0: # * length()
Chris@0: # * size()
Chris@0: #
Chris@0: def initialize(headers, fields, header_row = false)
Chris@0: @header_row = header_row
Chris@0:
Chris@0: # handle extra headers or fields
Chris@0: @row = if headers.size > fields.size
Chris@0: headers.zip(fields)
Chris@0: else
Chris@0: fields.zip(headers).map { |pair| pair.reverse }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # Internal data format used to compare equality.
Chris@0: attr_reader :row
Chris@0: protected :row
Chris@0:
Chris@0: ### Array Delegation ###
Chris@0:
Chris@0: extend Forwardable
Chris@0: def_delegators :@row, :empty?, :length, :size
Chris@0:
Chris@0: # Returns +true+ if this is a header row.
Chris@0: def header_row?
Chris@0: @header_row
Chris@0: end
Chris@0:
Chris@0: # Returns +true+ if this is a field row.
Chris@0: def field_row?
Chris@0: not header_row?
Chris@0: end
Chris@0:
Chris@0: # Returns the headers of this row.
Chris@0: def headers
Chris@0: @row.map { |pair| pair.first }
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # field( header )
Chris@0: # field( header, offset )
Chris@0: # field( index )
Chris@0: #
Chris@0: # This method will fetch the field value by +header+ or +index+. If a field
Chris@0: # is not found, +nil+ is returned.
Chris@0: #
Chris@0: # When provided, +offset+ ensures that a header match occurrs on or later
Chris@0: # than the +offset+ index. You can use this to find duplicate headers,
Chris@0: # without resorting to hard-coding exact indices.
Chris@0: #
Chris@0: def field(header_or_index, minimum_index = 0)
Chris@0: # locate the pair
Chris@0: finder = header_or_index.is_a?(Integer) ? :[] : :assoc
Chris@0: pair = @row[minimum_index..-1].send(finder, header_or_index)
Chris@0:
Chris@0: # return the field if we have a pair
Chris@0: pair.nil? ? nil : pair.last
Chris@0: end
Chris@0: alias_method :[], :field
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # []=( header, value )
Chris@0: # []=( header, offset, value )
Chris@0: # []=( index, value )
Chris@0: #
Chris@0: # Looks up the field by the semantics described in FasterCSV::Row.field()
Chris@0: # and assigns the +value+.
Chris@0: #
Chris@0: # Assigning past the end of the row with an index will set all pairs between
Chris@0: # to [nil, nil]. Assigning to an unused header appends the new
Chris@0: # pair.
Chris@0: #
Chris@0: def []=(*args)
Chris@0: value = args.pop
Chris@0:
Chris@0: if args.first.is_a? Integer
Chris@0: if @row[args.first].nil? # extending past the end with index
Chris@0: @row[args.first] = [nil, value]
Chris@0: @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
Chris@0: else # normal index assignment
Chris@0: @row[args.first][1] = value
Chris@0: end
Chris@0: else
Chris@0: index = index(*args)
Chris@0: if index.nil? # appending a field
Chris@0: self << [args.first, value]
Chris@0: else # normal header assignment
Chris@0: @row[index][1] = value
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # <<( field )
Chris@0: # <<( header_and_field_array )
Chris@0: # <<( header_and_field_hash )
Chris@0: #
Chris@0: # If a two-element Array is provided, it is assumed to be a header and field
Chris@0: # and the pair is appended. A Hash works the same way with the key being
Chris@0: # the header and the value being the field. Anything else is assumed to be
Chris@0: # a lone field which is appended with a +nil+ header.
Chris@0: #
Chris@0: # This method returns the row for chaining.
Chris@0: #
Chris@0: def <<(arg)
Chris@0: if arg.is_a?(Array) and arg.size == 2 # appending a header and name
Chris@0: @row << arg
Chris@0: elsif arg.is_a?(Hash) # append header and name pairs
Chris@0: arg.each { |pair| @row << pair }
Chris@0: else # append field value
Chris@0: @row << [nil, arg]
Chris@0: end
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # A shortcut for appending multiple fields. Equivalent to:
Chris@0: #
Chris@0: # args.each { |arg| faster_csv_row << arg }
Chris@0: #
Chris@0: # This method returns the row for chaining.
Chris@0: #
Chris@0: def push(*args)
Chris@0: args.each { |arg| self << arg }
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # delete( header )
Chris@0: # delete( header, offset )
Chris@0: # delete( index )
Chris@0: #
Chris@0: # Used to remove a pair from the row by +header+ or +index+. The pair is
Chris@0: # located as described in FasterCSV::Row.field(). The deleted pair is
Chris@0: # returned, or +nil+ if a pair could not be found.
Chris@0: #
Chris@0: def delete(header_or_index, minimum_index = 0)
Chris@0: if header_or_index.is_a? Integer # by index
Chris@0: @row.delete_at(header_or_index)
Chris@0: else # by header
Chris@0: @row.delete_at(index(header_or_index, minimum_index))
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # The provided +block+ is passed a header and field for each pair in the row
Chris@0: # and expected to return +true+ or +false+, depending on whether the pair
Chris@0: # should be deleted.
Chris@0: #
Chris@0: # This method returns the row for chaining.
Chris@0: #
Chris@0: def delete_if(&block)
Chris@0: @row.delete_if(&block)
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method accepts any number of arguments which can be headers, indices,
Chris@0: # Ranges of either, or two-element Arrays containing a header and offset.
Chris@0: # Each argument will be replaced with a field lookup as described in
Chris@0: # FasterCSV::Row.field().
Chris@0: #
Chris@0: # If called with no arguments, all fields are returned.
Chris@0: #
Chris@0: def fields(*headers_and_or_indices)
Chris@0: if headers_and_or_indices.empty? # return all fields--no arguments
Chris@0: @row.map { |pair| pair.last }
Chris@0: else # or work like values_at()
Chris@0: headers_and_or_indices.inject(Array.new) do |all, h_or_i|
Chris@0: all + if h_or_i.is_a? Range
Chris@0: index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
Chris@0: index(h_or_i.begin)
Chris@0: index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
Chris@0: index(h_or_i.end)
Chris@0: new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
Chris@0: (index_begin..index_end)
Chris@0: fields.values_at(new_range)
Chris@0: else
Chris@0: [field(*Array(h_or_i))]
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: alias_method :values_at, :fields
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # index( header )
Chris@0: # index( header, offset )
Chris@0: #
Chris@0: # This method will return the index of a field with the provided +header+.
Chris@0: # The +offset+ can be used to locate duplicate header names, as described in
Chris@0: # FasterCSV::Row.field().
Chris@0: #
Chris@0: def index(header, minimum_index = 0)
Chris@0: # find the pair
Chris@0: index = headers[minimum_index..-1].index(header)
Chris@0: # return the index at the right offset, if we found one
Chris@0: index.nil? ? nil : index + minimum_index
Chris@0: end
Chris@0:
Chris@0: # Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
Chris@0: def header?(name)
Chris@0: headers.include? name
Chris@0: end
Chris@0: alias_method :include?, :header?
Chris@0:
Chris@0: #
Chris@0: # Returns +true+ if +data+ matches a field in this row, and +false+
Chris@0: # otherwise.
Chris@0: #
Chris@0: def field?(data)
Chris@0: fields.include? data
Chris@0: end
Chris@0:
Chris@0: include Enumerable
Chris@0:
Chris@0: #
Chris@0: # Yields each pair of the row as header and field tuples (much like
Chris@0: # iterating over a Hash).
Chris@0: #
Chris@0: # Support for Enumerable.
Chris@0: #
Chris@0: # This method returns the row for chaining.
Chris@0: #
Chris@0: def each(&block)
Chris@0: @row.each(&block)
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns +true+ if this row contains the same headers and fields in the
Chris@0: # same order as +other+.
Chris@0: #
Chris@0: def ==(other)
Chris@0: @row == other.row
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Collapses the row into a simple Hash. Be warning that this discards field
Chris@0: # order and clobbers duplicate fields.
Chris@0: #
Chris@0: def to_hash
Chris@0: # flatten just one level of the internal Array
Chris@0: Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns the row as a CSV String. Headers are not used. Equivalent to:
Chris@0: #
Chris@0: # faster_csv_row.fields.to_csv( options )
Chris@0: #
Chris@0: def to_csv(options = Hash.new)
Chris@0: fields.to_csv(options)
Chris@0: end
Chris@0: alias_method :to_s, :to_csv
Chris@0:
Chris@0: # A summary of fields, by header.
Chris@0: def inspect
Chris@0: str = "#<#{self.class}"
Chris@0: each do |header, field|
Chris@0: str << " #{header.is_a?(Symbol) ? header.to_s : header.inspect}:" <<
Chris@0: field.inspect
Chris@0: end
Chris@0: str << ">"
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # A FasterCSV::Table is a two-dimensional data structure for representing CSV
Chris@0: # documents. Tables allow you to work with the data by row or column,
Chris@0: # manipulate the data, and even convert the results back to CSV, if needed.
Chris@0: #
Chris@0: # All tables returned by FasterCSV will be constructed from this class, if
Chris@0: # header row processing is activated.
Chris@0: #
Chris@0: class Table
Chris@0: #
Chris@0: # Construct a new FasterCSV::Table from +array_of_rows+, which are expected
Chris@0: # to be FasterCSV::Row objects. All rows are assumed to have the same
Chris@0: # headers.
Chris@0: #
Chris@0: # A FasterCSV::Table object supports the following Array methods through
Chris@0: # delegation:
Chris@0: #
Chris@0: # * empty?()
Chris@0: # * length()
Chris@0: # * size()
Chris@0: #
Chris@0: def initialize(array_of_rows)
Chris@0: @table = array_of_rows
Chris@0: @mode = :col_or_row
Chris@0: end
Chris@0:
Chris@0: # The current access mode for indexing and iteration.
Chris@0: attr_reader :mode
Chris@0:
Chris@0: # Internal data format used to compare equality.
Chris@0: attr_reader :table
Chris@0: protected :table
Chris@0:
Chris@0: ### Array Delegation ###
Chris@0:
Chris@0: extend Forwardable
Chris@0: def_delegators :@table, :empty?, :length, :size
Chris@0:
Chris@0: #
Chris@0: # Returns a duplicate table object, in column mode. This is handy for
Chris@0: # chaining in a single call without changing the table mode, but be aware
Chris@0: # that this method can consume a fair amount of memory for bigger data sets.
Chris@0: #
Chris@0: # This method returns the duplicate table for chaining. Don't chain
Chris@0: # destructive methods (like []=()) this way though, since you are working
Chris@0: # with a duplicate.
Chris@0: #
Chris@0: def by_col
Chris@0: self.class.new(@table.dup).by_col!
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Switches the mode of this table to column mode. All calls to indexing and
Chris@0: # iteration methods will work with columns until the mode is changed again.
Chris@0: #
Chris@0: # This method returns the table and is safe to chain.
Chris@0: #
Chris@0: def by_col!
Chris@0: @mode = :col
Chris@0:
Chris@0: self
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns a duplicate table object, in mixed mode. This is handy for
Chris@0: # chaining in a single call without changing the table mode, but be aware
Chris@0: # that this method can consume a fair amount of memory for bigger data sets.
Chris@0: #
Chris@0: # This method returns the duplicate table for chaining. Don't chain
Chris@0: # destructive methods (like []=()) this way though, since you are working
Chris@0: # with a duplicate.
Chris@0: #
Chris@0: def by_col_or_row
Chris@0: self.class.new(@table.dup).by_col_or_row!
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Switches the mode of this table to mixed mode. All calls to indexing and
Chris@0: # iteration methods will use the default intelligent indexing system until
Chris@0: # the mode is changed again. In mixed mode an index is assumed to be a row
Chris@0: # reference while anything else is assumed to be column access by headers.
Chris@0: #
Chris@0: # This method returns the table and is safe to chain.
Chris@0: #
Chris@0: def by_col_or_row!
Chris@0: @mode = :col_or_row
Chris@0:
Chris@0: self
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns a duplicate table object, in row mode. This is handy for chaining
Chris@0: # in a single call without changing the table mode, but be aware that this
Chris@0: # method can consume a fair amount of memory for bigger data sets.
Chris@0: #
Chris@0: # This method returns the duplicate table for chaining. Don't chain
Chris@0: # destructive methods (like []=()) this way though, since you are working
Chris@0: # with a duplicate.
Chris@0: #
Chris@0: def by_row
Chris@0: self.class.new(@table.dup).by_row!
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Switches the mode of this table to row mode. All calls to indexing and
Chris@0: # iteration methods will work with rows until the mode is changed again.
Chris@0: #
Chris@0: # This method returns the table and is safe to chain.
Chris@0: #
Chris@0: def by_row!
Chris@0: @mode = :row
Chris@0:
Chris@0: self
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns the headers for the first row of this table (assumed to match all
Chris@0: # other rows). An empty Array is returned for empty tables.
Chris@0: #
Chris@0: def headers
Chris@0: if @table.empty?
Chris@0: Array.new
Chris@0: else
Chris@0: @table.first.headers
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # In the default mixed mode, this method returns rows for index access and
Chris@0: # columns for header access. You can force the index association by first
Chris@0: # calling by_col!() or by_row!().
Chris@0: #
Chris@0: # Columns are returned as an Array of values. Altering that Array has no
Chris@0: # effect on the table.
Chris@0: #
Chris@0: def [](index_or_header)
Chris@0: if @mode == :row or # by index
Chris@0: (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@0: @table[index_or_header]
Chris@0: else # by header
Chris@0: @table.map { |row| row[index_or_header] }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # In the default mixed mode, this method assigns rows for index access and
Chris@0: # columns for header access. You can force the index association by first
Chris@0: # calling by_col!() or by_row!().
Chris@0: #
Chris@0: # Rows may be set to an Array of values (which will inherit the table's
Chris@0: # headers()) or a FasterCSV::Row.
Chris@0: #
Chris@0: # Columns may be set to a single value, which is copied to each row of the
Chris@0: # column, or an Array of values. Arrays of values are assigned to rows top
Chris@0: # to bottom in row major order. Excess values are ignored and if the Array
Chris@0: # does not have a value for each row the extra rows will receive a +nil+.
Chris@0: #
Chris@0: # Assigning to an existing column or row clobbers the data. Assigning to
Chris@0: # new columns creates them at the right end of the table.
Chris@0: #
Chris@0: def []=(index_or_header, value)
Chris@0: if @mode == :row or # by index
Chris@0: (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@0: if value.is_a? Array
Chris@0: @table[index_or_header] = Row.new(headers, value)
Chris@0: else
Chris@0: @table[index_or_header] = value
Chris@0: end
Chris@0: else # set column
Chris@0: if value.is_a? Array # multiple values
Chris@0: @table.each_with_index do |row, i|
Chris@0: if row.header_row?
Chris@0: row[index_or_header] = index_or_header
Chris@0: else
Chris@0: row[index_or_header] = value[i]
Chris@0: end
Chris@0: end
Chris@0: else # repeated value
Chris@0: @table.each do |row|
Chris@0: if row.header_row?
Chris@0: row[index_or_header] = index_or_header
Chris@0: else
Chris@0: row[index_or_header] = value
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # The mixed mode default is to treat a list of indices as row access,
Chris@0: # returning the rows indicated. Anything else is considered columnar
Chris@0: # access. For columnar access, the return set has an Array for each row
Chris@0: # with the values indicated by the headers in each Array. You can force
Chris@0: # column or row mode using by_col!() or by_row!().
Chris@0: #
Chris@0: # You cannot mix column and row access.
Chris@0: #
Chris@0: def values_at(*indices_or_headers)
Chris@0: if @mode == :row or # by indices
Chris@0: ( @mode == :col_or_row and indices_or_headers.all? do |index|
Chris@0: index.is_a?(Integer) or
Chris@0: ( index.is_a?(Range) and
Chris@0: index.first.is_a?(Integer) and
Chris@0: index.last.is_a?(Integer) )
Chris@0: end )
Chris@0: @table.values_at(*indices_or_headers)
Chris@0: else # by headers
Chris@0: @table.map { |row| row.values_at(*indices_or_headers) }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Adds a new row to the bottom end of this table. You can provide an Array,
Chris@0: # which will be converted to a FasterCSV::Row (inheriting the table's
Chris@0: # headers()), or a FasterCSV::Row.
Chris@0: #
Chris@0: # This method returns the table for chaining.
Chris@0: #
Chris@0: def <<(row_or_array)
Chris@0: if row_or_array.is_a? Array # append Array
Chris@0: @table << Row.new(headers, row_or_array)
Chris@0: else # append Row
Chris@0: @table << row_or_array
Chris@0: end
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # A shortcut for appending multiple rows. Equivalent to:
Chris@0: #
Chris@0: # rows.each { |row| self << row }
Chris@0: #
Chris@0: # This method returns the table for chaining.
Chris@0: #
Chris@0: def push(*rows)
Chris@0: rows.each { |row| self << row }
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Removes and returns the indicated column or row. In the default mixed
Chris@0: # mode indices refer to rows and everything else is assumed to be a column
Chris@0: # header. Use by_col!() or by_row!() to force the lookup.
Chris@0: #
Chris@0: def delete(index_or_header)
Chris@0: if @mode == :row or # by index
Chris@0: (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@0: @table.delete_at(index_or_header)
Chris@0: else # by header
Chris@0: @table.map { |row| row.delete(index_or_header).last }
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Removes any column or row for which the block returns +true+. In the
Chris@0: # default mixed mode or row mode, iteration is the standard row major
Chris@0: # walking of rows. In column mode, interation will +yield+ two element
Chris@0: # tuples containing the column name and an Array of values for that column.
Chris@0: #
Chris@0: # This method returns the table for chaining.
Chris@0: #
Chris@0: def delete_if(&block)
Chris@0: if @mode == :row or @mode == :col_or_row # by index
Chris@0: @table.delete_if(&block)
Chris@0: else # by header
Chris@0: to_delete = Array.new
Chris@0: headers.each_with_index do |header, i|
Chris@0: to_delete << header if block[[header, self[header]]]
Chris@0: end
Chris@0: to_delete.map { |header| delete(header) }
Chris@0: end
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: include Enumerable
Chris@0:
Chris@0: #
Chris@0: # In the default mixed mode or row mode, iteration is the standard row major
Chris@0: # walking of rows. In column mode, interation will +yield+ two element
Chris@0: # tuples containing the column name and an Array of values for that column.
Chris@0: #
Chris@0: # This method returns the table for chaining.
Chris@0: #
Chris@0: def each(&block)
Chris@0: if @mode == :col
Chris@0: headers.each { |header| block[[header, self[header]]] }
Chris@0: else
Chris@0: @table.each(&block)
Chris@0: end
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0:
Chris@0: # Returns +true+ if all rows of this table ==() +other+'s rows.
Chris@0: def ==(other)
Chris@0: @table == other.table
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns the table as an Array of Arrays. Headers will be the first row,
Chris@0: # then all of the field rows will follow.
Chris@0: #
Chris@0: def to_a
Chris@0: @table.inject([headers]) do |array, row|
Chris@0: if row.header_row?
Chris@0: array
Chris@0: else
Chris@0: array + [row.fields]
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Returns the table as a complete CSV String. Headers will be listed first,
Chris@0: # then all of the field rows.
Chris@0: #
Chris@0: def to_csv(options = Hash.new)
Chris@0: @table.inject([headers.to_csv(options)]) do |rows, row|
Chris@0: if row.header_row?
Chris@0: rows
Chris@0: else
Chris@0: rows + [row.fields.to_csv(options)]
Chris@0: end
Chris@0: end.join
Chris@0: end
Chris@0: alias_method :to_s, :to_csv
Chris@0:
Chris@0: def inspect
Chris@0: "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>"
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # The error thrown when the parser encounters illegal CSV formatting.
Chris@0: class MalformedCSVError < RuntimeError; end
Chris@0:
Chris@0: #
Chris@0: # A FieldInfo Struct contains details about a field's position in the data
Chris@0: # source it was read from. FasterCSV will pass this Struct to some blocks
Chris@0: # that make decisions based on field structure. See
Chris@0: # FasterCSV.convert_fields() for an example.
Chris@0: #
Chris@0: # index:: The zero-based index of the field in its row.
Chris@0: # line:: The line of the data source this row is from.
Chris@0: # header:: The header for the column, when available.
Chris@0: #
Chris@0: FieldInfo = Struct.new(:index, :line, :header)
Chris@0:
Chris@0: # A Regexp used to find and convert some common Date formats.
Chris@0: DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
Chris@0: \d{4}-\d{2}-\d{2} )\z /x
Chris@0: # A Regexp used to find and convert some common DateTime formats.
Chris@0: DateTimeMatcher =
Chris@0: / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
Chris@0: \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
Chris@0: #
Chris@0: # This Hash holds the built-in converters of FasterCSV that can be accessed by
Chris@0: # name. You can select Converters with FasterCSV.convert() or through the
Chris@0: # +options+ Hash passed to FasterCSV::new().
Chris@0: #
Chris@0: # :integer:: Converts any field Integer() accepts.
Chris@0: # :float:: Converts any field Float() accepts.
Chris@0: # :numeric:: A combination of :integer
Chris@0: # and :float.
Chris@0: # :date:: Converts any field Date::parse() accepts.
Chris@0: # :date_time:: Converts any field DateTime::parse() accepts.
Chris@0: # :all:: All built-in converters. A combination of
Chris@0: # :date_time and :numeric.
Chris@0: #
Chris@0: # This Hash is intetionally left unfrozen and users should feel free to add
Chris@0: # values to it that can be accessed by all FasterCSV objects.
Chris@0: #
Chris@0: # To add a combo field, the value should be an Array of names. Combo fields
Chris@0: # can be nested with other combo fields.
Chris@0: #
Chris@0: Converters = { :integer => lambda { |f| Integer(f) rescue f },
Chris@0: :float => lambda { |f| Float(f) rescue f },
Chris@0: :numeric => [:integer, :float],
Chris@0: :date => lambda { |f|
Chris@0: f =~ DateMatcher ? (Date.parse(f) rescue f) : f
Chris@0: },
Chris@0: :date_time => lambda { |f|
Chris@0: f =~ DateTimeMatcher ? (DateTime.parse(f) rescue f) : f
Chris@0: },
Chris@0: :all => [:date_time, :numeric] }
Chris@0:
Chris@0: #
Chris@0: # This Hash holds the built-in header converters of FasterCSV that can be
Chris@0: # accessed by name. You can select HeaderConverters with
Chris@0: # FasterCSV.header_convert() or through the +options+ Hash passed to
Chris@0: # FasterCSV::new().
Chris@0: #
Chris@0: # :downcase:: Calls downcase() on the header String.
Chris@0: # :symbol:: The header String is downcased, spaces are
Chris@0: # replaced with underscores, non-word characters
Chris@0: # are dropped, and finally to_sym() is called.
Chris@0: #
Chris@0: # This Hash is intetionally left unfrozen and users should feel free to add
Chris@0: # values to it that can be accessed by all FasterCSV objects.
Chris@0: #
Chris@0: # To add a combo field, the value should be an Array of names. Combo fields
Chris@0: # can be nested with other combo fields.
Chris@0: #
Chris@0: HeaderConverters = {
Chris@0: :downcase => lambda { |h| h.downcase },
Chris@0: :symbol => lambda { |h|
Chris@0: h.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym
Chris@0: }
Chris@0: }
Chris@0:
Chris@0: #
Chris@0: # The options used when no overrides are given by calling code. They are:
Chris@0: #
Chris@0: # :col_sep:: ","
Chris@0: # :row_sep:: :auto
Chris@0: # :quote_char:: '"'
Chris@0: # :converters:: +nil+
Chris@0: # :unconverted_fields:: +nil+
Chris@0: # :headers:: +false+
Chris@0: # :return_headers:: +false+
Chris@0: # :header_converters:: +nil+
Chris@0: # :skip_blanks:: +false+
Chris@0: # :force_quotes:: +false+
Chris@0: #
Chris@0: DEFAULT_OPTIONS = { :col_sep => ",",
Chris@0: :row_sep => :auto,
Chris@0: :quote_char => '"',
Chris@0: :converters => nil,
Chris@0: :unconverted_fields => nil,
Chris@0: :headers => false,
Chris@0: :return_headers => false,
Chris@0: :header_converters => nil,
Chris@0: :skip_blanks => false,
Chris@0: :force_quotes => false }.freeze
Chris@0:
Chris@0: #
Chris@0: # This method will build a drop-in replacement for many of the standard CSV
Chris@0: # methods. It allows you to write code like:
Chris@0: #
Chris@0: # begin
Chris@0: # require "faster_csv"
Chris@0: # FasterCSV.build_csv_interface
Chris@0: # rescue LoadError
Chris@0: # require "csv"
Chris@0: # end
Chris@0: # # ... use CSV here ...
Chris@0: #
Chris@0: # This is not a complete interface with completely identical behavior.
Chris@0: # However, it is intended to be close enough that you won't notice the
Chris@0: # difference in most cases. CSV methods supported are:
Chris@0: #
Chris@0: # * foreach()
Chris@0: # * generate_line()
Chris@0: # * open()
Chris@0: # * parse()
Chris@0: # * parse_line()
Chris@0: # * readlines()
Chris@0: #
Chris@0: # Be warned that this interface is slower than vanilla FasterCSV due to the
Chris@0: # extra layer of method calls. Depending on usage, this can slow it down to
Chris@0: # near CSV speeds.
Chris@0: #
Chris@0: def self.build_csv_interface
Chris@0: Object.const_set(:CSV, Class.new).class_eval do
Chris@0: def self.foreach(path, rs = :auto, &block) # :nodoc:
Chris@0: FasterCSV.foreach(path, :row_sep => rs, &block)
Chris@0: end
Chris@0:
Chris@0: def self.generate_line(row, fs = ",", rs = "") # :nodoc:
Chris@0: FasterCSV.generate_line(row, :col_sep => fs, :row_sep => rs)
Chris@0: end
Chris@0:
Chris@0: def self.open(path, mode, fs = ",", rs = :auto, &block) # :nodoc:
Chris@0: if block and mode.include? "r"
Chris@0: FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs) do |csv|
Chris@0: csv.each(&block)
Chris@0: end
Chris@0: else
Chris@0: FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs, &block)
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: def self.parse(str_or_readable, fs = ",", rs = :auto, &block) # :nodoc:
Chris@0: FasterCSV.parse(str_or_readable, :col_sep => fs, :row_sep => rs, &block)
Chris@0: end
Chris@0:
Chris@0: def self.parse_line(src, fs = ",", rs = :auto) # :nodoc:
Chris@0: FasterCSV.parse_line(src, :col_sep => fs, :row_sep => rs)
Chris@0: end
Chris@0:
Chris@0: def self.readlines(path, rs = :auto) # :nodoc:
Chris@0: FasterCSV.readlines(path, :row_sep => rs)
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method allows you to serialize an Array of Ruby objects to a String or
Chris@0: # File of CSV data. This is not as powerful as Marshal or YAML, but perhaps
Chris@0: # useful for spreadsheet and database interaction.
Chris@0: #
Chris@0: # Out of the box, this method is intended to work with simple data objects or
Chris@0: # Structs. It will serialize a list of instance variables and/or
Chris@0: # Struct.members().
Chris@0: #
Chris@0: # If you need need more complicated serialization, you can control the process
Chris@0: # by adding methods to the class to be serialized.
Chris@0: #
Chris@0: # A class method csv_meta() is responsible for returning the first row of the
Chris@0: # document (as an Array). This row is considered to be a Hash of the form
Chris@0: # key_1,value_1,key_2,value_2,... FasterCSV::load() expects to find a class
Chris@0: # key with a value of the stringified class name and FasterCSV::dump() will
Chris@0: # create this, if you do not define this method. This method is only called
Chris@0: # on the first object of the Array.
Chris@0: #
Chris@0: # The next method you can provide is an instance method called csv_headers().
Chris@0: # This method is expected to return the second line of the document (again as
Chris@0: # an Array), which is to be used to give each column a header. By default,
Chris@0: # FasterCSV::load() will set an instance variable if the field header starts
Chris@0: # with an @ character or call send() passing the header as the method name and
Chris@0: # the field value as an argument. This method is only called on the first
Chris@0: # object of the Array.
Chris@0: #
Chris@0: # Finally, you can provide an instance method called csv_dump(), which will
Chris@0: # be passed the headers. This should return an Array of fields that can be
Chris@0: # serialized for this object. This method is called once for every object in
Chris@0: # the Array.
Chris@0: #
Chris@0: # The +io+ parameter can be used to serialize to a File, and +options+ can be
Chris@0: # anything FasterCSV::new() accepts.
Chris@0: #
Chris@0: def self.dump(ary_of_objs, io = "", options = Hash.new)
Chris@0: obj_template = ary_of_objs.first
Chris@0:
Chris@0: csv = FasterCSV.new(io, options)
Chris@0:
Chris@0: # write meta information
Chris@0: begin
Chris@0: csv << obj_template.class.csv_meta
Chris@0: rescue NoMethodError
Chris@0: csv << [:class, obj_template.class]
Chris@0: end
Chris@0:
Chris@0: # write headers
Chris@0: begin
Chris@0: headers = obj_template.csv_headers
Chris@0: rescue NoMethodError
Chris@0: headers = obj_template.instance_variables.sort
Chris@0: if obj_template.class.ancestors.find { |cls| cls.to_s =~ /\AStruct\b/ }
Chris@0: headers += obj_template.members.map { |mem| "#{mem}=" }.sort
Chris@0: end
Chris@0: end
Chris@0: csv << headers
Chris@0:
Chris@0: # serialize each object
Chris@0: ary_of_objs.each do |obj|
Chris@0: begin
Chris@0: csv << obj.csv_dump(headers)
Chris@0: rescue NoMethodError
Chris@0: csv << headers.map do |var|
Chris@0: if var[0] == ?@
Chris@0: obj.instance_variable_get(var)
Chris@0: else
Chris@0: obj[var[0..-2]]
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: if io.is_a? String
Chris@0: csv.string
Chris@0: else
Chris@0: csv.close
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # filter( options = Hash.new ) { |row| ... }
Chris@0: # filter( input, options = Hash.new ) { |row| ... }
Chris@0: # filter( input, output, options = Hash.new ) { |row| ... }
Chris@0: #
Chris@0: # This method is a convenience for building Unix-like filters for CSV data.
Chris@0: # Each row is yielded to the provided block which can alter it as needed.
Chris@0: # After the block returns, the row is appended to +output+ altered or not.
Chris@0: #
Chris@0: # The +input+ and +output+ arguments can be anything FasterCSV::new() accepts
Chris@0: # (generally String or IO objects). If not given, they default to
Chris@0: # ARGF and $stdout.
Chris@0: #
Chris@0: # The +options+ parameter is also filtered down to FasterCSV::new() after some
Chris@0: # clever key parsing. Any key beginning with :in_ or
Chris@0: # :input_ will have that leading identifier stripped and will only
Chris@0: # be used in the +options+ Hash for the +input+ object. Keys starting with
Chris@0: # :out_ or :output_ affect only +output+. All other keys
Chris@0: # are assigned to both objects.
Chris@0: #
Chris@0: # The :output_row_sep +option+ defaults to
Chris@0: # $INPUT_RECORD_SEPARATOR ($/).
Chris@0: #
Chris@0: def self.filter(*args)
Chris@0: # parse options for input, output, or both
Chris@0: in_options, out_options = Hash.new, {:row_sep => $INPUT_RECORD_SEPARATOR}
Chris@0: if args.last.is_a? Hash
Chris@0: args.pop.each do |key, value|
Chris@0: case key.to_s
Chris@0: when /\Ain(?:put)?_(.+)\Z/
Chris@0: in_options[$1.to_sym] = value
Chris@0: when /\Aout(?:put)?_(.+)\Z/
Chris@0: out_options[$1.to_sym] = value
Chris@0: else
Chris@0: in_options[key] = value
Chris@0: out_options[key] = value
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: # build input and output wrappers
Chris@0: input = FasterCSV.new(args.shift || ARGF, in_options)
Chris@0: output = FasterCSV.new(args.shift || $stdout, out_options)
Chris@0:
Chris@0: # read, yield, write
Chris@0: input.each do |row|
Chris@0: yield row
Chris@0: output << row
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method is intended as the primary interface for reading CSV files. You
Chris@0: # pass a +path+ and any +options+ you wish to set for the read. Each row of
Chris@0: # file will be passed to the provided +block+ in turn.
Chris@0: #
Chris@0: # The +options+ parameter can be anything FasterCSV::new() understands.
Chris@0: #
Chris@0: def self.foreach(path, options = Hash.new, &block)
Chris@0: open(path, "rb", options) do |csv|
Chris@0: csv.each(&block)
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # generate( str, options = Hash.new ) { |faster_csv| ... }
Chris@0: # generate( options = Hash.new ) { |faster_csv| ... }
Chris@0: #
Chris@0: # This method wraps a String you provide, or an empty default String, in a
Chris@0: # FasterCSV object which is passed to the provided block. You can use the
Chris@0: # block to append CSV rows to the String and when the block exits, the
Chris@0: # final String will be returned.
Chris@0: #
Chris@0: # Note that a passed String *is* modfied by this method. Call dup() before
Chris@0: # passing if you need a new String.
Chris@0: #
Chris@0: # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@0: #
Chris@0: def self.generate(*args)
Chris@0: # add a default empty String, if none was given
Chris@0: if args.first.is_a? String
Chris@0: io = StringIO.new(args.shift)
Chris@0: io.seek(0, IO::SEEK_END)
Chris@0: args.unshift(io)
Chris@0: else
Chris@0: args.unshift("")
Chris@0: end
Chris@0: faster_csv = new(*args) # wrap
Chris@0: yield faster_csv # yield for appending
Chris@0: faster_csv.string # return final String
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method is a shortcut for converting a single row (Array) into a CSV
Chris@0: # String.
Chris@0: #
Chris@0: # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@0: #
Chris@0: # The :row_sep +option+ defaults to $INPUT_RECORD_SEPARATOR
Chris@0: # ($/) when calling this method.
Chris@0: #
Chris@0: def self.generate_line(row, options = Hash.new)
Chris@0: options = {:row_sep => $INPUT_RECORD_SEPARATOR}.merge(options)
Chris@0: (new("", options) << row).string
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method will return a FasterCSV instance, just like FasterCSV::new(),
Chris@0: # but the instance will be cached and returned for all future calls to this
Chris@0: # method for the same +data+ object (tested by Object#object_id()) with the
Chris@0: # same +options+.
Chris@0: #
Chris@0: # If a block is given, the instance is passed to the block and the return
Chris@0: # value becomes the return value of the block.
Chris@0: #
Chris@0: def self.instance(data = $stdout, options = Hash.new)
Chris@0: # create a _signature_ for this method call, data object and options
Chris@0: sig = [data.object_id] +
Chris@0: options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })
Chris@0:
Chris@0: # fetch or create the instance for this signature
Chris@0: @@instances ||= Hash.new
Chris@0: instance = (@@instances[sig] ||= new(data, options))
Chris@0:
Chris@0: if block_given?
Chris@0: yield instance # run block, if given, returning result
Chris@0: else
Chris@0: instance # or return the instance
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method is the reading counterpart to FasterCSV::dump(). See that
Chris@0: # method for a detailed description of the process.
Chris@0: #
Chris@0: # You can customize loading by adding a class method called csv_load() which
Chris@0: # will be passed a Hash of meta information, an Array of headers, and an Array
Chris@0: # of fields for the object the method is expected to return.
Chris@0: #
Chris@0: # Remember that all fields will be Strings after this load. If you need
Chris@0: # something else, use +options+ to setup converters or provide a custom
Chris@0: # csv_load() implementation.
Chris@0: #
Chris@0: def self.load(io_or_str, options = Hash.new)
Chris@0: csv = FasterCSV.new(io_or_str, options)
Chris@0:
Chris@0: # load meta information
Chris@0: meta = Hash[*csv.shift]
Chris@0: cls = meta["class"].split("::").inject(Object) do |c, const|
Chris@0: c.const_get(const)
Chris@0: end
Chris@0:
Chris@0: # load headers
Chris@0: headers = csv.shift
Chris@0:
Chris@0: # unserialize each object stored in the file
Chris@0: results = csv.inject(Array.new) do |all, row|
Chris@0: begin
Chris@0: obj = cls.csv_load(meta, headers, row)
Chris@0: rescue NoMethodError
Chris@0: obj = cls.allocate
Chris@0: headers.zip(row) do |name, value|
Chris@0: if name[0] == ?@
Chris@0: obj.instance_variable_set(name, value)
Chris@0: else
Chris@0: obj.send(name, value)
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: all << obj
Chris@0: end
Chris@0:
Chris@0: csv.close unless io_or_str.is_a? String
Chris@0:
Chris@0: results
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # open( filename, mode="rb", options = Hash.new ) { |faster_csv| ... }
Chris@0: # open( filename, mode="rb", options = Hash.new )
Chris@0: #
Chris@0: # This method opens an IO object, and wraps that with FasterCSV. This is
Chris@0: # intended as the primary interface for writing a CSV file.
Chris@0: #
Chris@0: # You may pass any +args+ Ruby's open() understands followed by an optional
Chris@0: # Hash containing any +options+ FasterCSV::new() understands.
Chris@0: #
Chris@0: # This method works like Ruby's open() call, in that it will pass a FasterCSV
Chris@0: # object to a provided block and close it when the block termminates, or it
Chris@0: # will return the FasterCSV object when no block is provided. (*Note*: This
Chris@0: # is different from the standard CSV library which passes rows to the block.
Chris@0: # Use FasterCSV::foreach() for that behavior.)
Chris@0: #
Chris@0: # An opened FasterCSV object will delegate to many IO methods, for
Chris@0: # convenience. You may call:
Chris@0: #
Chris@0: # * binmode()
Chris@0: # * close()
Chris@0: # * close_read()
Chris@0: # * close_write()
Chris@0: # * closed?()
Chris@0: # * eof()
Chris@0: # * eof?()
Chris@0: # * fcntl()
Chris@0: # * fileno()
Chris@0: # * flush()
Chris@0: # * fsync()
Chris@0: # * ioctl()
Chris@0: # * isatty()
Chris@0: # * pid()
Chris@0: # * pos()
Chris@0: # * reopen()
Chris@0: # * seek()
Chris@0: # * stat()
Chris@0: # * sync()
Chris@0: # * sync=()
Chris@0: # * tell()
Chris@0: # * to_i()
Chris@0: # * to_io()
Chris@0: # * tty?()
Chris@0: #
Chris@0: def self.open(*args)
Chris@0: # find the +options+ Hash
Chris@0: options = if args.last.is_a? Hash then args.pop else Hash.new end
Chris@0: # default to a binary open mode
Chris@0: args << "rb" if args.size == 1
Chris@0: # wrap a File opened with the remaining +args+
Chris@0: csv = new(File.open(*args), options)
Chris@0:
Chris@0: # handle blocks like Ruby's open(), not like the CSV library
Chris@0: if block_given?
Chris@0: begin
Chris@0: yield csv
Chris@0: ensure
Chris@0: csv.close
Chris@0: end
Chris@0: else
Chris@0: csv
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # parse( str, options = Hash.new ) { |row| ... }
Chris@0: # parse( str, options = Hash.new )
Chris@0: #
Chris@0: # This method can be used to easily parse CSV out of a String. You may either
Chris@0: # provide a +block+ which will be called with each row of the String in turn,
Chris@0: # or just use the returned Array of Arrays (when no +block+ is given).
Chris@0: #
Chris@0: # You pass your +str+ to read from, and an optional +options+ Hash containing
Chris@0: # anything FasterCSV::new() understands.
Chris@0: #
Chris@0: def self.parse(*args, &block)
Chris@0: csv = new(*args)
Chris@0: if block.nil? # slurp contents, if no block is given
Chris@0: begin
Chris@0: csv.read
Chris@0: ensure
Chris@0: csv.close
Chris@0: end
Chris@0: else # or pass each row to a provided block
Chris@0: csv.each(&block)
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This method is a shortcut for converting a single line of a CSV String into
Chris@0: # a into an Array. Note that if +line+ contains multiple rows, anything
Chris@0: # beyond the first row is ignored.
Chris@0: #
Chris@0: # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@0: #
Chris@0: def self.parse_line(line, options = Hash.new)
Chris@0: new(line, options).shift
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the
Chris@0: # file and any +options+ FasterCSV::new() understands.
Chris@0: #
Chris@0: def self.read(path, options = Hash.new)
Chris@0: open(path, "rb", options) { |csv| csv.read }
Chris@0: end
Chris@0:
Chris@0: # Alias for FasterCSV::read().
Chris@0: def self.readlines(*args)
Chris@0: read(*args)
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # A shortcut for:
Chris@0: #
Chris@0: # FasterCSV.read( path, { :headers => true,
Chris@0: # :converters => :numeric,
Chris@0: # :header_converters => :symbol }.merge(options) )
Chris@0: #
Chris@0: def self.table(path, options = Hash.new)
Chris@0: read( path, { :headers => true,
Chris@0: :converters => :numeric,
Chris@0: :header_converters => :symbol }.merge(options) )
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This constructor will wrap either a String or IO object passed in +data+ for
Chris@0: # reading and/or writing. In addition to the FasterCSV instance methods,
Chris@0: # several IO methods are delegated. (See FasterCSV::open() for a complete
Chris@0: # list.) If you pass a String for +data+, you can later retrieve it (after
Chris@0: # writing to it, for example) with FasterCSV.string().
Chris@0: #
Chris@0: # Note that a wrapped String will be positioned at at the beginning (for
Chris@0: # reading). If you want it at the end (for writing), use
Chris@0: # FasterCSV::generate(). If you want any other positioning, pass a preset
Chris@0: # StringIO object instead.
Chris@0: #
Chris@0: # You may set any reading and/or writing preferences in the +options+ Hash.
Chris@0: # Available options are:
Chris@0: #
Chris@0: # :col_sep:: The String placed between each field.
Chris@0: # :row_sep:: The String appended to the end of each
Chris@0: # row. This can be set to the special
Chris@0: # :auto setting, which requests
Chris@0: # that FasterCSV automatically discover
Chris@0: # this from the data. Auto-discovery
Chris@0: # reads ahead in the data looking for
Chris@0: # the next "\r\n",
Chris@0: # "\n", or "\r"
Chris@0: # sequence. A sequence will be selected
Chris@0: # even if it occurs in a quoted field,
Chris@0: # assuming that you would have the same
Chris@0: # line endings there. If none of those
Chris@0: # sequences is found, +data+ is
Chris@0: # ARGF, STDIN,
Chris@0: # STDOUT, or STDERR,
Chris@0: # or the stream is only available for
Chris@0: # output, the default
Chris@0: # $INPUT_RECORD_SEPARATOR
Chris@0: # ($/) is used. Obviously,
Chris@0: # discovery takes a little time. Set
Chris@0: # manually if speed is important. Also
Chris@0: # note that IO objects should be opened
Chris@0: # in binary mode on Windows if this
Chris@0: # feature will be used as the
Chris@0: # line-ending translation can cause
Chris@0: # problems with resetting the document
Chris@0: # position to where it was before the
Chris@0: # read ahead.
Chris@0: # :quote_char:: The character used to quote fields.
Chris@0: # This has to be a single character
Chris@0: # String. This is useful for
Chris@0: # application that incorrectly use
Chris@0: # ' as the quote character
Chris@0: # instead of the correct ".
Chris@0: # FasterCSV will always consider a
Chris@0: # double sequence this character to be
Chris@0: # an escaped quote.
Chris@0: # :encoding:: The encoding to use when parsing the
Chris@0: # file. Defaults to your $KDOCE
Chris@0: # setting. Valid values: `n’ or
Chris@0: # `N’ for none, `e’ or
Chris@0: # `E’ for EUC, `s’ or
Chris@0: # `S’ for SJIS, and
Chris@0: # `u’ or `U’ for UTF-8
Chris@0: # (see Regexp.new()).
Chris@0: # :field_size_limit:: This is a maximum size FasterCSV will
Chris@0: # read ahead looking for the closing
Chris@0: # quote for a field. (In truth, it
Chris@0: # reads to the first line ending beyond
Chris@0: # this size.) If a quote cannot be
Chris@0: # found within the limit FasterCSV will
Chris@0: # raise a MalformedCSVError, assuming
Chris@0: # the data is faulty. You can use this
Chris@0: # limit to prevent what are effectively
Chris@0: # DoS attacks on the parser. However,
Chris@0: # this limit can cause a legitimate
Chris@0: # parse to fail and thus is set to
Chris@0: # +nil+, or off, by default.
Chris@0: # :converters:: An Array of names from the Converters
Chris@0: # Hash and/or lambdas that handle custom
Chris@0: # conversion. A single converter
Chris@0: # doesn't have to be in an Array.
Chris@0: # :unconverted_fields:: If set to +true+, an
Chris@0: # unconverted_fields() method will be
Chris@0: # added to all returned rows (Array or
Chris@0: # FasterCSV::Row) that will return the
Chris@0: # fields as they were before convertion.
Chris@0: # Note that :headers supplied
Chris@0: # by Array or String were not fields of
Chris@0: # the document and thus will have an
Chris@0: # empty Array attached.
Chris@0: # :headers:: If set to :first_row or
Chris@0: # +true+, the initial row of the CSV
Chris@0: # file will be treated as a row of
Chris@0: # headers. If set to an Array, the
Chris@0: # contents will be used as the headers.
Chris@0: # If set to a String, the String is run
Chris@0: # through a call of
Chris@0: # FasterCSV::parse_line() with the same
Chris@0: # :col_sep, :row_sep,
Chris@0: # and :quote_char as this
Chris@0: # instance to produce an Array of
Chris@0: # headers. This setting causes
Chris@0: # FasterCSV.shift() to return rows as
Chris@0: # FasterCSV::Row objects instead of
Chris@0: # Arrays and FasterCSV.read() to return
Chris@0: # FasterCSV::Table objects instead of
Chris@0: # an Array of Arrays.
Chris@0: # :return_headers:: When +false+, header rows are silently
Chris@0: # swallowed. If set to +true+, header
Chris@0: # rows are returned in a FasterCSV::Row
Chris@0: # object with identical headers and
Chris@0: # fields (save that the fields do not go
Chris@0: # through the converters).
Chris@0: # :write_headers:: When +true+ and :headers is
Chris@0: # set, a header row will be added to the
Chris@0: # output.
Chris@0: # :header_converters:: Identical in functionality to
Chris@0: # :converters save that the
Chris@0: # conversions are only made to header
Chris@0: # rows.
Chris@0: # :skip_blanks:: When set to a +true+ value, FasterCSV
Chris@0: # will skip over any rows with no
Chris@0: # content.
Chris@0: # :force_quotes:: When set to a +true+ value, FasterCSV
Chris@0: # will quote all CSV fields it creates.
Chris@0: #
Chris@0: # See FasterCSV::DEFAULT_OPTIONS for the default settings.
Chris@0: #
Chris@0: # Options cannot be overriden in the instance methods for performance reasons,
Chris@0: # so be sure to set what you want here.
Chris@0: #
Chris@0: def initialize(data, options = Hash.new)
Chris@0: # build the options for this read/write
Chris@0: options = DEFAULT_OPTIONS.merge(options)
Chris@0:
Chris@0: # create the IO object we will read from
Chris@0: @io = if data.is_a? String then StringIO.new(data) else data end
Chris@0:
Chris@0: init_separators(options)
Chris@0: init_parsers(options)
Chris@0: init_converters(options)
Chris@0: init_headers(options)
Chris@0:
Chris@0: unless options.empty?
Chris@0: raise ArgumentError, "Unknown options: #{options.keys.join(', ')}."
Chris@0: end
Chris@0:
Chris@0: # track our own lineno since IO gets confused about line-ends is CSV fields
Chris@0: @lineno = 0
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # The line number of the last row read from this file. Fields with nested
Chris@0: # line-end characters will not affect this count.
Chris@0: #
Chris@0: attr_reader :lineno
Chris@0:
Chris@0: ### IO and StringIO Delegation ###
Chris@0:
Chris@0: extend Forwardable
Chris@0: def_delegators :@io, :binmode, :close, :close_read, :close_write, :closed?,
Chris@0: :eof, :eof?, :fcntl, :fileno, :flush, :fsync, :ioctl,
Chris@0: :isatty, :pid, :pos, :reopen, :seek, :stat, :string,
Chris@0: :sync, :sync=, :tell, :to_i, :to_io, :tty?
Chris@0:
Chris@0: # Rewinds the underlying IO object and resets FasterCSV's lineno() counter.
Chris@0: def rewind
Chris@0: @headers = nil
Chris@0: @lineno = 0
Chris@0:
Chris@0: @io.rewind
Chris@0: end
Chris@0:
Chris@0: ### End Delegation ###
Chris@0:
Chris@0: #
Chris@0: # The primary write method for wrapped Strings and IOs, +row+ (an Array or
Chris@0: # FasterCSV::Row) is converted to CSV and appended to the data source. When a
Chris@0: # FasterCSV::Row is passed, only the row's fields() are appended to the
Chris@0: # output.
Chris@0: #
Chris@0: # The data source must be open for writing.
Chris@0: #
Chris@0: def <<(row)
Chris@0: # make sure headers have been assigned
Chris@0: if header_row? and [Array, String].include? @use_headers.class
Chris@0: parse_headers # won't read data for Array or String
Chris@0: self << @headers if @write_headers
Chris@0: end
Chris@0:
Chris@0: # Handle FasterCSV::Row objects and Hashes
Chris@0: row = case row
Chris@0: when self.class::Row then row.fields
Chris@0: when Hash then @headers.map { |header| row[header] }
Chris@0: else row
Chris@0: end
Chris@0:
Chris@0: @headers = row if header_row?
Chris@0: @lineno += 1
Chris@0:
Chris@0: @io << row.map(&@quote).join(@col_sep) + @row_sep # quote and separate
Chris@0:
Chris@0: self # for chaining
Chris@0: end
Chris@0: alias_method :add_row, :<<
Chris@0: alias_method :puts, :<<
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # convert( name )
Chris@0: # convert { |field| ... }
Chris@0: # convert { |field, field_info| ... }
Chris@0: #
Chris@0: # You can use this method to install a FasterCSV::Converters built-in, or
Chris@0: # provide a block that handles a custom conversion.
Chris@0: #
Chris@0: # If you provide a block that takes one argument, it will be passed the field
Chris@0: # and is expected to return the converted value or the field itself. If your
Chris@0: # block takes two arguments, it will also be passed a FieldInfo Struct,
Chris@0: # containing details about the field. Again, the block should return a
Chris@0: # converted field or the field itself.
Chris@0: #
Chris@0: def convert(name = nil, &converter)
Chris@0: add_converter(:converters, self.class::Converters, name, &converter)
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # :call-seq:
Chris@0: # header_convert( name )
Chris@0: # header_convert { |field| ... }
Chris@0: # header_convert { |field, field_info| ... }
Chris@0: #
Chris@0: # Identical to FasterCSV.convert(), but for header rows.
Chris@0: #
Chris@0: # Note that this method must be called before header rows are read to have any
Chris@0: # effect.
Chris@0: #
Chris@0: def header_convert(name = nil, &converter)
Chris@0: add_converter( :header_converters,
Chris@0: self.class::HeaderConverters,
Chris@0: name,
Chris@0: &converter )
Chris@0: end
Chris@0:
Chris@0: include Enumerable
Chris@0:
Chris@0: #
Chris@0: # Yields each row of the data source in turn.
Chris@0: #
Chris@0: # Support for Enumerable.
Chris@0: #
Chris@0: # The data source must be open for reading.
Chris@0: #
Chris@0: def each
Chris@0: while row = shift
Chris@0: yield row
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Slurps the remaining rows and returns an Array of Arrays.
Chris@0: #
Chris@0: # The data source must be open for reading.
Chris@0: #
Chris@0: def read
Chris@0: rows = to_a
Chris@0: if @use_headers
Chris@0: Table.new(rows)
Chris@0: else
Chris@0: rows
Chris@0: end
Chris@0: end
Chris@0: alias_method :readlines, :read
Chris@0:
Chris@0: # Returns +true+ if the next row read will be a header row.
Chris@0: def header_row?
Chris@0: @use_headers and @headers.nil?
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # The primary read method for wrapped Strings and IOs, a single row is pulled
Chris@0: # from the data source, parsed and returned as an Array of fields (if header
Chris@0: # rows are not used) or a FasterCSV::Row (when header rows are used).
Chris@0: #
Chris@0: # The data source must be open for reading.
Chris@0: #
Chris@0: def shift
Chris@0: #########################################################################
Chris@0: ### This method is purposefully kept a bit long as simple conditional ###
Chris@0: ### checks are faster than numerous (expensive) method calls. ###
Chris@0: #########################################################################
Chris@0:
Chris@0: # handle headers not based on document content
Chris@0: if header_row? and @return_headers and
Chris@0: [Array, String].include? @use_headers.class
Chris@0: if @unconverted_fields
Chris@0: return add_unconverted_fields(parse_headers, Array.new)
Chris@0: else
Chris@0: return parse_headers
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # begin with a blank line, so we can always add to it
Chris@0: line = String.new
Chris@0:
Chris@0: #
Chris@0: # it can take multiple calls to @io.gets() to get a full line,
Chris@0: # because of \r and/or \n characters embedded in quoted fields
Chris@0: #
Chris@0: loop do
Chris@0: # add another read to the line
Chris@0: begin
Chris@0: line += @io.gets(@row_sep)
Chris@0: rescue
Chris@0: return nil
Chris@0: end
Chris@0: # copy the line so we can chop it up in parsing
Chris@0: parse = line.dup
Chris@0: parse.sub!(@parsers[:line_end], "")
Chris@0:
Chris@0: #
Chris@0: # I believe a blank line should be an Array.new, not
Chris@0: # CSV's [nil]
Chris@0: #
Chris@0: if parse.empty?
Chris@0: @lineno += 1
Chris@0: if @skip_blanks
Chris@0: line = ""
Chris@0: next
Chris@0: elsif @unconverted_fields
Chris@0: return add_unconverted_fields(Array.new, Array.new)
Chris@0: elsif @use_headers
Chris@0: return FasterCSV::Row.new(Array.new, Array.new)
Chris@0: else
Chris@0: return Array.new
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # parse the fields with a mix of String#split and regular expressions
Chris@0: csv = Array.new
Chris@0: current_field = String.new
Chris@0: field_quotes = 0
Chris@0: parse.split(@col_sep, -1).each do |match|
Chris@0: if current_field.empty? && match.count(@quote_and_newlines).zero?
Chris@0: csv << (match.empty? ? nil : match)
Chris@0: elsif(current_field.empty? ? match[0] : current_field[0]) == @quote_char[0]
Chris@0: current_field << match
Chris@0: field_quotes += match.count(@quote_char)
Chris@0: if field_quotes % 2 == 0
Chris@0: in_quotes = current_field[@parsers[:quoted_field], 1]
Chris@0: raise MalformedCSVError unless in_quotes
Chris@0: current_field = in_quotes
Chris@0: current_field.gsub!(@quote_char * 2, @quote_char) # unescape contents
Chris@0: csv << current_field
Chris@0: current_field = String.new
Chris@0: field_quotes = 0
Chris@0: else # we found a quoted field that spans multiple lines
Chris@0: current_field << @col_sep
Chris@0: end
Chris@0: elsif match.count("\r\n").zero?
Chris@0: raise MalformedCSVError, "Illegal quoting on line #{lineno + 1}."
Chris@0: else
Chris@0: raise MalformedCSVError, "Unquoted fields do not allow " +
Chris@0: "\\r or \\n (line #{lineno + 1})."
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # if parse is empty?(), we found all the fields on the line...
Chris@0: if field_quotes % 2 == 0
Chris@0: @lineno += 1
Chris@0:
Chris@0: # save fields unconverted fields, if needed...
Chris@0: unconverted = csv.dup if @unconverted_fields
Chris@0:
Chris@0: # convert fields, if needed...
Chris@0: csv = convert_fields(csv) unless @use_headers or @converters.empty?
Chris@0: # parse out header rows and handle FasterCSV::Row conversions...
Chris@0: csv = parse_headers(csv) if @use_headers
Chris@0:
Chris@0: # inject unconverted fields and accessor, if requested...
Chris@0: if @unconverted_fields and not csv.respond_to? :unconverted_fields
Chris@0: add_unconverted_fields(csv, unconverted)
Chris@0: end
Chris@0:
Chris@0: # return the results
Chris@0: break csv
Chris@0: end
Chris@0: # if we're not empty?() but at eof?(), a quoted field wasn't closed...
Chris@0: if @io.eof?
Chris@0: raise MalformedCSVError, "Unclosed quoted field on line #{lineno + 1}."
Chris@0: elsif @field_size_limit and current_field.size >= @field_size_limit
Chris@0: raise MalformedCSVError, "Field size exceeded on line #{lineno + 1}."
Chris@0: end
Chris@0: # otherwise, we need to loop and pull some more data to complete the row
Chris@0: end
Chris@0: end
Chris@0: alias_method :gets, :shift
Chris@0: alias_method :readline, :shift
Chris@0:
Chris@0: # Returns a simplified description of the key FasterCSV attributes.
Chris@0: def inspect
Chris@0: str = "<##{self.class} io_type:"
Chris@0: # show type of wrapped IO
Chris@0: if @io == $stdout then str << "$stdout"
Chris@0: elsif @io == $stdin then str << "$stdin"
Chris@0: elsif @io == $stderr then str << "$stderr"
Chris@0: else str << @io.class.to_s
Chris@0: end
Chris@0: # show IO.path(), if available
Chris@0: if @io.respond_to?(:path) and (p = @io.path)
Chris@0: str << " io_path:#{p.inspect}"
Chris@0: end
Chris@0: # show other attributes
Chris@0: %w[ lineno col_sep row_sep
Chris@0: quote_char skip_blanks encoding ].each do |attr_name|
Chris@0: if a = instance_variable_get("@#{attr_name}")
Chris@0: str << " #{attr_name}:#{a.inspect}"
Chris@0: end
Chris@0: end
Chris@0: if @use_headers
Chris@0: str << " headers:#{(@headers || true).inspect}"
Chris@0: end
Chris@0: str << ">"
Chris@0: end
Chris@0:
Chris@0: private
Chris@0:
Chris@0: #
Chris@0: # Stores the indicated separators for later use.
Chris@0: #
Chris@0: # If auto-discovery was requested for @row_sep, this method will read
Chris@0: # ahead in the @io and try to find one. +ARGF+, +STDIN+, +STDOUT+,
Chris@0: # +STDERR+ and any stream open for output only with a default
Chris@0: # @row_sep of $INPUT_RECORD_SEPARATOR ($/).
Chris@0: #
Chris@0: # This method also establishes the quoting rules used for CSV output.
Chris@0: #
Chris@0: def init_separators(options)
Chris@0: # store the selected separators
Chris@0: @col_sep = options.delete(:col_sep)
Chris@0: @row_sep = options.delete(:row_sep)
Chris@0: @quote_char = options.delete(:quote_char)
Chris@0: @quote_and_newlines = "#{@quote_char}\r\n"
Chris@0:
Chris@0: if @quote_char.length != 1
Chris@0: raise ArgumentError, ":quote_char has to be a single character String"
Chris@0: end
Chris@0:
Chris@0: # automatically discover row separator when requested
Chris@0: if @row_sep == :auto
Chris@0: if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or
Chris@0: (defined?(Zlib) and @io.class == Zlib::GzipWriter)
Chris@0: @row_sep = $INPUT_RECORD_SEPARATOR
Chris@0: else
Chris@0: begin
Chris@0: saved_pos = @io.pos # remember where we were
Chris@0: while @row_sep == :auto
Chris@0: #
Chris@0: # if we run out of data, it's probably a single line
Chris@0: # (use a sensible default)
Chris@0: #
Chris@0: if @io.eof?
Chris@0: @row_sep = $INPUT_RECORD_SEPARATOR
Chris@0: break
Chris@0: end
Chris@0:
Chris@0: # read ahead a bit
Chris@0: sample = @io.read(1024)
Chris@0: sample += @io.read(1) if sample[-1..-1] == "\r" and not @io.eof?
Chris@0:
Chris@0: # try to find a standard separator
Chris@0: if sample =~ /\r\n?|\n/
Chris@0: @row_sep = $&
Chris@0: break
Chris@0: end
Chris@0: end
Chris@0: # tricky seek() clone to work around GzipReader's lack of seek()
Chris@0: @io.rewind
Chris@0: # reset back to the remembered position
Chris@0: while saved_pos > 1024 # avoid loading a lot of data into memory
Chris@0: @io.read(1024)
Chris@0: saved_pos -= 1024
Chris@0: end
Chris@0: @io.read(saved_pos) if saved_pos.nonzero?
Chris@0: rescue IOError # stream not opened for reading
Chris@0: @row_sep = $INPUT_RECORD_SEPARATOR
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # establish quoting rules
Chris@0: do_quote = lambda do |field|
Chris@0: @quote_char +
Chris@0: String(field).gsub(@quote_char, @quote_char * 2) +
Chris@0: @quote_char
Chris@0: end
Chris@0: @quote = if options.delete(:force_quotes)
Chris@0: do_quote
Chris@0: else
Chris@0: lambda do |field|
Chris@0: if field.nil? # represent +nil+ fields as empty unquoted fields
Chris@0: ""
Chris@0: else
Chris@0: field = String(field) # Stringify fields
Chris@0: # represent empty fields as empty quoted fields
Chris@0: if field.empty? or
Chris@0: field.count("\r\n#{@col_sep}#{@quote_char}").nonzero?
Chris@0: do_quote.call(field)
Chris@0: else
Chris@0: field # unquoted field
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # Pre-compiles parsers and stores them by name for access during reads.
Chris@0: def init_parsers(options)
Chris@0: # store the parser behaviors
Chris@0: @skip_blanks = options.delete(:skip_blanks)
Chris@0: @encoding = options.delete(:encoding) # nil will use $KCODE
Chris@0: @field_size_limit = options.delete(:field_size_limit)
Chris@0:
Chris@0: # prebuild Regexps for faster parsing
Chris@0: esc_col_sep = Regexp.escape(@col_sep)
Chris@0: esc_row_sep = Regexp.escape(@row_sep)
Chris@0: esc_quote = Regexp.escape(@quote_char)
Chris@0: @parsers = {
Chris@0: :any_field => Regexp.new( "[^#{esc_col_sep}]+",
Chris@0: Regexp::MULTILINE,
Chris@0: @encoding ),
Chris@0: :quoted_field => Regexp.new( "^#{esc_quote}(.*)#{esc_quote}$",
Chris@0: Regexp::MULTILINE,
Chris@0: @encoding ),
Chris@0: # safer than chomp!()
Chris@0: :line_end => Regexp.new("#{esc_row_sep}\\z", nil, @encoding)
Chris@0: }
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Loads any converters requested during construction.
Chris@0: #
Chris@0: # If +field_name+ is set :converters (the default) field converters
Chris@0: # are set. When +field_name+ is :header_converters header converters
Chris@0: # are added instead.
Chris@0: #
Chris@0: # The :unconverted_fields option is also actived for
Chris@0: # :converters calls, if requested.
Chris@0: #
Chris@0: def init_converters(options, field_name = :converters)
Chris@0: if field_name == :converters
Chris@0: @unconverted_fields = options.delete(:unconverted_fields)
Chris@0: end
Chris@0:
Chris@0: instance_variable_set("@#{field_name}", Array.new)
Chris@0:
Chris@0: # find the correct method to add the coverters
Chris@0: convert = method(field_name.to_s.sub(/ers\Z/, ""))
Chris@0:
Chris@0: # load converters
Chris@0: unless options[field_name].nil?
Chris@0: # allow a single converter not wrapped in an Array
Chris@0: unless options[field_name].is_a? Array
Chris@0: options[field_name] = [options[field_name]]
Chris@0: end
Chris@0: # load each converter...
Chris@0: options[field_name].each do |converter|
Chris@0: if converter.is_a? Proc # custom code block
Chris@0: convert.call(&converter)
Chris@0: else # by name
Chris@0: convert.call(converter)
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: options.delete(field_name)
Chris@0: end
Chris@0:
Chris@0: # Stores header row settings and loads header converters, if needed.
Chris@0: def init_headers(options)
Chris@0: @use_headers = options.delete(:headers)
Chris@0: @return_headers = options.delete(:return_headers)
Chris@0: @write_headers = options.delete(:write_headers)
Chris@0:
Chris@0: # headers must be delayed until shift(), in case they need a row of content
Chris@0: @headers = nil
Chris@0:
Chris@0: init_converters(options, :header_converters)
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # The actual work method for adding converters, used by both
Chris@0: # FasterCSV.convert() and FasterCSV.header_convert().
Chris@0: #
Chris@0: # This method requires the +var_name+ of the instance variable to place the
Chris@0: # converters in, the +const+ Hash to lookup named converters in, and the
Chris@0: # normal parameters of the FasterCSV.convert() and FasterCSV.header_convert()
Chris@0: # methods.
Chris@0: #
Chris@0: def add_converter(var_name, const, name = nil, &converter)
Chris@0: if name.nil? # custom converter
Chris@0: instance_variable_get("@#{var_name}") << converter
Chris@0: else # named converter
Chris@0: combo = const[name]
Chris@0: case combo
Chris@0: when Array # combo converter
Chris@0: combo.each do |converter_name|
Chris@0: add_converter(var_name, const, converter_name)
Chris@0: end
Chris@0: else # individual named converter
Chris@0: instance_variable_get("@#{var_name}") << combo
Chris@0: end
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Processes +fields+ with @converters, or @header_converters
Chris@0: # if +headers+ is passed as +true+, returning the converted field set. Any
Chris@0: # converter that changes the field into something other than a String halts
Chris@0: # the pipeline of conversion for that field. This is primarily an efficiency
Chris@0: # shortcut.
Chris@0: #
Chris@0: def convert_fields(fields, headers = false)
Chris@0: # see if we are converting headers or fields
Chris@0: converters = headers ? @header_converters : @converters
Chris@0:
Chris@0: fields.enum_for(:each_with_index).map do |field, index| # map_with_index
Chris@0: converters.each do |converter|
Chris@0: field = if converter.arity == 1 # straight field converter
Chris@0: converter[field]
Chris@0: else # FieldInfo converter
Chris@0: header = @use_headers && !headers ? @headers[index] : nil
Chris@0: converter[field, FieldInfo.new(index, lineno, header)]
Chris@0: end
Chris@0: break unless field.is_a? String # short-curcuit pipeline for speed
Chris@0: end
Chris@0: field # return final state of each field, converted or original
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # This methods is used to turn a finished +row+ into a FasterCSV::Row. Header
Chris@0: # rows are also dealt with here, either by returning a FasterCSV::Row with
Chris@0: # identical headers and fields (save that the fields do not go through the
Chris@0: # converters) or by reading past them to return a field row. Headers are also
Chris@0: # saved in @headers for use in future rows.
Chris@0: #
Chris@0: # When +nil+, +row+ is assumed to be a header row not based on an actual row
Chris@0: # of the stream.
Chris@0: #
Chris@0: def parse_headers(row = nil)
Chris@0: if @headers.nil? # header row
Chris@0: @headers = case @use_headers # save headers
Chris@0: # Array of headers
Chris@0: when Array then @use_headers
Chris@0: # CSV header String
Chris@0: when String
Chris@0: self.class.parse_line( @use_headers,
Chris@0: :col_sep => @col_sep,
Chris@0: :row_sep => @row_sep,
Chris@0: :quote_char => @quote_char )
Chris@0: # first row is headers
Chris@0: else row
Chris@0: end
Chris@0:
Chris@0: # prepare converted and unconverted copies
Chris@0: row = @headers if row.nil?
Chris@0: @headers = convert_fields(@headers, true)
Chris@0:
Chris@0: if @return_headers # return headers
Chris@0: return FasterCSV::Row.new(@headers, row, true)
Chris@0: elsif not [Array, String].include? @use_headers.class # skip to field row
Chris@0: return shift
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: FasterCSV::Row.new(@headers, convert_fields(row)) # field row
Chris@0: end
Chris@0:
Chris@0: #
Chris@0: # Thiw methods injects an instance variable unconverted_fields into
Chris@0: # +row+ and an accessor method for it called unconverted_fields(). The
Chris@0: # variable is set to the contents of +fields+.
Chris@0: #
Chris@0: def add_unconverted_fields(row, fields)
Chris@0: class << row
Chris@0: attr_reader :unconverted_fields
Chris@0: end
Chris@0: row.instance_eval { @unconverted_fields = fields }
Chris@0: row
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: # Another name for FasterCSV.
Chris@0: FCSV = FasterCSV
Chris@0:
Chris@0: # Another name for FasterCSV::instance().
Chris@0: def FasterCSV(*args, &block)
Chris@0: FasterCSV.instance(*args, &block)
Chris@0: end
Chris@0:
Chris@0: # Another name for FCSV::instance().
Chris@0: def FCSV(*args, &block)
Chris@0: FCSV.instance(*args, &block)
Chris@0: end
Chris@0:
Chris@0: class Array
Chris@0: # Equivalent to FasterCSV::generate_line(self, options).
Chris@0: def to_csv(options = Hash.new)
Chris@0: FasterCSV.generate_line(self, options)
Chris@0: end
Chris@0: end
Chris@0:
Chris@0: class String
Chris@0: # Equivalent to FasterCSV::parse_line(self, options).
Chris@0: def parse_csv(options = Hash.new)
Chris@0: FasterCSV.parse_line(self, options)
Chris@0: end
Chris@0: end