1 #!/usr/local/bin/ruby -w
3 # = faster_csv.rb -- Faster CSV Reading and Writing
5 # Created by James Edward Gray II on 2005-10-31.
6 # Copyright 2005 Gray Productions. All rights reserved.
8 # See FasterCSV for documentation.
10 if RUBY_VERSION >= "1.9"
11 abort <<-VERSION_WARNING.gsub(/^\s+/, "")
12 Please switch to Ruby 1.9's standard CSV library. It's FasterCSV plus
13 support for Ruby 1.9's m17n encoding engine.
24 # This class provides a complete interface to CSV files and data. It offers
25 # tools to enable you to read and write to and from Strings or IO objects, as
32 # ==== A Line at a Time
34 # FasterCSV.foreach("path/to/file.csv") do |row|
40 # arr_of_arrs = FasterCSV.read("path/to/file.csv")
44 # ==== A Line at a Time
46 # FasterCSV.parse("CSV,data,String") do |row|
52 # arr_of_arrs = FasterCSV.parse("CSV,data,String")
58 # FasterCSV.open("path/to/file.csv", "w") do |csv|
59 # csv << ["row", "of", "CSV", "data"]
60 # csv << ["another", "row"]
66 # csv_string = FasterCSV.generate do |csv|
67 # csv << ["row", "of", "CSV", "data"]
68 # csv << ["another", "row"]
72 # == Convert a Single Line
74 # csv_string = ["CSV", "data"].to_csv # to CSV
75 # csv_array = "CSV,String".parse_csv # from CSV
77 # == Shortcut Interface
79 # FCSV { |csv_out| csv_out << %w{my data here} } # to $stdout
80 # FCSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String
81 # FCSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr
84 # The version of the installed library.
85 VERSION = "1.5.0".freeze
88 # A FasterCSV::Row is part Array and part Hash. It retains an order for the
89 # fields and allows duplicates just as an Array would, but also allows you to
90 # access fields by name just as you could if they were in a Hash.
92 # All rows returned by FasterCSV will be constructed from this class, if
93 # header row processing is activated.
97 # Construct a new FasterCSV::Row from +headers+ and +fields+, which are
98 # expected to be Arrays. If one Array is shorter than the other, it will be
99 # padded with +nil+ objects.
101 # The optional +header_row+ parameter can be set to +true+ to indicate, via
102 # FasterCSV::Row.header_row?() and FasterCSV::Row.field_row?(), that this is
103 # a header row. Otherwise, the row is assumes to be a field row.
105 # A FasterCSV::Row object supports the following Array methods through
112 def initialize(headers, fields, header_row = false)
113 @header_row = header_row
115 # handle extra headers or fields
116 @row = if headers.size > fields.size
119 fields.zip(headers).map { |pair| pair.reverse }
123 # Internal data format used to compare equality.
127 ### Array Delegation ###
130 def_delegators :@row, :empty?, :length, :size
132 # Returns +true+ if this is a header row.
137 # Returns +true+ if this is a field row.
142 # Returns the headers of this row.
144 @row.map { |pair| pair.first }
150 # field( header, offset )
153 # This method will fetch the field value by +header+ or +index+. If a field
154 # is not found, +nil+ is returned.
156 # When provided, +offset+ ensures that a header match occurrs on or later
157 # than the +offset+ index. You can use this to find duplicate headers,
158 # without resorting to hard-coding exact indices.
160 def field(header_or_index, minimum_index = 0)
162 finder = header_or_index.is_a?(Integer) ? :[] : :assoc
163 pair = @row[minimum_index..-1].send(finder, header_or_index)
165 # return the field if we have a pair
166 pair.nil? ? nil : pair.last
168 alias_method :[], :field
172 # []=( header, value )
173 # []=( header, offset, value )
174 # []=( index, value )
176 # Looks up the field by the semantics described in FasterCSV::Row.field()
177 # and assigns the +value+.
179 # Assigning past the end of the row with an index will set all pairs between
180 # to <tt>[nil, nil]</tt>. Assigning to an unused header appends the new
186 if args.first.is_a? Integer
187 if @row[args.first].nil? # extending past the end with index
188 @row[args.first] = [nil, value]
189 @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
190 else # normal index assignment
191 @row[args.first][1] = value
195 if index.nil? # appending a field
196 self << [args.first, value]
197 else # normal header assignment
198 @row[index][1] = value
206 # <<( header_and_field_array )
207 # <<( header_and_field_hash )
209 # If a two-element Array is provided, it is assumed to be a header and field
210 # and the pair is appended. A Hash works the same way with the key being
211 # the header and the value being the field. Anything else is assumed to be
212 # a lone field which is appended with a +nil+ header.
214 # This method returns the row for chaining.
217 if arg.is_a?(Array) and arg.size == 2 # appending a header and name
219 elsif arg.is_a?(Hash) # append header and name pairs
220 arg.each { |pair| @row << pair }
221 else # append field value
229 # A shortcut for appending multiple fields. Equivalent to:
231 # args.each { |arg| faster_csv_row << arg }
233 # This method returns the row for chaining.
236 args.each { |arg| self << arg }
244 # delete( header, offset )
247 # Used to remove a pair from the row by +header+ or +index+. The pair is
248 # located as described in FasterCSV::Row.field(). The deleted pair is
249 # returned, or +nil+ if a pair could not be found.
251 def delete(header_or_index, minimum_index = 0)
252 if header_or_index.is_a? Integer # by index
253 @row.delete_at(header_or_index)
255 @row.delete_at(index(header_or_index, minimum_index))
260 # The provided +block+ is passed a header and field for each pair in the row
261 # and expected to return +true+ or +false+, depending on whether the pair
264 # This method returns the row for chaining.
266 def delete_if(&block)
267 @row.delete_if(&block)
273 # This method accepts any number of arguments which can be headers, indices,
274 # Ranges of either, or two-element Arrays containing a header and offset.
275 # Each argument will be replaced with a field lookup as described in
276 # FasterCSV::Row.field().
278 # If called with no arguments, all fields are returned.
280 def fields(*headers_and_or_indices)
281 if headers_and_or_indices.empty? # return all fields--no arguments
282 @row.map { |pair| pair.last }
283 else # or work like values_at()
284 headers_and_or_indices.inject(Array.new) do |all, h_or_i|
285 all + if h_or_i.is_a? Range
286 index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
288 index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
290 new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
291 (index_begin..index_end)
292 fields.values_at(new_range)
294 [field(*Array(h_or_i))]
299 alias_method :values_at, :fields
304 # index( header, offset )
306 # This method will return the index of a field with the provided +header+.
307 # The +offset+ can be used to locate duplicate header names, as described in
308 # FasterCSV::Row.field().
310 def index(header, minimum_index = 0)
312 index = headers[minimum_index..-1].index(header)
313 # return the index at the right offset, if we found one
314 index.nil? ? nil : index + minimum_index
317 # Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
319 headers.include? name
321 alias_method :include?, :header?
324 # Returns +true+ if +data+ matches a field in this row, and +false+
334 # Yields each pair of the row as header and field tuples (much like
335 # iterating over a Hash).
337 # Support for Enumerable.
339 # This method returns the row for chaining.
348 # Returns +true+ if this row contains the same headers and fields in the
349 # same order as +other+.
356 # Collapses the row into a simple Hash. Be warning that this discards field
357 # order and clobbers duplicate fields.
360 # flatten just one level of the internal Array
361 Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
365 # Returns the row as a CSV String. Headers are not used. Equivalent to:
367 # faster_csv_row.fields.to_csv( options )
369 def to_csv(options = Hash.new)
370 fields.to_csv(options)
372 alias_method :to_s, :to_csv
374 # A summary of fields, by header.
376 str = "#<#{self.class}"
377 each do |header, field|
378 str << " #{header.is_a?(Symbol) ? header.to_s : header.inspect}:" <<
386 # A FasterCSV::Table is a two-dimensional data structure for representing CSV
387 # documents. Tables allow you to work with the data by row or column,
388 # manipulate the data, and even convert the results back to CSV, if needed.
390 # All tables returned by FasterCSV will be constructed from this class, if
391 # header row processing is activated.
395 # Construct a new FasterCSV::Table from +array_of_rows+, which are expected
396 # to be FasterCSV::Row objects. All rows are assumed to have the same
399 # A FasterCSV::Table object supports the following Array methods through
406 def initialize(array_of_rows)
407 @table = array_of_rows
411 # The current access mode for indexing and iteration.
414 # Internal data format used to compare equality.
418 ### Array Delegation ###
421 def_delegators :@table, :empty?, :length, :size
424 # Returns a duplicate table object, in column mode. This is handy for
425 # chaining in a single call without changing the table mode, but be aware
426 # that this method can consume a fair amount of memory for bigger data sets.
428 # This method returns the duplicate table for chaining. Don't chain
429 # destructive methods (like []=()) this way though, since you are working
433 self.class.new(@table.dup).by_col!
437 # Switches the mode of this table to column mode. All calls to indexing and
438 # iteration methods will work with columns until the mode is changed again.
440 # This method returns the table and is safe to chain.
449 # Returns a duplicate table object, in mixed mode. This is handy for
450 # chaining in a single call without changing the table mode, but be aware
451 # that this method can consume a fair amount of memory for bigger data sets.
453 # This method returns the duplicate table for chaining. Don't chain
454 # destructive methods (like []=()) this way though, since you are working
458 self.class.new(@table.dup).by_col_or_row!
462 # Switches the mode of this table to mixed mode. All calls to indexing and
463 # iteration methods will use the default intelligent indexing system until
464 # the mode is changed again. In mixed mode an index is assumed to be a row
465 # reference while anything else is assumed to be column access by headers.
467 # This method returns the table and is safe to chain.
476 # Returns a duplicate table object, in row mode. This is handy for chaining
477 # in a single call without changing the table mode, but be aware that this
478 # method can consume a fair amount of memory for bigger data sets.
480 # This method returns the duplicate table for chaining. Don't chain
481 # destructive methods (like []=()) this way though, since you are working
485 self.class.new(@table.dup).by_row!
489 # Switches the mode of this table to row mode. All calls to indexing and
490 # iteration methods will work with rows until the mode is changed again.
492 # This method returns the table and is safe to chain.
501 # Returns the headers for the first row of this table (assumed to match all
502 # other rows). An empty Array is returned for empty tables.
513 # In the default mixed mode, this method returns rows for index access and
514 # columns for header access. You can force the index association by first
515 # calling by_col!() or by_row!().
517 # Columns are returned as an Array of values. Altering that Array has no
518 # effect on the table.
520 def [](index_or_header)
521 if @mode == :row or # by index
522 (@mode == :col_or_row and index_or_header.is_a? Integer)
523 @table[index_or_header]
525 @table.map { |row| row[index_or_header] }
530 # In the default mixed mode, this method assigns rows for index access and
531 # columns for header access. You can force the index association by first
532 # calling by_col!() or by_row!().
534 # Rows may be set to an Array of values (which will inherit the table's
535 # headers()) or a FasterCSV::Row.
537 # Columns may be set to a single value, which is copied to each row of the
538 # column, or an Array of values. Arrays of values are assigned to rows top
539 # to bottom in row major order. Excess values are ignored and if the Array
540 # does not have a value for each row the extra rows will receive a +nil+.
542 # Assigning to an existing column or row clobbers the data. Assigning to
543 # new columns creates them at the right end of the table.
545 def []=(index_or_header, value)
546 if @mode == :row or # by index
547 (@mode == :col_or_row and index_or_header.is_a? Integer)
549 @table[index_or_header] = Row.new(headers, value)
551 @table[index_or_header] = value
554 if value.is_a? Array # multiple values
555 @table.each_with_index do |row, i|
557 row[index_or_header] = index_or_header
559 row[index_or_header] = value[i]
562 else # repeated value
565 row[index_or_header] = index_or_header
567 row[index_or_header] = value
575 # The mixed mode default is to treat a list of indices as row access,
576 # returning the rows indicated. Anything else is considered columnar
577 # access. For columnar access, the return set has an Array for each row
578 # with the values indicated by the headers in each Array. You can force
579 # column or row mode using by_col!() or by_row!().
581 # You cannot mix column and row access.
583 def values_at(*indices_or_headers)
584 if @mode == :row or # by indices
585 ( @mode == :col_or_row and indices_or_headers.all? do |index|
586 index.is_a?(Integer) or
587 ( index.is_a?(Range) and
588 index.first.is_a?(Integer) and
589 index.last.is_a?(Integer) )
591 @table.values_at(*indices_or_headers)
593 @table.map { |row| row.values_at(*indices_or_headers) }
598 # Adds a new row to the bottom end of this table. You can provide an Array,
599 # which will be converted to a FasterCSV::Row (inheriting the table's
600 # headers()), or a FasterCSV::Row.
602 # This method returns the table for chaining.
605 if row_or_array.is_a? Array # append Array
606 @table << Row.new(headers, row_or_array)
608 @table << row_or_array
615 # A shortcut for appending multiple rows. Equivalent to:
617 # rows.each { |row| self << row }
619 # This method returns the table for chaining.
622 rows.each { |row| self << row }
628 # Removes and returns the indicated column or row. In the default mixed
629 # mode indices refer to rows and everything else is assumed to be a column
630 # header. Use by_col!() or by_row!() to force the lookup.
632 def delete(index_or_header)
633 if @mode == :row or # by index
634 (@mode == :col_or_row and index_or_header.is_a? Integer)
635 @table.delete_at(index_or_header)
637 @table.map { |row| row.delete(index_or_header).last }
642 # Removes any column or row for which the block returns +true+. In the
643 # default mixed mode or row mode, iteration is the standard row major
644 # walking of rows. In column mode, interation will +yield+ two element
645 # tuples containing the column name and an Array of values for that column.
647 # This method returns the table for chaining.
649 def delete_if(&block)
650 if @mode == :row or @mode == :col_or_row # by index
651 @table.delete_if(&block)
653 to_delete = Array.new
654 headers.each_with_index do |header, i|
655 to_delete << header if block[[header, self[header]]]
657 to_delete.map { |header| delete(header) }
666 # In the default mixed mode or row mode, iteration is the standard row major
667 # walking of rows. In column mode, interation will +yield+ two element
668 # tuples containing the column name and an Array of values for that column.
670 # This method returns the table for chaining.
674 headers.each { |header| block[[header, self[header]]] }
682 # Returns +true+ if all rows of this table ==() +other+'s rows.
684 @table == other.table
688 # Returns the table as an Array of Arrays. Headers will be the first row,
689 # then all of the field rows will follow.
692 @table.inject([headers]) do |array, row|
702 # Returns the table as a complete CSV String. Headers will be listed first,
703 # then all of the field rows.
705 def to_csv(options = Hash.new)
706 @table.inject([headers.to_csv(options)]) do |rows, row|
710 rows + [row.fields.to_csv(options)]
714 alias_method :to_s, :to_csv
717 "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>"
721 # The error thrown when the parser encounters illegal CSV formatting.
722 class MalformedCSVError < RuntimeError; end
725 # A FieldInfo Struct contains details about a field's position in the data
726 # source it was read from. FasterCSV will pass this Struct to some blocks
727 # that make decisions based on field structure. See
728 # FasterCSV.convert_fields() for an example.
730 # <b><tt>index</tt></b>:: The zero-based index of the field in its row.
731 # <b><tt>line</tt></b>:: The line of the data source this row is from.
732 # <b><tt>header</tt></b>:: The header for the column, when available.
734 FieldInfo = Struct.new(:index, :line, :header)
736 # A Regexp used to find and convert some common Date formats.
737 DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
738 \d{4}-\d{2}-\d{2} )\z /x
739 # A Regexp used to find and convert some common DateTime formats.
741 / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
742 \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
744 # This Hash holds the built-in converters of FasterCSV that can be accessed by
745 # name. You can select Converters with FasterCSV.convert() or through the
746 # +options+ Hash passed to FasterCSV::new().
748 # <b><tt>:integer</tt></b>:: Converts any field Integer() accepts.
749 # <b><tt>:float</tt></b>:: Converts any field Float() accepts.
750 # <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt>
751 # and <tt>:float</tt>.
752 # <b><tt>:date</tt></b>:: Converts any field Date::parse() accepts.
753 # <b><tt>:date_time</tt></b>:: Converts any field DateTime::parse() accepts.
754 # <b><tt>:all</tt></b>:: All built-in converters. A combination of
755 # <tt>:date_time</tt> and <tt>:numeric</tt>.
757 # This Hash is intetionally left unfrozen and users should feel free to add
758 # values to it that can be accessed by all FasterCSV objects.
760 # To add a combo field, the value should be an Array of names. Combo fields
761 # can be nested with other combo fields.
763 Converters = { :integer => lambda { |f| Integer(f) rescue f },
764 :float => lambda { |f| Float(f) rescue f },
765 :numeric => [:integer, :float],
766 :date => lambda { |f|
767 f =~ DateMatcher ? (Date.parse(f) rescue f) : f
769 :date_time => lambda { |f|
770 f =~ DateTimeMatcher ? (DateTime.parse(f) rescue f) : f
772 :all => [:date_time, :numeric] }
775 # This Hash holds the built-in header converters of FasterCSV that can be
776 # accessed by name. You can select HeaderConverters with
777 # FasterCSV.header_convert() or through the +options+ Hash passed to
780 # <b><tt>:downcase</tt></b>:: Calls downcase() on the header String.
781 # <b><tt>:symbol</tt></b>:: The header String is downcased, spaces are
782 # replaced with underscores, non-word characters
783 # are dropped, and finally to_sym() is called.
785 # This Hash is intetionally left unfrozen and users should feel free to add
786 # values to it that can be accessed by all FasterCSV objects.
788 # To add a combo field, the value should be an Array of names. Combo fields
789 # can be nested with other combo fields.
792 :downcase => lambda { |h| h.downcase },
793 :symbol => lambda { |h|
794 h.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym
799 # The options used when no overrides are given by calling code. They are:
801 # <b><tt>:col_sep</tt></b>:: <tt>","</tt>
802 # <b><tt>:row_sep</tt></b>:: <tt>:auto</tt>
803 # <b><tt>:quote_char</tt></b>:: <tt>'"'</tt>
804 # <b><tt>:converters</tt></b>:: +nil+
805 # <b><tt>:unconverted_fields</tt></b>:: +nil+
806 # <b><tt>:headers</tt></b>:: +false+
807 # <b><tt>:return_headers</tt></b>:: +false+
808 # <b><tt>:header_converters</tt></b>:: +nil+
809 # <b><tt>:skip_blanks</tt></b>:: +false+
810 # <b><tt>:force_quotes</tt></b>:: +false+
812 DEFAULT_OPTIONS = { :col_sep => ",",
816 :unconverted_fields => nil,
818 :return_headers => false,
819 :header_converters => nil,
820 :skip_blanks => false,
821 :force_quotes => false }.freeze
824 # This method will build a drop-in replacement for many of the standard CSV
825 # methods. It allows you to write code like:
828 # require "faster_csv"
829 # FasterCSV.build_csv_interface
833 # # ... use CSV here ...
835 # This is not a complete interface with completely identical behavior.
836 # However, it is intended to be close enough that you won't notice the
837 # difference in most cases. CSV methods supported are:
846 # Be warned that this interface is slower than vanilla FasterCSV due to the
847 # extra layer of method calls. Depending on usage, this can slow it down to
850 def self.build_csv_interface
851 Object.const_set(:CSV, Class.new).class_eval do
852 def self.foreach(path, rs = :auto, &block) # :nodoc:
853 FasterCSV.foreach(path, :row_sep => rs, &block)
856 def self.generate_line(row, fs = ",", rs = "") # :nodoc:
857 FasterCSV.generate_line(row, :col_sep => fs, :row_sep => rs)
860 def self.open(path, mode, fs = ",", rs = :auto, &block) # :nodoc:
861 if block and mode.include? "r"
862 FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs) do |csv|
866 FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs, &block)
870 def self.parse(str_or_readable, fs = ",", rs = :auto, &block) # :nodoc:
871 FasterCSV.parse(str_or_readable, :col_sep => fs, :row_sep => rs, &block)
874 def self.parse_line(src, fs = ",", rs = :auto) # :nodoc:
875 FasterCSV.parse_line(src, :col_sep => fs, :row_sep => rs)
878 def self.readlines(path, rs = :auto) # :nodoc:
879 FasterCSV.readlines(path, :row_sep => rs)
885 # This method allows you to serialize an Array of Ruby objects to a String or
886 # File of CSV data. This is not as powerful as Marshal or YAML, but perhaps
887 # useful for spreadsheet and database interaction.
889 # Out of the box, this method is intended to work with simple data objects or
890 # Structs. It will serialize a list of instance variables and/or
893 # If you need need more complicated serialization, you can control the process
894 # by adding methods to the class to be serialized.
896 # A class method csv_meta() is responsible for returning the first row of the
897 # document (as an Array). This row is considered to be a Hash of the form
898 # key_1,value_1,key_2,value_2,... FasterCSV::load() expects to find a class
899 # key with a value of the stringified class name and FasterCSV::dump() will
900 # create this, if you do not define this method. This method is only called
901 # on the first object of the Array.
903 # The next method you can provide is an instance method called csv_headers().
904 # This method is expected to return the second line of the document (again as
905 # an Array), which is to be used to give each column a header. By default,
906 # FasterCSV::load() will set an instance variable if the field header starts
907 # with an @ character or call send() passing the header as the method name and
908 # the field value as an argument. This method is only called on the first
909 # object of the Array.
911 # Finally, you can provide an instance method called csv_dump(), which will
912 # be passed the headers. This should return an Array of fields that can be
913 # serialized for this object. This method is called once for every object in
916 # The +io+ parameter can be used to serialize to a File, and +options+ can be
917 # anything FasterCSV::new() accepts.
919 def self.dump(ary_of_objs, io = "", options = Hash.new)
920 obj_template = ary_of_objs.first
922 csv = FasterCSV.new(io, options)
924 # write meta information
926 csv << obj_template.class.csv_meta
928 csv << [:class, obj_template.class]
933 headers = obj_template.csv_headers
935 headers = obj_template.instance_variables.sort
936 if obj_template.class.ancestors.find { |cls| cls.to_s =~ /\AStruct\b/ }
937 headers += obj_template.members.map { |mem| "#{mem}=" }.sort
942 # serialize each object
943 ary_of_objs.each do |obj|
945 csv << obj.csv_dump(headers)
947 csv << headers.map do |var|
949 obj.instance_variable_get(var)
966 # filter( options = Hash.new ) { |row| ... }
967 # filter( input, options = Hash.new ) { |row| ... }
968 # filter( input, output, options = Hash.new ) { |row| ... }
970 # This method is a convenience for building Unix-like filters for CSV data.
971 # Each row is yielded to the provided block which can alter it as needed.
972 # After the block returns, the row is appended to +output+ altered or not.
974 # The +input+ and +output+ arguments can be anything FasterCSV::new() accepts
975 # (generally String or IO objects). If not given, they default to
976 # <tt>ARGF</tt> and <tt>$stdout</tt>.
978 # The +options+ parameter is also filtered down to FasterCSV::new() after some
979 # clever key parsing. Any key beginning with <tt>:in_</tt> or
980 # <tt>:input_</tt> will have that leading identifier stripped and will only
981 # be used in the +options+ Hash for the +input+ object. Keys starting with
982 # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+. All other keys
983 # are assigned to both objects.
985 # The <tt>:output_row_sep</tt> +option+ defaults to
986 # <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
988 def self.filter(*args)
989 # parse options for input, output, or both
990 in_options, out_options = Hash.new, {:row_sep => $INPUT_RECORD_SEPARATOR}
991 if args.last.is_a? Hash
992 args.pop.each do |key, value|
994 when /\Ain(?:put)?_(.+)\Z/
995 in_options[$1.to_sym] = value
996 when /\Aout(?:put)?_(.+)\Z/
997 out_options[$1.to_sym] = value
999 in_options[key] = value
1000 out_options[key] = value
1004 # build input and output wrappers
1005 input = FasterCSV.new(args.shift || ARGF, in_options)
1006 output = FasterCSV.new(args.shift || $stdout, out_options)
1008 # read, yield, write
1016 # This method is intended as the primary interface for reading CSV files. You
1017 # pass a +path+ and any +options+ you wish to set for the read. Each row of
1018 # file will be passed to the provided +block+ in turn.
1020 # The +options+ parameter can be anything FasterCSV::new() understands.
1022 def self.foreach(path, options = Hash.new, &block)
1023 open(path, "rb", options) do |csv|
1030 # generate( str, options = Hash.new ) { |faster_csv| ... }
1031 # generate( options = Hash.new ) { |faster_csv| ... }
1033 # This method wraps a String you provide, or an empty default String, in a
1034 # FasterCSV object which is passed to the provided block. You can use the
1035 # block to append CSV rows to the String and when the block exits, the
1036 # final String will be returned.
1038 # Note that a passed String *is* modfied by this method. Call dup() before
1039 # passing if you need a new String.
1041 # The +options+ parameter can be anthing FasterCSV::new() understands.
1043 def self.generate(*args)
1044 # add a default empty String, if none was given
1045 if args.first.is_a? String
1046 io = StringIO.new(args.shift)
1047 io.seek(0, IO::SEEK_END)
1052 faster_csv = new(*args) # wrap
1053 yield faster_csv # yield for appending
1054 faster_csv.string # return final String
1058 # This method is a shortcut for converting a single row (Array) into a CSV
1061 # The +options+ parameter can be anthing FasterCSV::new() understands.
1063 # The <tt>:row_sep</tt> +option+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
1064 # (<tt>$/</tt>) when calling this method.
1066 def self.generate_line(row, options = Hash.new)
1067 options = {:row_sep => $INPUT_RECORD_SEPARATOR}.merge(options)
1068 (new("", options) << row).string
1072 # This method will return a FasterCSV instance, just like FasterCSV::new(),
1073 # but the instance will be cached and returned for all future calls to this
1074 # method for the same +data+ object (tested by Object#object_id()) with the
1077 # If a block is given, the instance is passed to the block and the return
1078 # value becomes the return value of the block.
1080 def self.instance(data = $stdout, options = Hash.new)
1081 # create a _signature_ for this method call, data object and options
1082 sig = [data.object_id] +
1083 options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })
1085 # fetch or create the instance for this signature
1086 @@instances ||= Hash.new
1087 instance = (@@instances[sig] ||= new(data, options))
1090 yield instance # run block, if given, returning result
1092 instance # or return the instance
1097 # This method is the reading counterpart to FasterCSV::dump(). See that
1098 # method for a detailed description of the process.
1100 # You can customize loading by adding a class method called csv_load() which
1101 # will be passed a Hash of meta information, an Array of headers, and an Array
1102 # of fields for the object the method is expected to return.
1104 # Remember that all fields will be Strings after this load. If you need
1105 # something else, use +options+ to setup converters or provide a custom
1106 # csv_load() implementation.
1108 def self.load(io_or_str, options = Hash.new)
1109 csv = FasterCSV.new(io_or_str, options)
1111 # load meta information
1112 meta = Hash[*csv.shift]
1113 cls = meta["class"].split("::").inject(Object) do |c, const|
1120 # unserialize each object stored in the file
1121 results = csv.inject(Array.new) do |all, row|
1123 obj = cls.csv_load(meta, headers, row)
1124 rescue NoMethodError
1126 headers.zip(row) do |name, value|
1128 obj.instance_variable_set(name, value)
1130 obj.send(name, value)
1137 csv.close unless io_or_str.is_a? String
1144 # open( filename, mode="rb", options = Hash.new ) { |faster_csv| ... }
1145 # open( filename, mode="rb", options = Hash.new )
1147 # This method opens an IO object, and wraps that with FasterCSV. This is
1148 # intended as the primary interface for writing a CSV file.
1150 # You may pass any +args+ Ruby's open() understands followed by an optional
1151 # Hash containing any +options+ FasterCSV::new() understands.
1153 # This method works like Ruby's open() call, in that it will pass a FasterCSV
1154 # object to a provided block and close it when the block termminates, or it
1155 # will return the FasterCSV object when no block is provided. (*Note*: This
1156 # is different from the standard CSV library which passes rows to the block.
1157 # Use FasterCSV::foreach() for that behavior.)
1159 # An opened FasterCSV object will delegate to many IO methods, for
1160 # convenience. You may call:
1187 def self.open(*args)
1188 # find the +options+ Hash
1189 options = if args.last.is_a? Hash then args.pop else Hash.new end
1190 # default to a binary open mode
1191 args << "rb" if args.size == 1
1192 # wrap a File opened with the remaining +args+
1193 csv = new(File.open(*args), options)
1195 # handle blocks like Ruby's open(), not like the CSV library
1209 # parse( str, options = Hash.new ) { |row| ... }
1210 # parse( str, options = Hash.new )
1212 # This method can be used to easily parse CSV out of a String. You may either
1213 # provide a +block+ which will be called with each row of the String in turn,
1214 # or just use the returned Array of Arrays (when no +block+ is given).
1216 # You pass your +str+ to read from, and an optional +options+ Hash containing
1217 # anything FasterCSV::new() understands.
1219 def self.parse(*args, &block)
1221 if block.nil? # slurp contents, if no block is given
1227 else # or pass each row to a provided block
1233 # This method is a shortcut for converting a single line of a CSV String into
1234 # a into an Array. Note that if +line+ contains multiple rows, anything
1235 # beyond the first row is ignored.
1237 # The +options+ parameter can be anthing FasterCSV::new() understands.
1239 def self.parse_line(line, options = Hash.new)
1240 new(line, options).shift
1244 # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the
1245 # file and any +options+ FasterCSV::new() understands.
1247 def self.read(path, options = Hash.new)
1248 open(path, "rb", options) { |csv| csv.read }
1251 # Alias for FasterCSV::read().
1252 def self.readlines(*args)
1259 # FasterCSV.read( path, { :headers => true,
1260 # :converters => :numeric,
1261 # :header_converters => :symbol }.merge(options) )
1263 def self.table(path, options = Hash.new)
1264 read( path, { :headers => true,
1265 :converters => :numeric,
1266 :header_converters => :symbol }.merge(options) )
1270 # This constructor will wrap either a String or IO object passed in +data+ for
1271 # reading and/or writing. In addition to the FasterCSV instance methods,
1272 # several IO methods are delegated. (See FasterCSV::open() for a complete
1273 # list.) If you pass a String for +data+, you can later retrieve it (after
1274 # writing to it, for example) with FasterCSV.string().
1276 # Note that a wrapped String will be positioned at at the beginning (for
1277 # reading). If you want it at the end (for writing), use
1278 # FasterCSV::generate(). If you want any other positioning, pass a preset
1279 # StringIO object instead.
1281 # You may set any reading and/or writing preferences in the +options+ Hash.
1282 # Available options are:
1284 # <b><tt>:col_sep</tt></b>:: The String placed between each field.
1285 # <b><tt>:row_sep</tt></b>:: The String appended to the end of each
1286 # row. This can be set to the special
1287 # <tt>:auto</tt> setting, which requests
1288 # that FasterCSV automatically discover
1289 # this from the data. Auto-discovery
1290 # reads ahead in the data looking for
1291 # the next <tt>"\r\n"</tt>,
1292 # <tt>"\n"</tt>, or <tt>"\r"</tt>
1293 # sequence. A sequence will be selected
1294 # even if it occurs in a quoted field,
1295 # assuming that you would have the same
1296 # line endings there. If none of those
1297 # sequences is found, +data+ is
1298 # <tt>ARGF</tt>, <tt>STDIN</tt>,
1299 # <tt>STDOUT</tt>, or <tt>STDERR</tt>,
1300 # or the stream is only available for
1301 # output, the default
1302 # <tt>$INPUT_RECORD_SEPARATOR</tt>
1303 # (<tt>$/</tt>) is used. Obviously,
1304 # discovery takes a little time. Set
1305 # manually if speed is important. Also
1306 # note that IO objects should be opened
1307 # in binary mode on Windows if this
1308 # feature will be used as the
1309 # line-ending translation can cause
1310 # problems with resetting the document
1311 # position to where it was before the
1313 # <b><tt>:quote_char</tt></b>:: The character used to quote fields.
1314 # This has to be a single character
1315 # String. This is useful for
1316 # application that incorrectly use
1317 # <tt>'</tt> as the quote character
1318 # instead of the correct <tt>"</tt>.
1319 # FasterCSV will always consider a
1320 # double sequence this character to be
1322 # <b><tt>:encoding</tt></b>:: The encoding to use when parsing the
1323 # file. Defaults to your <tt>$KDOCE</tt>
1324 # setting. Valid values: <tt>`n’</tt> or
1325 # <tt>`N’</tt> for none, <tt>`e’</tt> or
1326 # <tt>`E’</tt> for EUC, <tt>`s’</tt> or
1327 # <tt>`S’</tt> for SJIS, and
1328 # <tt>`u’</tt> or <tt>`U’</tt> for UTF-8
1329 # (see Regexp.new()).
1330 # <b><tt>:field_size_limit</tt></b>:: This is a maximum size FasterCSV will
1331 # read ahead looking for the closing
1332 # quote for a field. (In truth, it
1333 # reads to the first line ending beyond
1334 # this size.) If a quote cannot be
1335 # found within the limit FasterCSV will
1336 # raise a MalformedCSVError, assuming
1337 # the data is faulty. You can use this
1338 # limit to prevent what are effectively
1339 # DoS attacks on the parser. However,
1340 # this limit can cause a legitimate
1341 # parse to fail and thus is set to
1342 # +nil+, or off, by default.
1343 # <b><tt>:converters</tt></b>:: An Array of names from the Converters
1344 # Hash and/or lambdas that handle custom
1345 # conversion. A single converter
1346 # doesn't have to be in an Array.
1347 # <b><tt>:unconverted_fields</tt></b>:: If set to +true+, an
1348 # unconverted_fields() method will be
1349 # added to all returned rows (Array or
1350 # FasterCSV::Row) that will return the
1351 # fields as they were before convertion.
1352 # Note that <tt>:headers</tt> supplied
1353 # by Array or String were not fields of
1354 # the document and thus will have an
1355 # empty Array attached.
1356 # <b><tt>:headers</tt></b>:: If set to <tt>:first_row</tt> or
1357 # +true+, the initial row of the CSV
1358 # file will be treated as a row of
1359 # headers. If set to an Array, the
1360 # contents will be used as the headers.
1361 # If set to a String, the String is run
1363 # FasterCSV::parse_line() with the same
1364 # <tt>:col_sep</tt>, <tt>:row_sep</tt>,
1365 # and <tt>:quote_char</tt> as this
1366 # instance to produce an Array of
1367 # headers. This setting causes
1368 # FasterCSV.shift() to return rows as
1369 # FasterCSV::Row objects instead of
1370 # Arrays and FasterCSV.read() to return
1371 # FasterCSV::Table objects instead of
1372 # an Array of Arrays.
1373 # <b><tt>:return_headers</tt></b>:: When +false+, header rows are silently
1374 # swallowed. If set to +true+, header
1375 # rows are returned in a FasterCSV::Row
1376 # object with identical headers and
1377 # fields (save that the fields do not go
1378 # through the converters).
1379 # <b><tt>:write_headers</tt></b>:: When +true+ and <tt>:headers</tt> is
1380 # set, a header row will be added to the
1382 # <b><tt>:header_converters</tt></b>:: Identical in functionality to
1383 # <tt>:converters</tt> save that the
1384 # conversions are only made to header
1386 # <b><tt>:skip_blanks</tt></b>:: When set to a +true+ value, FasterCSV
1387 # will skip over any rows with no
1389 # <b><tt>:force_quotes</tt></b>:: When set to a +true+ value, FasterCSV
1390 # will quote all CSV fields it creates.
1392 # See FasterCSV::DEFAULT_OPTIONS for the default settings.
1394 # Options cannot be overriden in the instance methods for performance reasons,
1395 # so be sure to set what you want here.
1397 def initialize(data, options = Hash.new)
1398 # build the options for this read/write
1399 options = DEFAULT_OPTIONS.merge(options)
1401 # create the IO object we will read from
1402 @io = if data.is_a? String then StringIO.new(data) else data end
1404 init_separators(options)
1405 init_parsers(options)
1406 init_converters(options)
1407 init_headers(options)
1409 unless options.empty?
1410 raise ArgumentError, "Unknown options: #{options.keys.join(', ')}."
1413 # track our own lineno since IO gets confused about line-ends is CSV fields
1418 # The line number of the last row read from this file. Fields with nested
1419 # line-end characters will not affect this count.
1423 ### IO and StringIO Delegation ###
1426 def_delegators :@io, :binmode, :close, :close_read, :close_write, :closed?,
1427 :eof, :eof?, :fcntl, :fileno, :flush, :fsync, :ioctl,
1428 :isatty, :pid, :pos, :reopen, :seek, :stat, :string,
1429 :sync, :sync=, :tell, :to_i, :to_io, :tty?
1431 # Rewinds the underlying IO object and resets FasterCSV's lineno() counter.
1439 ### End Delegation ###
1442 # The primary write method for wrapped Strings and IOs, +row+ (an Array or
1443 # FasterCSV::Row) is converted to CSV and appended to the data source. When a
1444 # FasterCSV::Row is passed, only the row's fields() are appended to the
1447 # The data source must be open for writing.
1450 # make sure headers have been assigned
1451 if header_row? and [Array, String].include? @use_headers.class
1452 parse_headers # won't read data for Array or String
1453 self << @headers if @write_headers
1456 # Handle FasterCSV::Row objects and Hashes
1458 when self.class::Row then row.fields
1459 when Hash then @headers.map { |header| row[header] }
1463 @headers = row if header_row?
1466 @io << row.map(&@quote).join(@col_sep) + @row_sep # quote and separate
1470 alias_method :add_row, :<<
1471 alias_method :puts, :<<
1476 # convert { |field| ... }
1477 # convert { |field, field_info| ... }
1479 # You can use this method to install a FasterCSV::Converters built-in, or
1480 # provide a block that handles a custom conversion.
1482 # If you provide a block that takes one argument, it will be passed the field
1483 # and is expected to return the converted value or the field itself. If your
1484 # block takes two arguments, it will also be passed a FieldInfo Struct,
1485 # containing details about the field. Again, the block should return a
1486 # converted field or the field itself.
1488 def convert(name = nil, &converter)
1489 add_converter(:converters, self.class::Converters, name, &converter)
1494 # header_convert( name )
1495 # header_convert { |field| ... }
1496 # header_convert { |field, field_info| ... }
1498 # Identical to FasterCSV.convert(), but for header rows.
1500 # Note that this method must be called before header rows are read to have any
1503 def header_convert(name = nil, &converter)
1504 add_converter( :header_converters,
1505 self.class::HeaderConverters,
1513 # Yields each row of the data source in turn.
1515 # Support for Enumerable.
1517 # The data source must be open for reading.
1526 # Slurps the remaining rows and returns an Array of Arrays.
1528 # The data source must be open for reading.
1538 alias_method :readlines, :read
1540 # Returns +true+ if the next row read will be a header row.
1542 @use_headers and @headers.nil?
1546 # The primary read method for wrapped Strings and IOs, a single row is pulled
1547 # from the data source, parsed and returned as an Array of fields (if header
1548 # rows are not used) or a FasterCSV::Row (when header rows are used).
1550 # The data source must be open for reading.
1553 #########################################################################
1554 ### This method is purposefully kept a bit long as simple conditional ###
1555 ### checks are faster than numerous (expensive) method calls. ###
1556 #########################################################################
1558 # handle headers not based on document content
1559 if header_row? and @return_headers and
1560 [Array, String].include? @use_headers.class
1561 if @unconverted_fields
1562 return add_unconverted_fields(parse_headers, Array.new)
1564 return parse_headers
1568 # begin with a blank line, so we can always add to it
1572 # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,
1573 # because of \r and/or \n characters embedded in quoted fields
1576 # add another read to the line
1578 line += @io.gets(@row_sep)
1582 # copy the line so we can chop it up in parsing
1584 parse.sub!(@parsers[:line_end], "")
1587 # I believe a blank line should be an <tt>Array.new</tt>, not
1588 # CSV's <tt>[nil]</tt>
1595 elsif @unconverted_fields
1596 return add_unconverted_fields(Array.new, Array.new)
1598 return FasterCSV::Row.new(Array.new, Array.new)
1604 # parse the fields with a mix of String#split and regular expressions
1606 current_field = String.new
1608 parse.split(@col_sep, -1).each do |match|
1609 if current_field.empty? && match.count(@quote_and_newlines).zero?
1610 csv << (match.empty? ? nil : match)
1611 elsif(current_field.empty? ? match[0] : current_field[0]) == @quote_char[0]
1612 current_field << match
1613 field_quotes += match.count(@quote_char)
1614 if field_quotes % 2 == 0
1615 in_quotes = current_field[@parsers[:quoted_field], 1]
1616 raise MalformedCSVError unless in_quotes
1617 current_field = in_quotes
1618 current_field.gsub!(@quote_char * 2, @quote_char) # unescape contents
1619 csv << current_field
1620 current_field = String.new
1622 else # we found a quoted field that spans multiple lines
1623 current_field << @col_sep
1625 elsif match.count("\r\n").zero?
1626 raise MalformedCSVError, "Illegal quoting on line #{lineno + 1}."
1628 raise MalformedCSVError, "Unquoted fields do not allow " +
1629 "\\r or \\n (line #{lineno + 1})."
1633 # if parse is empty?(), we found all the fields on the line...
1634 if field_quotes % 2 == 0
1637 # save fields unconverted fields, if needed...
1638 unconverted = csv.dup if @unconverted_fields
1640 # convert fields, if needed...
1641 csv = convert_fields(csv) unless @use_headers or @converters.empty?
1642 # parse out header rows and handle FasterCSV::Row conversions...
1643 csv = parse_headers(csv) if @use_headers
1645 # inject unconverted fields and accessor, if requested...
1646 if @unconverted_fields and not csv.respond_to? :unconverted_fields
1647 add_unconverted_fields(csv, unconverted)
1650 # return the results
1653 # if we're not empty?() but at eof?(), a quoted field wasn't closed...
1655 raise MalformedCSVError, "Unclosed quoted field on line #{lineno + 1}."
1656 elsif @field_size_limit and current_field.size >= @field_size_limit
1657 raise MalformedCSVError, "Field size exceeded on line #{lineno + 1}."
1659 # otherwise, we need to loop and pull some more data to complete the row
1662 alias_method :gets, :shift
1663 alias_method :readline, :shift
1665 # Returns a simplified description of the key FasterCSV attributes.
1667 str = "<##{self.class} io_type:"
1668 # show type of wrapped IO
1669 if @io == $stdout then str << "$stdout"
1670 elsif @io == $stdin then str << "$stdin"
1671 elsif @io == $stderr then str << "$stderr"
1672 else str << @io.class.to_s
1674 # show IO.path(), if available
1675 if @io.respond_to?(:path) and (p = @io.path)
1676 str << " io_path:#{p.inspect}"
1678 # show other attributes
1679 %w[ lineno col_sep row_sep
1680 quote_char skip_blanks encoding ].each do |attr_name|
1681 if a = instance_variable_get("@#{attr_name}")
1682 str << " #{attr_name}:#{a.inspect}"
1686 str << " headers:#{(@headers || true).inspect}"
1694 # Stores the indicated separators for later use.
1696 # If auto-discovery was requested for <tt>@row_sep</tt>, this method will read
1697 # ahead in the <tt>@io</tt> and try to find one. +ARGF+, +STDIN+, +STDOUT+,
1698 # +STDERR+ and any stream open for output only with a default
1699 # <tt>@row_sep</tt> of <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
1701 # This method also establishes the quoting rules used for CSV output.
1703 def init_separators(options)
1704 # store the selected separators
1705 @col_sep = options.delete(:col_sep)
1706 @row_sep = options.delete(:row_sep)
1707 @quote_char = options.delete(:quote_char)
1708 @quote_and_newlines = "#{@quote_char}\r\n"
1710 if @quote_char.length != 1
1711 raise ArgumentError, ":quote_char has to be a single character String"
1714 # automatically discover row separator when requested
1715 if @row_sep == :auto
1716 if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or
1717 (defined?(Zlib) and @io.class == Zlib::GzipWriter)
1718 @row_sep = $INPUT_RECORD_SEPARATOR
1721 saved_pos = @io.pos # remember where we were
1722 while @row_sep == :auto
1724 # if we run out of data, it's probably a single line
1725 # (use a sensible default)
1728 @row_sep = $INPUT_RECORD_SEPARATOR
1733 sample = @io.read(1024)
1734 sample += @io.read(1) if sample[-1..-1] == "\r" and not @io.eof?
1736 # try to find a standard separator
1737 if sample =~ /\r\n?|\n/
1742 # tricky seek() clone to work around GzipReader's lack of seek()
1744 # reset back to the remembered position
1745 while saved_pos > 1024 # avoid loading a lot of data into memory
1749 @io.read(saved_pos) if saved_pos.nonzero?
1750 rescue IOError # stream not opened for reading
1751 @row_sep = $INPUT_RECORD_SEPARATOR
1756 # establish quoting rules
1757 do_quote = lambda do |field|
1759 String(field).gsub(@quote_char, @quote_char * 2) +
1762 @quote = if options.delete(:force_quotes)
1766 if field.nil? # represent +nil+ fields as empty unquoted fields
1769 field = String(field) # Stringify fields
1770 # represent empty fields as empty quoted fields
1772 field.count("\r\n#{@col_sep}#{@quote_char}").nonzero?
1773 do_quote.call(field)
1775 field # unquoted field
1782 # Pre-compiles parsers and stores them by name for access during reads.
1783 def init_parsers(options)
1784 # store the parser behaviors
1785 @skip_blanks = options.delete(:skip_blanks)
1786 @encoding = options.delete(:encoding) # nil will use $KCODE
1787 @field_size_limit = options.delete(:field_size_limit)
1789 # prebuild Regexps for faster parsing
1790 esc_col_sep = Regexp.escape(@col_sep)
1791 esc_row_sep = Regexp.escape(@row_sep)
1792 esc_quote = Regexp.escape(@quote_char)
1794 :any_field => Regexp.new( "[^#{esc_col_sep}]+",
1797 :quoted_field => Regexp.new( "^#{esc_quote}(.*)#{esc_quote}$",
1800 # safer than chomp!()
1801 :line_end => Regexp.new("#{esc_row_sep}\\z", nil, @encoding)
1806 # Loads any converters requested during construction.
1808 # If +field_name+ is set <tt>:converters</tt> (the default) field converters
1809 # are set. When +field_name+ is <tt>:header_converters</tt> header converters
1810 # are added instead.
1812 # The <tt>:unconverted_fields</tt> option is also actived for
1813 # <tt>:converters</tt> calls, if requested.
1815 def init_converters(options, field_name = :converters)
1816 if field_name == :converters
1817 @unconverted_fields = options.delete(:unconverted_fields)
1820 instance_variable_set("@#{field_name}", Array.new)
1822 # find the correct method to add the coverters
1823 convert = method(field_name.to_s.sub(/ers\Z/, ""))
1826 unless options[field_name].nil?
1827 # allow a single converter not wrapped in an Array
1828 unless options[field_name].is_a? Array
1829 options[field_name] = [options[field_name]]
1831 # load each converter...
1832 options[field_name].each do |converter|
1833 if converter.is_a? Proc # custom code block
1834 convert.call(&converter)
1836 convert.call(converter)
1841 options.delete(field_name)
1844 # Stores header row settings and loads header converters, if needed.
1845 def init_headers(options)
1846 @use_headers = options.delete(:headers)
1847 @return_headers = options.delete(:return_headers)
1848 @write_headers = options.delete(:write_headers)
1850 # headers must be delayed until shift(), in case they need a row of content
1853 init_converters(options, :header_converters)
1857 # The actual work method for adding converters, used by both
1858 # FasterCSV.convert() and FasterCSV.header_convert().
1860 # This method requires the +var_name+ of the instance variable to place the
1861 # converters in, the +const+ Hash to lookup named converters in, and the
1862 # normal parameters of the FasterCSV.convert() and FasterCSV.header_convert()
1865 def add_converter(var_name, const, name = nil, &converter)
1866 if name.nil? # custom converter
1867 instance_variable_get("@#{var_name}") << converter
1868 else # named converter
1871 when Array # combo converter
1872 combo.each do |converter_name|
1873 add_converter(var_name, const, converter_name)
1875 else # individual named converter
1876 instance_variable_get("@#{var_name}") << combo
1882 # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt>
1883 # if +headers+ is passed as +true+, returning the converted field set. Any
1884 # converter that changes the field into something other than a String halts
1885 # the pipeline of conversion for that field. This is primarily an efficiency
1888 def convert_fields(fields, headers = false)
1889 # see if we are converting headers or fields
1890 converters = headers ? @header_converters : @converters
1892 fields.enum_for(:each_with_index).map do |field, index| # map_with_index
1893 converters.each do |converter|
1894 field = if converter.arity == 1 # straight field converter
1896 else # FieldInfo converter
1897 header = @use_headers && !headers ? @headers[index] : nil
1898 converter[field, FieldInfo.new(index, lineno, header)]
1900 break unless field.is_a? String # short-curcuit pipeline for speed
1902 field # return final state of each field, converted or original
1907 # This methods is used to turn a finished +row+ into a FasterCSV::Row. Header
1908 # rows are also dealt with here, either by returning a FasterCSV::Row with
1909 # identical headers and fields (save that the fields do not go through the
1910 # converters) or by reading past them to return a field row. Headers are also
1911 # saved in <tt>@headers</tt> for use in future rows.
1913 # When +nil+, +row+ is assumed to be a header row not based on an actual row
1916 def parse_headers(row = nil)
1917 if @headers.nil? # header row
1918 @headers = case @use_headers # save headers
1920 when Array then @use_headers
1923 self.class.parse_line( @use_headers,
1924 :col_sep => @col_sep,
1925 :row_sep => @row_sep,
1926 :quote_char => @quote_char )
1927 # first row is headers
1931 # prepare converted and unconverted copies
1932 row = @headers if row.nil?
1933 @headers = convert_fields(@headers, true)
1935 if @return_headers # return headers
1936 return FasterCSV::Row.new(@headers, row, true)
1937 elsif not [Array, String].include? @use_headers.class # skip to field row
1942 FasterCSV::Row.new(@headers, convert_fields(row)) # field row
1946 # Thiw methods injects an instance variable <tt>unconverted_fields</tt> into
1947 # +row+ and an accessor method for it called unconverted_fields(). The
1948 # variable is set to the contents of +fields+.
1950 def add_unconverted_fields(row, fields)
1952 attr_reader :unconverted_fields
1954 row.instance_eval { @unconverted_fields = fields }
1959 # Another name for FasterCSV.
1962 # Another name for FasterCSV::instance().
1963 def FasterCSV(*args, &block)
1964 FasterCSV.instance(*args, &block)
1967 # Another name for FCSV::instance().
1968 def FCSV(*args, &block)
1969 FCSV.instance(*args, &block)
1973 # Equivalent to <tt>FasterCSV::generate_line(self, options)</tt>.
1974 def to_csv(options = Hash.new)
1975 FasterCSV.generate_line(self, options)
1980 # Equivalent to <tt>FasterCSV::parse_line(self, options)</tt>.
1981 def parse_csv(options = Hash.new)
1982 FasterCSV.parse_line(self, options)