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