annotate .svn/pristine/e9/e9990f128dfb945f216de87f320fffbd740baf36.svn-base @ 1524:82fac3dcf466 redmine-2.5-integration

Fix failure to interpret Javascript when autocompleting members for project
author Chris Cannam <chris.cannam@soundsoftware.ac.uk>
date Thu, 11 Sep 2014 10:24:38 +0100
parents cbb26bc654de
children
rev   line source
Chris@909 1 #!/usr/local/bin/ruby -w
Chris@909 2
Chris@909 3 # = faster_csv.rb -- Faster CSV Reading and Writing
Chris@909 4 #
Chris@909 5 # Created by James Edward Gray II on 2005-10-31.
Chris@909 6 # Copyright 2005 Gray Productions. All rights reserved.
Chris@909 7 #
Chris@909 8 # See FasterCSV for documentation.
Chris@909 9
Chris@909 10 if RUBY_VERSION >= "1.9"
Chris@909 11 abort <<-VERSION_WARNING.gsub(/^\s+/, "")
Chris@909 12 Please switch to Ruby 1.9's standard CSV library. It's FasterCSV plus
Chris@909 13 support for Ruby 1.9's m17n encoding engine.
Chris@909 14 VERSION_WARNING
Chris@909 15 end
Chris@909 16
Chris@909 17 require "forwardable"
Chris@909 18 require "English"
Chris@909 19 require "enumerator"
Chris@909 20 require "date"
Chris@909 21 require "stringio"
Chris@909 22
Chris@909 23 #
Chris@909 24 # This class provides a complete interface to CSV files and data. It offers
Chris@909 25 # tools to enable you to read and write to and from Strings or IO objects, as
Chris@909 26 # needed.
Chris@909 27 #
Chris@909 28 # == Reading
Chris@909 29 #
Chris@909 30 # === From a File
Chris@909 31 #
Chris@909 32 # ==== A Line at a Time
Chris@909 33 #
Chris@909 34 # FasterCSV.foreach("path/to/file.csv") do |row|
Chris@909 35 # # use row here...
Chris@909 36 # end
Chris@909 37 #
Chris@909 38 # ==== All at Once
Chris@909 39 #
Chris@909 40 # arr_of_arrs = FasterCSV.read("path/to/file.csv")
Chris@909 41 #
Chris@909 42 # === From a String
Chris@909 43 #
Chris@909 44 # ==== A Line at a Time
Chris@909 45 #
Chris@909 46 # FasterCSV.parse("CSV,data,String") do |row|
Chris@909 47 # # use row here...
Chris@909 48 # end
Chris@909 49 #
Chris@909 50 # ==== All at Once
Chris@909 51 #
Chris@909 52 # arr_of_arrs = FasterCSV.parse("CSV,data,String")
Chris@909 53 #
Chris@909 54 # == Writing
Chris@909 55 #
Chris@909 56 # === To a File
Chris@909 57 #
Chris@909 58 # FasterCSV.open("path/to/file.csv", "w") do |csv|
Chris@909 59 # csv << ["row", "of", "CSV", "data"]
Chris@909 60 # csv << ["another", "row"]
Chris@909 61 # # ...
Chris@909 62 # end
Chris@909 63 #
Chris@909 64 # === To a String
Chris@909 65 #
Chris@909 66 # csv_string = FasterCSV.generate do |csv|
Chris@909 67 # csv << ["row", "of", "CSV", "data"]
Chris@909 68 # csv << ["another", "row"]
Chris@909 69 # # ...
Chris@909 70 # end
Chris@909 71 #
Chris@909 72 # == Convert a Single Line
Chris@909 73 #
Chris@909 74 # csv_string = ["CSV", "data"].to_csv # to CSV
Chris@909 75 # csv_array = "CSV,String".parse_csv # from CSV
Chris@909 76 #
Chris@909 77 # == Shortcut Interface
Chris@909 78 #
Chris@909 79 # FCSV { |csv_out| csv_out << %w{my data here} } # to $stdout
Chris@909 80 # FCSV(csv = "") { |csv_str| csv_str << %w{my data here} } # to a String
Chris@909 81 # FCSV($stderr) { |csv_err| csv_err << %w{my data here} } # to $stderr
Chris@909 82 #
Chris@909 83 class FasterCSV
Chris@909 84 # The version of the installed library.
Chris@909 85 VERSION = "1.5.0".freeze
Chris@909 86
Chris@909 87 #
Chris@909 88 # A FasterCSV::Row is part Array and part Hash. It retains an order for the
Chris@909 89 # fields and allows duplicates just as an Array would, but also allows you to
Chris@909 90 # access fields by name just as you could if they were in a Hash.
Chris@909 91 #
Chris@909 92 # All rows returned by FasterCSV will be constructed from this class, if
Chris@909 93 # header row processing is activated.
Chris@909 94 #
Chris@909 95 class Row
Chris@909 96 #
Chris@909 97 # Construct a new FasterCSV::Row from +headers+ and +fields+, which are
Chris@909 98 # expected to be Arrays. If one Array is shorter than the other, it will be
Chris@909 99 # padded with +nil+ objects.
Chris@909 100 #
Chris@909 101 # The optional +header_row+ parameter can be set to +true+ to indicate, via
Chris@909 102 # FasterCSV::Row.header_row?() and FasterCSV::Row.field_row?(), that this is
Chris@909 103 # a header row. Otherwise, the row is assumes to be a field row.
Chris@909 104 #
Chris@909 105 # A FasterCSV::Row object supports the following Array methods through
Chris@909 106 # delegation:
Chris@909 107 #
Chris@909 108 # * empty?()
Chris@909 109 # * length()
Chris@909 110 # * size()
Chris@909 111 #
Chris@909 112 def initialize(headers, fields, header_row = false)
Chris@909 113 @header_row = header_row
Chris@909 114
Chris@909 115 # handle extra headers or fields
Chris@909 116 @row = if headers.size > fields.size
Chris@909 117 headers.zip(fields)
Chris@909 118 else
Chris@909 119 fields.zip(headers).map { |pair| pair.reverse }
Chris@909 120 end
Chris@909 121 end
Chris@909 122
Chris@909 123 # Internal data format used to compare equality.
Chris@909 124 attr_reader :row
Chris@909 125 protected :row
Chris@909 126
Chris@909 127 ### Array Delegation ###
Chris@909 128
Chris@909 129 extend Forwardable
Chris@909 130 def_delegators :@row, :empty?, :length, :size
Chris@909 131
Chris@909 132 # Returns +true+ if this is a header row.
Chris@909 133 def header_row?
Chris@909 134 @header_row
Chris@909 135 end
Chris@909 136
Chris@909 137 # Returns +true+ if this is a field row.
Chris@909 138 def field_row?
Chris@909 139 not header_row?
Chris@909 140 end
Chris@909 141
Chris@909 142 # Returns the headers of this row.
Chris@909 143 def headers
Chris@909 144 @row.map { |pair| pair.first }
Chris@909 145 end
Chris@909 146
Chris@909 147 #
Chris@909 148 # :call-seq:
Chris@909 149 # field( header )
Chris@909 150 # field( header, offset )
Chris@909 151 # field( index )
Chris@909 152 #
Chris@909 153 # This method will fetch the field value by +header+ or +index+. If a field
Chris@909 154 # is not found, +nil+ is returned.
Chris@909 155 #
Chris@909 156 # When provided, +offset+ ensures that a header match occurrs on or later
Chris@909 157 # than the +offset+ index. You can use this to find duplicate headers,
Chris@909 158 # without resorting to hard-coding exact indices.
Chris@909 159 #
Chris@909 160 def field(header_or_index, minimum_index = 0)
Chris@909 161 # locate the pair
Chris@909 162 finder = header_or_index.is_a?(Integer) ? :[] : :assoc
Chris@909 163 pair = @row[minimum_index..-1].send(finder, header_or_index)
Chris@909 164
Chris@909 165 # return the field if we have a pair
Chris@909 166 pair.nil? ? nil : pair.last
Chris@909 167 end
Chris@909 168 alias_method :[], :field
Chris@909 169
Chris@909 170 #
Chris@909 171 # :call-seq:
Chris@909 172 # []=( header, value )
Chris@909 173 # []=( header, offset, value )
Chris@909 174 # []=( index, value )
Chris@909 175 #
Chris@909 176 # Looks up the field by the semantics described in FasterCSV::Row.field()
Chris@909 177 # and assigns the +value+.
Chris@909 178 #
Chris@909 179 # Assigning past the end of the row with an index will set all pairs between
Chris@909 180 # to <tt>[nil, nil]</tt>. Assigning to an unused header appends the new
Chris@909 181 # pair.
Chris@909 182 #
Chris@909 183 def []=(*args)
Chris@909 184 value = args.pop
Chris@909 185
Chris@909 186 if args.first.is_a? Integer
Chris@909 187 if @row[args.first].nil? # extending past the end with index
Chris@909 188 @row[args.first] = [nil, value]
Chris@909 189 @row.map! { |pair| pair.nil? ? [nil, nil] : pair }
Chris@909 190 else # normal index assignment
Chris@909 191 @row[args.first][1] = value
Chris@909 192 end
Chris@909 193 else
Chris@909 194 index = index(*args)
Chris@909 195 if index.nil? # appending a field
Chris@909 196 self << [args.first, value]
Chris@909 197 else # normal header assignment
Chris@909 198 @row[index][1] = value
Chris@909 199 end
Chris@909 200 end
Chris@909 201 end
Chris@909 202
Chris@909 203 #
Chris@909 204 # :call-seq:
Chris@909 205 # <<( field )
Chris@909 206 # <<( header_and_field_array )
Chris@909 207 # <<( header_and_field_hash )
Chris@909 208 #
Chris@909 209 # If a two-element Array is provided, it is assumed to be a header and field
Chris@909 210 # and the pair is appended. A Hash works the same way with the key being
Chris@909 211 # the header and the value being the field. Anything else is assumed to be
Chris@909 212 # a lone field which is appended with a +nil+ header.
Chris@909 213 #
Chris@909 214 # This method returns the row for chaining.
Chris@909 215 #
Chris@909 216 def <<(arg)
Chris@909 217 if arg.is_a?(Array) and arg.size == 2 # appending a header and name
Chris@909 218 @row << arg
Chris@909 219 elsif arg.is_a?(Hash) # append header and name pairs
Chris@909 220 arg.each { |pair| @row << pair }
Chris@909 221 else # append field value
Chris@909 222 @row << [nil, arg]
Chris@909 223 end
Chris@909 224
Chris@909 225 self # for chaining
Chris@909 226 end
Chris@909 227
Chris@909 228 #
Chris@909 229 # A shortcut for appending multiple fields. Equivalent to:
Chris@909 230 #
Chris@909 231 # args.each { |arg| faster_csv_row << arg }
Chris@909 232 #
Chris@909 233 # This method returns the row for chaining.
Chris@909 234 #
Chris@909 235 def push(*args)
Chris@909 236 args.each { |arg| self << arg }
Chris@909 237
Chris@909 238 self # for chaining
Chris@909 239 end
Chris@909 240
Chris@909 241 #
Chris@909 242 # :call-seq:
Chris@909 243 # delete( header )
Chris@909 244 # delete( header, offset )
Chris@909 245 # delete( index )
Chris@909 246 #
Chris@909 247 # Used to remove a pair from the row by +header+ or +index+. The pair is
Chris@909 248 # located as described in FasterCSV::Row.field(). The deleted pair is
Chris@909 249 # returned, or +nil+ if a pair could not be found.
Chris@909 250 #
Chris@909 251 def delete(header_or_index, minimum_index = 0)
Chris@909 252 if header_or_index.is_a? Integer # by index
Chris@909 253 @row.delete_at(header_or_index)
Chris@909 254 else # by header
Chris@909 255 @row.delete_at(index(header_or_index, minimum_index))
Chris@909 256 end
Chris@909 257 end
Chris@909 258
Chris@909 259 #
Chris@909 260 # The provided +block+ is passed a header and field for each pair in the row
Chris@909 261 # and expected to return +true+ or +false+, depending on whether the pair
Chris@909 262 # should be deleted.
Chris@909 263 #
Chris@909 264 # This method returns the row for chaining.
Chris@909 265 #
Chris@909 266 def delete_if(&block)
Chris@909 267 @row.delete_if(&block)
Chris@909 268
Chris@909 269 self # for chaining
Chris@909 270 end
Chris@909 271
Chris@909 272 #
Chris@909 273 # This method accepts any number of arguments which can be headers, indices,
Chris@909 274 # Ranges of either, or two-element Arrays containing a header and offset.
Chris@909 275 # Each argument will be replaced with a field lookup as described in
Chris@909 276 # FasterCSV::Row.field().
Chris@909 277 #
Chris@909 278 # If called with no arguments, all fields are returned.
Chris@909 279 #
Chris@909 280 def fields(*headers_and_or_indices)
Chris@909 281 if headers_and_or_indices.empty? # return all fields--no arguments
Chris@909 282 @row.map { |pair| pair.last }
Chris@909 283 else # or work like values_at()
Chris@909 284 headers_and_or_indices.inject(Array.new) do |all, h_or_i|
Chris@909 285 all + if h_or_i.is_a? Range
Chris@909 286 index_begin = h_or_i.begin.is_a?(Integer) ? h_or_i.begin :
Chris@909 287 index(h_or_i.begin)
Chris@909 288 index_end = h_or_i.end.is_a?(Integer) ? h_or_i.end :
Chris@909 289 index(h_or_i.end)
Chris@909 290 new_range = h_or_i.exclude_end? ? (index_begin...index_end) :
Chris@909 291 (index_begin..index_end)
Chris@909 292 fields.values_at(new_range)
Chris@909 293 else
Chris@909 294 [field(*Array(h_or_i))]
Chris@909 295 end
Chris@909 296 end
Chris@909 297 end
Chris@909 298 end
Chris@909 299 alias_method :values_at, :fields
Chris@909 300
Chris@909 301 #
Chris@909 302 # :call-seq:
Chris@909 303 # index( header )
Chris@909 304 # index( header, offset )
Chris@909 305 #
Chris@909 306 # This method will return the index of a field with the provided +header+.
Chris@909 307 # The +offset+ can be used to locate duplicate header names, as described in
Chris@909 308 # FasterCSV::Row.field().
Chris@909 309 #
Chris@909 310 def index(header, minimum_index = 0)
Chris@909 311 # find the pair
Chris@909 312 index = headers[minimum_index..-1].index(header)
Chris@909 313 # return the index at the right offset, if we found one
Chris@909 314 index.nil? ? nil : index + minimum_index
Chris@909 315 end
Chris@909 316
Chris@909 317 # Returns +true+ if +name+ is a header for this row, and +false+ otherwise.
Chris@909 318 def header?(name)
Chris@909 319 headers.include? name
Chris@909 320 end
Chris@909 321 alias_method :include?, :header?
Chris@909 322
Chris@909 323 #
Chris@909 324 # Returns +true+ if +data+ matches a field in this row, and +false+
Chris@909 325 # otherwise.
Chris@909 326 #
Chris@909 327 def field?(data)
Chris@909 328 fields.include? data
Chris@909 329 end
Chris@909 330
Chris@909 331 include Enumerable
Chris@909 332
Chris@909 333 #
Chris@909 334 # Yields each pair of the row as header and field tuples (much like
Chris@909 335 # iterating over a Hash).
Chris@909 336 #
Chris@909 337 # Support for Enumerable.
Chris@909 338 #
Chris@909 339 # This method returns the row for chaining.
Chris@909 340 #
Chris@909 341 def each(&block)
Chris@909 342 @row.each(&block)
Chris@909 343
Chris@909 344 self # for chaining
Chris@909 345 end
Chris@909 346
Chris@909 347 #
Chris@909 348 # Returns +true+ if this row contains the same headers and fields in the
Chris@909 349 # same order as +other+.
Chris@909 350 #
Chris@909 351 def ==(other)
Chris@909 352 @row == other.row
Chris@909 353 end
Chris@909 354
Chris@909 355 #
Chris@909 356 # Collapses the row into a simple Hash. Be warning that this discards field
Chris@909 357 # order and clobbers duplicate fields.
Chris@909 358 #
Chris@909 359 def to_hash
Chris@909 360 # flatten just one level of the internal Array
Chris@909 361 Hash[*@row.inject(Array.new) { |ary, pair| ary.push(*pair) }]
Chris@909 362 end
Chris@909 363
Chris@909 364 #
Chris@909 365 # Returns the row as a CSV String. Headers are not used. Equivalent to:
Chris@909 366 #
Chris@909 367 # faster_csv_row.fields.to_csv( options )
Chris@909 368 #
Chris@909 369 def to_csv(options = Hash.new)
Chris@909 370 fields.to_csv(options)
Chris@909 371 end
Chris@909 372 alias_method :to_s, :to_csv
Chris@909 373
Chris@909 374 # A summary of fields, by header.
Chris@909 375 def inspect
Chris@909 376 str = "#<#{self.class}"
Chris@909 377 each do |header, field|
Chris@909 378 str << " #{header.is_a?(Symbol) ? header.to_s : header.inspect}:" <<
Chris@909 379 field.inspect
Chris@909 380 end
Chris@909 381 str << ">"
Chris@909 382 end
Chris@909 383 end
Chris@909 384
Chris@909 385 #
Chris@909 386 # A FasterCSV::Table is a two-dimensional data structure for representing CSV
Chris@909 387 # documents. Tables allow you to work with the data by row or column,
Chris@909 388 # manipulate the data, and even convert the results back to CSV, if needed.
Chris@909 389 #
Chris@909 390 # All tables returned by FasterCSV will be constructed from this class, if
Chris@909 391 # header row processing is activated.
Chris@909 392 #
Chris@909 393 class Table
Chris@909 394 #
Chris@909 395 # Construct a new FasterCSV::Table from +array_of_rows+, which are expected
Chris@909 396 # to be FasterCSV::Row objects. All rows are assumed to have the same
Chris@909 397 # headers.
Chris@909 398 #
Chris@909 399 # A FasterCSV::Table object supports the following Array methods through
Chris@909 400 # delegation:
Chris@909 401 #
Chris@909 402 # * empty?()
Chris@909 403 # * length()
Chris@909 404 # * size()
Chris@909 405 #
Chris@909 406 def initialize(array_of_rows)
Chris@909 407 @table = array_of_rows
Chris@909 408 @mode = :col_or_row
Chris@909 409 end
Chris@909 410
Chris@909 411 # The current access mode for indexing and iteration.
Chris@909 412 attr_reader :mode
Chris@909 413
Chris@909 414 # Internal data format used to compare equality.
Chris@909 415 attr_reader :table
Chris@909 416 protected :table
Chris@909 417
Chris@909 418 ### Array Delegation ###
Chris@909 419
Chris@909 420 extend Forwardable
Chris@909 421 def_delegators :@table, :empty?, :length, :size
Chris@909 422
Chris@909 423 #
Chris@909 424 # Returns a duplicate table object, in column mode. This is handy for
Chris@909 425 # chaining in a single call without changing the table mode, but be aware
Chris@909 426 # that this method can consume a fair amount of memory for bigger data sets.
Chris@909 427 #
Chris@909 428 # This method returns the duplicate table for chaining. Don't chain
Chris@909 429 # destructive methods (like []=()) this way though, since you are working
Chris@909 430 # with a duplicate.
Chris@909 431 #
Chris@909 432 def by_col
Chris@909 433 self.class.new(@table.dup).by_col!
Chris@909 434 end
Chris@909 435
Chris@909 436 #
Chris@909 437 # Switches the mode of this table to column mode. All calls to indexing and
Chris@909 438 # iteration methods will work with columns until the mode is changed again.
Chris@909 439 #
Chris@909 440 # This method returns the table and is safe to chain.
Chris@909 441 #
Chris@909 442 def by_col!
Chris@909 443 @mode = :col
Chris@909 444
Chris@909 445 self
Chris@909 446 end
Chris@909 447
Chris@909 448 #
Chris@909 449 # Returns a duplicate table object, in mixed mode. This is handy for
Chris@909 450 # chaining in a single call without changing the table mode, but be aware
Chris@909 451 # that this method can consume a fair amount of memory for bigger data sets.
Chris@909 452 #
Chris@909 453 # This method returns the duplicate table for chaining. Don't chain
Chris@909 454 # destructive methods (like []=()) this way though, since you are working
Chris@909 455 # with a duplicate.
Chris@909 456 #
Chris@909 457 def by_col_or_row
Chris@909 458 self.class.new(@table.dup).by_col_or_row!
Chris@909 459 end
Chris@909 460
Chris@909 461 #
Chris@909 462 # Switches the mode of this table to mixed mode. All calls to indexing and
Chris@909 463 # iteration methods will use the default intelligent indexing system until
Chris@909 464 # the mode is changed again. In mixed mode an index is assumed to be a row
Chris@909 465 # reference while anything else is assumed to be column access by headers.
Chris@909 466 #
Chris@909 467 # This method returns the table and is safe to chain.
Chris@909 468 #
Chris@909 469 def by_col_or_row!
Chris@909 470 @mode = :col_or_row
Chris@909 471
Chris@909 472 self
Chris@909 473 end
Chris@909 474
Chris@909 475 #
Chris@909 476 # Returns a duplicate table object, in row mode. This is handy for chaining
Chris@909 477 # in a single call without changing the table mode, but be aware that this
Chris@909 478 # method can consume a fair amount of memory for bigger data sets.
Chris@909 479 #
Chris@909 480 # This method returns the duplicate table for chaining. Don't chain
Chris@909 481 # destructive methods (like []=()) this way though, since you are working
Chris@909 482 # with a duplicate.
Chris@909 483 #
Chris@909 484 def by_row
Chris@909 485 self.class.new(@table.dup).by_row!
Chris@909 486 end
Chris@909 487
Chris@909 488 #
Chris@909 489 # Switches the mode of this table to row mode. All calls to indexing and
Chris@909 490 # iteration methods will work with rows until the mode is changed again.
Chris@909 491 #
Chris@909 492 # This method returns the table and is safe to chain.
Chris@909 493 #
Chris@909 494 def by_row!
Chris@909 495 @mode = :row
Chris@909 496
Chris@909 497 self
Chris@909 498 end
Chris@909 499
Chris@909 500 #
Chris@909 501 # Returns the headers for the first row of this table (assumed to match all
Chris@909 502 # other rows). An empty Array is returned for empty tables.
Chris@909 503 #
Chris@909 504 def headers
Chris@909 505 if @table.empty?
Chris@909 506 Array.new
Chris@909 507 else
Chris@909 508 @table.first.headers
Chris@909 509 end
Chris@909 510 end
Chris@909 511
Chris@909 512 #
Chris@909 513 # In the default mixed mode, this method returns rows for index access and
Chris@909 514 # columns for header access. You can force the index association by first
Chris@909 515 # calling by_col!() or by_row!().
Chris@909 516 #
Chris@909 517 # Columns are returned as an Array of values. Altering that Array has no
Chris@909 518 # effect on the table.
Chris@909 519 #
Chris@909 520 def [](index_or_header)
Chris@909 521 if @mode == :row or # by index
Chris@909 522 (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@909 523 @table[index_or_header]
Chris@909 524 else # by header
Chris@909 525 @table.map { |row| row[index_or_header] }
Chris@909 526 end
Chris@909 527 end
Chris@909 528
Chris@909 529 #
Chris@909 530 # In the default mixed mode, this method assigns rows for index access and
Chris@909 531 # columns for header access. You can force the index association by first
Chris@909 532 # calling by_col!() or by_row!().
Chris@909 533 #
Chris@909 534 # Rows may be set to an Array of values (which will inherit the table's
Chris@909 535 # headers()) or a FasterCSV::Row.
Chris@909 536 #
Chris@909 537 # Columns may be set to a single value, which is copied to each row of the
Chris@909 538 # column, or an Array of values. Arrays of values are assigned to rows top
Chris@909 539 # to bottom in row major order. Excess values are ignored and if the Array
Chris@909 540 # does not have a value for each row the extra rows will receive a +nil+.
Chris@909 541 #
Chris@909 542 # Assigning to an existing column or row clobbers the data. Assigning to
Chris@909 543 # new columns creates them at the right end of the table.
Chris@909 544 #
Chris@909 545 def []=(index_or_header, value)
Chris@909 546 if @mode == :row or # by index
Chris@909 547 (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@909 548 if value.is_a? Array
Chris@909 549 @table[index_or_header] = Row.new(headers, value)
Chris@909 550 else
Chris@909 551 @table[index_or_header] = value
Chris@909 552 end
Chris@909 553 else # set column
Chris@909 554 if value.is_a? Array # multiple values
Chris@909 555 @table.each_with_index do |row, i|
Chris@909 556 if row.header_row?
Chris@909 557 row[index_or_header] = index_or_header
Chris@909 558 else
Chris@909 559 row[index_or_header] = value[i]
Chris@909 560 end
Chris@909 561 end
Chris@909 562 else # repeated value
Chris@909 563 @table.each do |row|
Chris@909 564 if row.header_row?
Chris@909 565 row[index_or_header] = index_or_header
Chris@909 566 else
Chris@909 567 row[index_or_header] = value
Chris@909 568 end
Chris@909 569 end
Chris@909 570 end
Chris@909 571 end
Chris@909 572 end
Chris@909 573
Chris@909 574 #
Chris@909 575 # The mixed mode default is to treat a list of indices as row access,
Chris@909 576 # returning the rows indicated. Anything else is considered columnar
Chris@909 577 # access. For columnar access, the return set has an Array for each row
Chris@909 578 # with the values indicated by the headers in each Array. You can force
Chris@909 579 # column or row mode using by_col!() or by_row!().
Chris@909 580 #
Chris@909 581 # You cannot mix column and row access.
Chris@909 582 #
Chris@909 583 def values_at(*indices_or_headers)
Chris@909 584 if @mode == :row or # by indices
Chris@909 585 ( @mode == :col_or_row and indices_or_headers.all? do |index|
Chris@909 586 index.is_a?(Integer) or
Chris@909 587 ( index.is_a?(Range) and
Chris@909 588 index.first.is_a?(Integer) and
Chris@909 589 index.last.is_a?(Integer) )
Chris@909 590 end )
Chris@909 591 @table.values_at(*indices_or_headers)
Chris@909 592 else # by headers
Chris@909 593 @table.map { |row| row.values_at(*indices_or_headers) }
Chris@909 594 end
Chris@909 595 end
Chris@909 596
Chris@909 597 #
Chris@909 598 # Adds a new row to the bottom end of this table. You can provide an Array,
Chris@909 599 # which will be converted to a FasterCSV::Row (inheriting the table's
Chris@909 600 # headers()), or a FasterCSV::Row.
Chris@909 601 #
Chris@909 602 # This method returns the table for chaining.
Chris@909 603 #
Chris@909 604 def <<(row_or_array)
Chris@909 605 if row_or_array.is_a? Array # append Array
Chris@909 606 @table << Row.new(headers, row_or_array)
Chris@909 607 else # append Row
Chris@909 608 @table << row_or_array
Chris@909 609 end
Chris@909 610
Chris@909 611 self # for chaining
Chris@909 612 end
Chris@909 613
Chris@909 614 #
Chris@909 615 # A shortcut for appending multiple rows. Equivalent to:
Chris@909 616 #
Chris@909 617 # rows.each { |row| self << row }
Chris@909 618 #
Chris@909 619 # This method returns the table for chaining.
Chris@909 620 #
Chris@909 621 def push(*rows)
Chris@909 622 rows.each { |row| self << row }
Chris@909 623
Chris@909 624 self # for chaining
Chris@909 625 end
Chris@909 626
Chris@909 627 #
Chris@909 628 # Removes and returns the indicated column or row. In the default mixed
Chris@909 629 # mode indices refer to rows and everything else is assumed to be a column
Chris@909 630 # header. Use by_col!() or by_row!() to force the lookup.
Chris@909 631 #
Chris@909 632 def delete(index_or_header)
Chris@909 633 if @mode == :row or # by index
Chris@909 634 (@mode == :col_or_row and index_or_header.is_a? Integer)
Chris@909 635 @table.delete_at(index_or_header)
Chris@909 636 else # by header
Chris@909 637 @table.map { |row| row.delete(index_or_header).last }
Chris@909 638 end
Chris@909 639 end
Chris@909 640
Chris@909 641 #
Chris@909 642 # Removes any column or row for which the block returns +true+. In the
Chris@909 643 # default mixed mode or row mode, iteration is the standard row major
Chris@909 644 # walking of rows. In column mode, interation will +yield+ two element
Chris@909 645 # tuples containing the column name and an Array of values for that column.
Chris@909 646 #
Chris@909 647 # This method returns the table for chaining.
Chris@909 648 #
Chris@909 649 def delete_if(&block)
Chris@909 650 if @mode == :row or @mode == :col_or_row # by index
Chris@909 651 @table.delete_if(&block)
Chris@909 652 else # by header
Chris@909 653 to_delete = Array.new
Chris@909 654 headers.each_with_index do |header, i|
Chris@909 655 to_delete << header if block[[header, self[header]]]
Chris@909 656 end
Chris@909 657 to_delete.map { |header| delete(header) }
Chris@909 658 end
Chris@909 659
Chris@909 660 self # for chaining
Chris@909 661 end
Chris@909 662
Chris@909 663 include Enumerable
Chris@909 664
Chris@909 665 #
Chris@909 666 # In the default mixed mode or row mode, iteration is the standard row major
Chris@909 667 # walking of rows. In column mode, interation will +yield+ two element
Chris@909 668 # tuples containing the column name and an Array of values for that column.
Chris@909 669 #
Chris@909 670 # This method returns the table for chaining.
Chris@909 671 #
Chris@909 672 def each(&block)
Chris@909 673 if @mode == :col
Chris@909 674 headers.each { |header| block[[header, self[header]]] }
Chris@909 675 else
Chris@909 676 @table.each(&block)
Chris@909 677 end
Chris@909 678
Chris@909 679 self # for chaining
Chris@909 680 end
Chris@909 681
Chris@909 682 # Returns +true+ if all rows of this table ==() +other+'s rows.
Chris@909 683 def ==(other)
Chris@909 684 @table == other.table
Chris@909 685 end
Chris@909 686
Chris@909 687 #
Chris@909 688 # Returns the table as an Array of Arrays. Headers will be the first row,
Chris@909 689 # then all of the field rows will follow.
Chris@909 690 #
Chris@909 691 def to_a
Chris@909 692 @table.inject([headers]) do |array, row|
Chris@909 693 if row.header_row?
Chris@909 694 array
Chris@909 695 else
Chris@909 696 array + [row.fields]
Chris@909 697 end
Chris@909 698 end
Chris@909 699 end
Chris@909 700
Chris@909 701 #
Chris@909 702 # Returns the table as a complete CSV String. Headers will be listed first,
Chris@909 703 # then all of the field rows.
Chris@909 704 #
Chris@909 705 def to_csv(options = Hash.new)
Chris@909 706 @table.inject([headers.to_csv(options)]) do |rows, row|
Chris@909 707 if row.header_row?
Chris@909 708 rows
Chris@909 709 else
Chris@909 710 rows + [row.fields.to_csv(options)]
Chris@909 711 end
Chris@909 712 end.join
Chris@909 713 end
Chris@909 714 alias_method :to_s, :to_csv
Chris@909 715
Chris@909 716 def inspect
Chris@909 717 "#<#{self.class} mode:#{@mode} row_count:#{to_a.size}>"
Chris@909 718 end
Chris@909 719 end
Chris@909 720
Chris@909 721 # The error thrown when the parser encounters illegal CSV formatting.
Chris@909 722 class MalformedCSVError < RuntimeError; end
Chris@909 723
Chris@909 724 #
Chris@909 725 # A FieldInfo Struct contains details about a field's position in the data
Chris@909 726 # source it was read from. FasterCSV will pass this Struct to some blocks
Chris@909 727 # that make decisions based on field structure. See
Chris@909 728 # FasterCSV.convert_fields() for an example.
Chris@909 729 #
Chris@909 730 # <b><tt>index</tt></b>:: The zero-based index of the field in its row.
Chris@909 731 # <b><tt>line</tt></b>:: The line of the data source this row is from.
Chris@909 732 # <b><tt>header</tt></b>:: The header for the column, when available.
Chris@909 733 #
Chris@909 734 FieldInfo = Struct.new(:index, :line, :header)
Chris@909 735
Chris@909 736 # A Regexp used to find and convert some common Date formats.
Chris@909 737 DateMatcher = / \A(?: (\w+,?\s+)?\w+\s+\d{1,2},?\s+\d{2,4} |
Chris@909 738 \d{4}-\d{2}-\d{2} )\z /x
Chris@909 739 # A Regexp used to find and convert some common DateTime formats.
Chris@909 740 DateTimeMatcher =
Chris@909 741 / \A(?: (\w+,?\s+)?\w+\s+\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2},?\s+\d{2,4} |
Chris@909 742 \d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2} )\z /x
Chris@909 743 #
Chris@909 744 # This Hash holds the built-in converters of FasterCSV that can be accessed by
Chris@909 745 # name. You can select Converters with FasterCSV.convert() or through the
Chris@909 746 # +options+ Hash passed to FasterCSV::new().
Chris@909 747 #
Chris@909 748 # <b><tt>:integer</tt></b>:: Converts any field Integer() accepts.
Chris@909 749 # <b><tt>:float</tt></b>:: Converts any field Float() accepts.
Chris@909 750 # <b><tt>:numeric</tt></b>:: A combination of <tt>:integer</tt>
Chris@909 751 # and <tt>:float</tt>.
Chris@909 752 # <b><tt>:date</tt></b>:: Converts any field Date::parse() accepts.
Chris@909 753 # <b><tt>:date_time</tt></b>:: Converts any field DateTime::parse() accepts.
Chris@909 754 # <b><tt>:all</tt></b>:: All built-in converters. A combination of
Chris@909 755 # <tt>:date_time</tt> and <tt>:numeric</tt>.
Chris@909 756 #
Chris@909 757 # This Hash is intetionally left unfrozen and users should feel free to add
Chris@909 758 # values to it that can be accessed by all FasterCSV objects.
Chris@909 759 #
Chris@909 760 # To add a combo field, the value should be an Array of names. Combo fields
Chris@909 761 # can be nested with other combo fields.
Chris@909 762 #
Chris@909 763 Converters = { :integer => lambda { |f| Integer(f) rescue f },
Chris@909 764 :float => lambda { |f| Float(f) rescue f },
Chris@909 765 :numeric => [:integer, :float],
Chris@909 766 :date => lambda { |f|
Chris@909 767 f =~ DateMatcher ? (Date.parse(f) rescue f) : f
Chris@909 768 },
Chris@909 769 :date_time => lambda { |f|
Chris@909 770 f =~ DateTimeMatcher ? (DateTime.parse(f) rescue f) : f
Chris@909 771 },
Chris@909 772 :all => [:date_time, :numeric] }
Chris@909 773
Chris@909 774 #
Chris@909 775 # This Hash holds the built-in header converters of FasterCSV that can be
Chris@909 776 # accessed by name. You can select HeaderConverters with
Chris@909 777 # FasterCSV.header_convert() or through the +options+ Hash passed to
Chris@909 778 # FasterCSV::new().
Chris@909 779 #
Chris@909 780 # <b><tt>:downcase</tt></b>:: Calls downcase() on the header String.
Chris@909 781 # <b><tt>:symbol</tt></b>:: The header String is downcased, spaces are
Chris@909 782 # replaced with underscores, non-word characters
Chris@909 783 # are dropped, and finally to_sym() is called.
Chris@909 784 #
Chris@909 785 # This Hash is intetionally left unfrozen and users should feel free to add
Chris@909 786 # values to it that can be accessed by all FasterCSV objects.
Chris@909 787 #
Chris@909 788 # To add a combo field, the value should be an Array of names. Combo fields
Chris@909 789 # can be nested with other combo fields.
Chris@909 790 #
Chris@909 791 HeaderConverters = {
Chris@909 792 :downcase => lambda { |h| h.downcase },
Chris@909 793 :symbol => lambda { |h|
Chris@909 794 h.downcase.tr(" ", "_").delete("^a-z0-9_").to_sym
Chris@909 795 }
Chris@909 796 }
Chris@909 797
Chris@909 798 #
Chris@909 799 # The options used when no overrides are given by calling code. They are:
Chris@909 800 #
Chris@909 801 # <b><tt>:col_sep</tt></b>:: <tt>","</tt>
Chris@909 802 # <b><tt>:row_sep</tt></b>:: <tt>:auto</tt>
Chris@909 803 # <b><tt>:quote_char</tt></b>:: <tt>'"'</tt>
Chris@909 804 # <b><tt>:converters</tt></b>:: +nil+
Chris@909 805 # <b><tt>:unconverted_fields</tt></b>:: +nil+
Chris@909 806 # <b><tt>:headers</tt></b>:: +false+
Chris@909 807 # <b><tt>:return_headers</tt></b>:: +false+
Chris@909 808 # <b><tt>:header_converters</tt></b>:: +nil+
Chris@909 809 # <b><tt>:skip_blanks</tt></b>:: +false+
Chris@909 810 # <b><tt>:force_quotes</tt></b>:: +false+
Chris@909 811 #
Chris@909 812 DEFAULT_OPTIONS = { :col_sep => ",",
Chris@909 813 :row_sep => :auto,
Chris@909 814 :quote_char => '"',
Chris@909 815 :converters => nil,
Chris@909 816 :unconverted_fields => nil,
Chris@909 817 :headers => false,
Chris@909 818 :return_headers => false,
Chris@909 819 :header_converters => nil,
Chris@909 820 :skip_blanks => false,
Chris@909 821 :force_quotes => false }.freeze
Chris@909 822
Chris@909 823 #
Chris@909 824 # This method will build a drop-in replacement for many of the standard CSV
Chris@909 825 # methods. It allows you to write code like:
Chris@909 826 #
Chris@909 827 # begin
Chris@909 828 # require "faster_csv"
Chris@909 829 # FasterCSV.build_csv_interface
Chris@909 830 # rescue LoadError
Chris@909 831 # require "csv"
Chris@909 832 # end
Chris@909 833 # # ... use CSV here ...
Chris@909 834 #
Chris@909 835 # This is not a complete interface with completely identical behavior.
Chris@909 836 # However, it is intended to be close enough that you won't notice the
Chris@909 837 # difference in most cases. CSV methods supported are:
Chris@909 838 #
Chris@909 839 # * foreach()
Chris@909 840 # * generate_line()
Chris@909 841 # * open()
Chris@909 842 # * parse()
Chris@909 843 # * parse_line()
Chris@909 844 # * readlines()
Chris@909 845 #
Chris@909 846 # Be warned that this interface is slower than vanilla FasterCSV due to the
Chris@909 847 # extra layer of method calls. Depending on usage, this can slow it down to
Chris@909 848 # near CSV speeds.
Chris@909 849 #
Chris@909 850 def self.build_csv_interface
Chris@909 851 Object.const_set(:CSV, Class.new).class_eval do
Chris@909 852 def self.foreach(path, rs = :auto, &block) # :nodoc:
Chris@909 853 FasterCSV.foreach(path, :row_sep => rs, &block)
Chris@909 854 end
Chris@909 855
Chris@909 856 def self.generate_line(row, fs = ",", rs = "") # :nodoc:
Chris@909 857 FasterCSV.generate_line(row, :col_sep => fs, :row_sep => rs)
Chris@909 858 end
Chris@909 859
Chris@909 860 def self.open(path, mode, fs = ",", rs = :auto, &block) # :nodoc:
Chris@909 861 if block and mode.include? "r"
Chris@909 862 FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs) do |csv|
Chris@909 863 csv.each(&block)
Chris@909 864 end
Chris@909 865 else
Chris@909 866 FasterCSV.open(path, mode, :col_sep => fs, :row_sep => rs, &block)
Chris@909 867 end
Chris@909 868 end
Chris@909 869
Chris@909 870 def self.parse(str_or_readable, fs = ",", rs = :auto, &block) # :nodoc:
Chris@909 871 FasterCSV.parse(str_or_readable, :col_sep => fs, :row_sep => rs, &block)
Chris@909 872 end
Chris@909 873
Chris@909 874 def self.parse_line(src, fs = ",", rs = :auto) # :nodoc:
Chris@909 875 FasterCSV.parse_line(src, :col_sep => fs, :row_sep => rs)
Chris@909 876 end
Chris@909 877
Chris@909 878 def self.readlines(path, rs = :auto) # :nodoc:
Chris@909 879 FasterCSV.readlines(path, :row_sep => rs)
Chris@909 880 end
Chris@909 881 end
Chris@909 882 end
Chris@909 883
Chris@909 884 #
Chris@909 885 # This method allows you to serialize an Array of Ruby objects to a String or
Chris@909 886 # File of CSV data. This is not as powerful as Marshal or YAML, but perhaps
Chris@909 887 # useful for spreadsheet and database interaction.
Chris@909 888 #
Chris@909 889 # Out of the box, this method is intended to work with simple data objects or
Chris@909 890 # Structs. It will serialize a list of instance variables and/or
Chris@909 891 # Struct.members().
Chris@909 892 #
Chris@909 893 # If you need need more complicated serialization, you can control the process
Chris@909 894 # by adding methods to the class to be serialized.
Chris@909 895 #
Chris@909 896 # A class method csv_meta() is responsible for returning the first row of the
Chris@909 897 # document (as an Array). This row is considered to be a Hash of the form
Chris@909 898 # key_1,value_1,key_2,value_2,... FasterCSV::load() expects to find a class
Chris@909 899 # key with a value of the stringified class name and FasterCSV::dump() will
Chris@909 900 # create this, if you do not define this method. This method is only called
Chris@909 901 # on the first object of the Array.
Chris@909 902 #
Chris@909 903 # The next method you can provide is an instance method called csv_headers().
Chris@909 904 # This method is expected to return the second line of the document (again as
Chris@909 905 # an Array), which is to be used to give each column a header. By default,
Chris@909 906 # FasterCSV::load() will set an instance variable if the field header starts
Chris@909 907 # with an @ character or call send() passing the header as the method name and
Chris@909 908 # the field value as an argument. This method is only called on the first
Chris@909 909 # object of the Array.
Chris@909 910 #
Chris@909 911 # Finally, you can provide an instance method called csv_dump(), which will
Chris@909 912 # be passed the headers. This should return an Array of fields that can be
Chris@909 913 # serialized for this object. This method is called once for every object in
Chris@909 914 # the Array.
Chris@909 915 #
Chris@909 916 # The +io+ parameter can be used to serialize to a File, and +options+ can be
Chris@909 917 # anything FasterCSV::new() accepts.
Chris@909 918 #
Chris@909 919 def self.dump(ary_of_objs, io = "", options = Hash.new)
Chris@909 920 obj_template = ary_of_objs.first
Chris@909 921
Chris@909 922 csv = FasterCSV.new(io, options)
Chris@909 923
Chris@909 924 # write meta information
Chris@909 925 begin
Chris@909 926 csv << obj_template.class.csv_meta
Chris@909 927 rescue NoMethodError
Chris@909 928 csv << [:class, obj_template.class]
Chris@909 929 end
Chris@909 930
Chris@909 931 # write headers
Chris@909 932 begin
Chris@909 933 headers = obj_template.csv_headers
Chris@909 934 rescue NoMethodError
Chris@909 935 headers = obj_template.instance_variables.sort
Chris@909 936 if obj_template.class.ancestors.find { |cls| cls.to_s =~ /\AStruct\b/ }
Chris@909 937 headers += obj_template.members.map { |mem| "#{mem}=" }.sort
Chris@909 938 end
Chris@909 939 end
Chris@909 940 csv << headers
Chris@909 941
Chris@909 942 # serialize each object
Chris@909 943 ary_of_objs.each do |obj|
Chris@909 944 begin
Chris@909 945 csv << obj.csv_dump(headers)
Chris@909 946 rescue NoMethodError
Chris@909 947 csv << headers.map do |var|
Chris@909 948 if var[0] == ?@
Chris@909 949 obj.instance_variable_get(var)
Chris@909 950 else
Chris@909 951 obj[var[0..-2]]
Chris@909 952 end
Chris@909 953 end
Chris@909 954 end
Chris@909 955 end
Chris@909 956
Chris@909 957 if io.is_a? String
Chris@909 958 csv.string
Chris@909 959 else
Chris@909 960 csv.close
Chris@909 961 end
Chris@909 962 end
Chris@909 963
Chris@909 964 #
Chris@909 965 # :call-seq:
Chris@909 966 # filter( options = Hash.new ) { |row| ... }
Chris@909 967 # filter( input, options = Hash.new ) { |row| ... }
Chris@909 968 # filter( input, output, options = Hash.new ) { |row| ... }
Chris@909 969 #
Chris@909 970 # This method is a convenience for building Unix-like filters for CSV data.
Chris@909 971 # Each row is yielded to the provided block which can alter it as needed.
Chris@909 972 # After the block returns, the row is appended to +output+ altered or not.
Chris@909 973 #
Chris@909 974 # The +input+ and +output+ arguments can be anything FasterCSV::new() accepts
Chris@909 975 # (generally String or IO objects). If not given, they default to
Chris@909 976 # <tt>ARGF</tt> and <tt>$stdout</tt>.
Chris@909 977 #
Chris@909 978 # The +options+ parameter is also filtered down to FasterCSV::new() after some
Chris@909 979 # clever key parsing. Any key beginning with <tt>:in_</tt> or
Chris@909 980 # <tt>:input_</tt> will have that leading identifier stripped and will only
Chris@909 981 # be used in the +options+ Hash for the +input+ object. Keys starting with
Chris@909 982 # <tt>:out_</tt> or <tt>:output_</tt> affect only +output+. All other keys
Chris@909 983 # are assigned to both objects.
Chris@909 984 #
Chris@909 985 # The <tt>:output_row_sep</tt> +option+ defaults to
Chris@909 986 # <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
Chris@909 987 #
Chris@909 988 def self.filter(*args)
Chris@909 989 # parse options for input, output, or both
Chris@909 990 in_options, out_options = Hash.new, {:row_sep => $INPUT_RECORD_SEPARATOR}
Chris@909 991 if args.last.is_a? Hash
Chris@909 992 args.pop.each do |key, value|
Chris@909 993 case key.to_s
Chris@909 994 when /\Ain(?:put)?_(.+)\Z/
Chris@909 995 in_options[$1.to_sym] = value
Chris@909 996 when /\Aout(?:put)?_(.+)\Z/
Chris@909 997 out_options[$1.to_sym] = value
Chris@909 998 else
Chris@909 999 in_options[key] = value
Chris@909 1000 out_options[key] = value
Chris@909 1001 end
Chris@909 1002 end
Chris@909 1003 end
Chris@909 1004 # build input and output wrappers
Chris@909 1005 input = FasterCSV.new(args.shift || ARGF, in_options)
Chris@909 1006 output = FasterCSV.new(args.shift || $stdout, out_options)
Chris@909 1007
Chris@909 1008 # read, yield, write
Chris@909 1009 input.each do |row|
Chris@909 1010 yield row
Chris@909 1011 output << row
Chris@909 1012 end
Chris@909 1013 end
Chris@909 1014
Chris@909 1015 #
Chris@909 1016 # This method is intended as the primary interface for reading CSV files. You
Chris@909 1017 # pass a +path+ and any +options+ you wish to set for the read. Each row of
Chris@909 1018 # file will be passed to the provided +block+ in turn.
Chris@909 1019 #
Chris@909 1020 # The +options+ parameter can be anything FasterCSV::new() understands.
Chris@909 1021 #
Chris@909 1022 def self.foreach(path, options = Hash.new, &block)
Chris@909 1023 open(path, "rb", options) do |csv|
Chris@909 1024 csv.each(&block)
Chris@909 1025 end
Chris@909 1026 end
Chris@909 1027
Chris@909 1028 #
Chris@909 1029 # :call-seq:
Chris@909 1030 # generate( str, options = Hash.new ) { |faster_csv| ... }
Chris@909 1031 # generate( options = Hash.new ) { |faster_csv| ... }
Chris@909 1032 #
Chris@909 1033 # This method wraps a String you provide, or an empty default String, in a
Chris@909 1034 # FasterCSV object which is passed to the provided block. You can use the
Chris@909 1035 # block to append CSV rows to the String and when the block exits, the
Chris@909 1036 # final String will be returned.
Chris@909 1037 #
Chris@909 1038 # Note that a passed String *is* modfied by this method. Call dup() before
Chris@909 1039 # passing if you need a new String.
Chris@909 1040 #
Chris@909 1041 # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@909 1042 #
Chris@909 1043 def self.generate(*args)
Chris@909 1044 # add a default empty String, if none was given
Chris@909 1045 if args.first.is_a? String
Chris@909 1046 io = StringIO.new(args.shift)
Chris@909 1047 io.seek(0, IO::SEEK_END)
Chris@909 1048 args.unshift(io)
Chris@909 1049 else
Chris@909 1050 args.unshift("")
Chris@909 1051 end
Chris@909 1052 faster_csv = new(*args) # wrap
Chris@909 1053 yield faster_csv # yield for appending
Chris@909 1054 faster_csv.string # return final String
Chris@909 1055 end
Chris@909 1056
Chris@909 1057 #
Chris@909 1058 # This method is a shortcut for converting a single row (Array) into a CSV
Chris@909 1059 # String.
Chris@909 1060 #
Chris@909 1061 # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@909 1062 #
Chris@909 1063 # The <tt>:row_sep</tt> +option+ defaults to <tt>$INPUT_RECORD_SEPARATOR</tt>
Chris@909 1064 # (<tt>$/</tt>) when calling this method.
Chris@909 1065 #
Chris@909 1066 def self.generate_line(row, options = Hash.new)
Chris@909 1067 options = {:row_sep => $INPUT_RECORD_SEPARATOR}.merge(options)
Chris@909 1068 (new("", options) << row).string
Chris@909 1069 end
Chris@909 1070
Chris@909 1071 #
Chris@909 1072 # This method will return a FasterCSV instance, just like FasterCSV::new(),
Chris@909 1073 # but the instance will be cached and returned for all future calls to this
Chris@909 1074 # method for the same +data+ object (tested by Object#object_id()) with the
Chris@909 1075 # same +options+.
Chris@909 1076 #
Chris@909 1077 # If a block is given, the instance is passed to the block and the return
Chris@909 1078 # value becomes the return value of the block.
Chris@909 1079 #
Chris@909 1080 def self.instance(data = $stdout, options = Hash.new)
Chris@909 1081 # create a _signature_ for this method call, data object and options
Chris@909 1082 sig = [data.object_id] +
Chris@909 1083 options.values_at(*DEFAULT_OPTIONS.keys.sort_by { |sym| sym.to_s })
Chris@909 1084
Chris@909 1085 # fetch or create the instance for this signature
Chris@909 1086 @@instances ||= Hash.new
Chris@909 1087 instance = (@@instances[sig] ||= new(data, options))
Chris@909 1088
Chris@909 1089 if block_given?
Chris@909 1090 yield instance # run block, if given, returning result
Chris@909 1091 else
Chris@909 1092 instance # or return the instance
Chris@909 1093 end
Chris@909 1094 end
Chris@909 1095
Chris@909 1096 #
Chris@909 1097 # This method is the reading counterpart to FasterCSV::dump(). See that
Chris@909 1098 # method for a detailed description of the process.
Chris@909 1099 #
Chris@909 1100 # You can customize loading by adding a class method called csv_load() which
Chris@909 1101 # will be passed a Hash of meta information, an Array of headers, and an Array
Chris@909 1102 # of fields for the object the method is expected to return.
Chris@909 1103 #
Chris@909 1104 # Remember that all fields will be Strings after this load. If you need
Chris@909 1105 # something else, use +options+ to setup converters or provide a custom
Chris@909 1106 # csv_load() implementation.
Chris@909 1107 #
Chris@909 1108 def self.load(io_or_str, options = Hash.new)
Chris@909 1109 csv = FasterCSV.new(io_or_str, options)
Chris@909 1110
Chris@909 1111 # load meta information
Chris@909 1112 meta = Hash[*csv.shift]
Chris@909 1113 cls = meta["class"].split("::").inject(Object) do |c, const|
Chris@909 1114 c.const_get(const)
Chris@909 1115 end
Chris@909 1116
Chris@909 1117 # load headers
Chris@909 1118 headers = csv.shift
Chris@909 1119
Chris@909 1120 # unserialize each object stored in the file
Chris@909 1121 results = csv.inject(Array.new) do |all, row|
Chris@909 1122 begin
Chris@909 1123 obj = cls.csv_load(meta, headers, row)
Chris@909 1124 rescue NoMethodError
Chris@909 1125 obj = cls.allocate
Chris@909 1126 headers.zip(row) do |name, value|
Chris@909 1127 if name[0] == ?@
Chris@909 1128 obj.instance_variable_set(name, value)
Chris@909 1129 else
Chris@909 1130 obj.send(name, value)
Chris@909 1131 end
Chris@909 1132 end
Chris@909 1133 end
Chris@909 1134 all << obj
Chris@909 1135 end
Chris@909 1136
Chris@909 1137 csv.close unless io_or_str.is_a? String
Chris@909 1138
Chris@909 1139 results
Chris@909 1140 end
Chris@909 1141
Chris@909 1142 #
Chris@909 1143 # :call-seq:
Chris@909 1144 # open( filename, mode="rb", options = Hash.new ) { |faster_csv| ... }
Chris@909 1145 # open( filename, mode="rb", options = Hash.new )
Chris@909 1146 #
Chris@909 1147 # This method opens an IO object, and wraps that with FasterCSV. This is
Chris@909 1148 # intended as the primary interface for writing a CSV file.
Chris@909 1149 #
Chris@909 1150 # You may pass any +args+ Ruby's open() understands followed by an optional
Chris@909 1151 # Hash containing any +options+ FasterCSV::new() understands.
Chris@909 1152 #
Chris@909 1153 # This method works like Ruby's open() call, in that it will pass a FasterCSV
Chris@909 1154 # object to a provided block and close it when the block termminates, or it
Chris@909 1155 # will return the FasterCSV object when no block is provided. (*Note*: This
Chris@909 1156 # is different from the standard CSV library which passes rows to the block.
Chris@909 1157 # Use FasterCSV::foreach() for that behavior.)
Chris@909 1158 #
Chris@909 1159 # An opened FasterCSV object will delegate to many IO methods, for
Chris@909 1160 # convenience. You may call:
Chris@909 1161 #
Chris@909 1162 # * binmode()
Chris@909 1163 # * close()
Chris@909 1164 # * close_read()
Chris@909 1165 # * close_write()
Chris@909 1166 # * closed?()
Chris@909 1167 # * eof()
Chris@909 1168 # * eof?()
Chris@909 1169 # * fcntl()
Chris@909 1170 # * fileno()
Chris@909 1171 # * flush()
Chris@909 1172 # * fsync()
Chris@909 1173 # * ioctl()
Chris@909 1174 # * isatty()
Chris@909 1175 # * pid()
Chris@909 1176 # * pos()
Chris@909 1177 # * reopen()
Chris@909 1178 # * seek()
Chris@909 1179 # * stat()
Chris@909 1180 # * sync()
Chris@909 1181 # * sync=()
Chris@909 1182 # * tell()
Chris@909 1183 # * to_i()
Chris@909 1184 # * to_io()
Chris@909 1185 # * tty?()
Chris@909 1186 #
Chris@909 1187 def self.open(*args)
Chris@909 1188 # find the +options+ Hash
Chris@909 1189 options = if args.last.is_a? Hash then args.pop else Hash.new end
Chris@909 1190 # default to a binary open mode
Chris@909 1191 args << "rb" if args.size == 1
Chris@909 1192 # wrap a File opened with the remaining +args+
Chris@909 1193 csv = new(File.open(*args), options)
Chris@909 1194
Chris@909 1195 # handle blocks like Ruby's open(), not like the CSV library
Chris@909 1196 if block_given?
Chris@909 1197 begin
Chris@909 1198 yield csv
Chris@909 1199 ensure
Chris@909 1200 csv.close
Chris@909 1201 end
Chris@909 1202 else
Chris@909 1203 csv
Chris@909 1204 end
Chris@909 1205 end
Chris@909 1206
Chris@909 1207 #
Chris@909 1208 # :call-seq:
Chris@909 1209 # parse( str, options = Hash.new ) { |row| ... }
Chris@909 1210 # parse( str, options = Hash.new )
Chris@909 1211 #
Chris@909 1212 # This method can be used to easily parse CSV out of a String. You may either
Chris@909 1213 # provide a +block+ which will be called with each row of the String in turn,
Chris@909 1214 # or just use the returned Array of Arrays (when no +block+ is given).
Chris@909 1215 #
Chris@909 1216 # You pass your +str+ to read from, and an optional +options+ Hash containing
Chris@909 1217 # anything FasterCSV::new() understands.
Chris@909 1218 #
Chris@909 1219 def self.parse(*args, &block)
Chris@909 1220 csv = new(*args)
Chris@909 1221 if block.nil? # slurp contents, if no block is given
Chris@909 1222 begin
Chris@909 1223 csv.read
Chris@909 1224 ensure
Chris@909 1225 csv.close
Chris@909 1226 end
Chris@909 1227 else # or pass each row to a provided block
Chris@909 1228 csv.each(&block)
Chris@909 1229 end
Chris@909 1230 end
Chris@909 1231
Chris@909 1232 #
Chris@909 1233 # This method is a shortcut for converting a single line of a CSV String into
Chris@909 1234 # a into an Array. Note that if +line+ contains multiple rows, anything
Chris@909 1235 # beyond the first row is ignored.
Chris@909 1236 #
Chris@909 1237 # The +options+ parameter can be anthing FasterCSV::new() understands.
Chris@909 1238 #
Chris@909 1239 def self.parse_line(line, options = Hash.new)
Chris@909 1240 new(line, options).shift
Chris@909 1241 end
Chris@909 1242
Chris@909 1243 #
Chris@909 1244 # Use to slurp a CSV file into an Array of Arrays. Pass the +path+ to the
Chris@909 1245 # file and any +options+ FasterCSV::new() understands.
Chris@909 1246 #
Chris@909 1247 def self.read(path, options = Hash.new)
Chris@909 1248 open(path, "rb", options) { |csv| csv.read }
Chris@909 1249 end
Chris@909 1250
Chris@909 1251 # Alias for FasterCSV::read().
Chris@909 1252 def self.readlines(*args)
Chris@909 1253 read(*args)
Chris@909 1254 end
Chris@909 1255
Chris@909 1256 #
Chris@909 1257 # A shortcut for:
Chris@909 1258 #
Chris@909 1259 # FasterCSV.read( path, { :headers => true,
Chris@909 1260 # :converters => :numeric,
Chris@909 1261 # :header_converters => :symbol }.merge(options) )
Chris@909 1262 #
Chris@909 1263 def self.table(path, options = Hash.new)
Chris@909 1264 read( path, { :headers => true,
Chris@909 1265 :converters => :numeric,
Chris@909 1266 :header_converters => :symbol }.merge(options) )
Chris@909 1267 end
Chris@909 1268
Chris@909 1269 #
Chris@909 1270 # This constructor will wrap either a String or IO object passed in +data+ for
Chris@909 1271 # reading and/or writing. In addition to the FasterCSV instance methods,
Chris@909 1272 # several IO methods are delegated. (See FasterCSV::open() for a complete
Chris@909 1273 # list.) If you pass a String for +data+, you can later retrieve it (after
Chris@909 1274 # writing to it, for example) with FasterCSV.string().
Chris@909 1275 #
Chris@909 1276 # Note that a wrapped String will be positioned at at the beginning (for
Chris@909 1277 # reading). If you want it at the end (for writing), use
Chris@909 1278 # FasterCSV::generate(). If you want any other positioning, pass a preset
Chris@909 1279 # StringIO object instead.
Chris@909 1280 #
Chris@909 1281 # You may set any reading and/or writing preferences in the +options+ Hash.
Chris@909 1282 # Available options are:
Chris@909 1283 #
Chris@909 1284 # <b><tt>:col_sep</tt></b>:: The String placed between each field.
Chris@909 1285 # <b><tt>:row_sep</tt></b>:: The String appended to the end of each
Chris@909 1286 # row. This can be set to the special
Chris@909 1287 # <tt>:auto</tt> setting, which requests
Chris@909 1288 # that FasterCSV automatically discover
Chris@909 1289 # this from the data. Auto-discovery
Chris@909 1290 # reads ahead in the data looking for
Chris@909 1291 # the next <tt>"\r\n"</tt>,
Chris@909 1292 # <tt>"\n"</tt>, or <tt>"\r"</tt>
Chris@909 1293 # sequence. A sequence will be selected
Chris@909 1294 # even if it occurs in a quoted field,
Chris@909 1295 # assuming that you would have the same
Chris@909 1296 # line endings there. If none of those
Chris@909 1297 # sequences is found, +data+ is
Chris@909 1298 # <tt>ARGF</tt>, <tt>STDIN</tt>,
Chris@909 1299 # <tt>STDOUT</tt>, or <tt>STDERR</tt>,
Chris@909 1300 # or the stream is only available for
Chris@909 1301 # output, the default
Chris@909 1302 # <tt>$INPUT_RECORD_SEPARATOR</tt>
Chris@909 1303 # (<tt>$/</tt>) is used. Obviously,
Chris@909 1304 # discovery takes a little time. Set
Chris@909 1305 # manually if speed is important. Also
Chris@909 1306 # note that IO objects should be opened
Chris@909 1307 # in binary mode on Windows if this
Chris@909 1308 # feature will be used as the
Chris@909 1309 # line-ending translation can cause
Chris@909 1310 # problems with resetting the document
Chris@909 1311 # position to where it was before the
Chris@909 1312 # read ahead.
Chris@909 1313 # <b><tt>:quote_char</tt></b>:: The character used to quote fields.
Chris@909 1314 # This has to be a single character
Chris@909 1315 # String. This is useful for
Chris@909 1316 # application that incorrectly use
Chris@909 1317 # <tt>'</tt> as the quote character
Chris@909 1318 # instead of the correct <tt>"</tt>.
Chris@909 1319 # FasterCSV will always consider a
Chris@909 1320 # double sequence this character to be
Chris@909 1321 # an escaped quote.
Chris@909 1322 # <b><tt>:encoding</tt></b>:: The encoding to use when parsing the
Chris@909 1323 # file. Defaults to your <tt>$KDOCE</tt>
Chris@909 1324 # setting. Valid values: <tt>`n’</tt> or
Chris@909 1325 # <tt>`N’</tt> for none, <tt>`e’</tt> or
Chris@909 1326 # <tt>`E’</tt> for EUC, <tt>`s’</tt> or
Chris@909 1327 # <tt>`S’</tt> for SJIS, and
Chris@909 1328 # <tt>`u’</tt> or <tt>`U’</tt> for UTF-8
Chris@909 1329 # (see Regexp.new()).
Chris@909 1330 # <b><tt>:field_size_limit</tt></b>:: This is a maximum size FasterCSV will
Chris@909 1331 # read ahead looking for the closing
Chris@909 1332 # quote for a field. (In truth, it
Chris@909 1333 # reads to the first line ending beyond
Chris@909 1334 # this size.) If a quote cannot be
Chris@909 1335 # found within the limit FasterCSV will
Chris@909 1336 # raise a MalformedCSVError, assuming
Chris@909 1337 # the data is faulty. You can use this
Chris@909 1338 # limit to prevent what are effectively
Chris@909 1339 # DoS attacks on the parser. However,
Chris@909 1340 # this limit can cause a legitimate
Chris@909 1341 # parse to fail and thus is set to
Chris@909 1342 # +nil+, or off, by default.
Chris@909 1343 # <b><tt>:converters</tt></b>:: An Array of names from the Converters
Chris@909 1344 # Hash and/or lambdas that handle custom
Chris@909 1345 # conversion. A single converter
Chris@909 1346 # doesn't have to be in an Array.
Chris@909 1347 # <b><tt>:unconverted_fields</tt></b>:: If set to +true+, an
Chris@909 1348 # unconverted_fields() method will be
Chris@909 1349 # added to all returned rows (Array or
Chris@909 1350 # FasterCSV::Row) that will return the
Chris@909 1351 # fields as they were before convertion.
Chris@909 1352 # Note that <tt>:headers</tt> supplied
Chris@909 1353 # by Array or String were not fields of
Chris@909 1354 # the document and thus will have an
Chris@909 1355 # empty Array attached.
Chris@909 1356 # <b><tt>:headers</tt></b>:: If set to <tt>:first_row</tt> or
Chris@909 1357 # +true+, the initial row of the CSV
Chris@909 1358 # file will be treated as a row of
Chris@909 1359 # headers. If set to an Array, the
Chris@909 1360 # contents will be used as the headers.
Chris@909 1361 # If set to a String, the String is run
Chris@909 1362 # through a call of
Chris@909 1363 # FasterCSV::parse_line() with the same
Chris@909 1364 # <tt>:col_sep</tt>, <tt>:row_sep</tt>,
Chris@909 1365 # and <tt>:quote_char</tt> as this
Chris@909 1366 # instance to produce an Array of
Chris@909 1367 # headers. This setting causes
Chris@909 1368 # FasterCSV.shift() to return rows as
Chris@909 1369 # FasterCSV::Row objects instead of
Chris@909 1370 # Arrays and FasterCSV.read() to return
Chris@909 1371 # FasterCSV::Table objects instead of
Chris@909 1372 # an Array of Arrays.
Chris@909 1373 # <b><tt>:return_headers</tt></b>:: When +false+, header rows are silently
Chris@909 1374 # swallowed. If set to +true+, header
Chris@909 1375 # rows are returned in a FasterCSV::Row
Chris@909 1376 # object with identical headers and
Chris@909 1377 # fields (save that the fields do not go
Chris@909 1378 # through the converters).
Chris@909 1379 # <b><tt>:write_headers</tt></b>:: When +true+ and <tt>:headers</tt> is
Chris@909 1380 # set, a header row will be added to the
Chris@909 1381 # output.
Chris@909 1382 # <b><tt>:header_converters</tt></b>:: Identical in functionality to
Chris@909 1383 # <tt>:converters</tt> save that the
Chris@909 1384 # conversions are only made to header
Chris@909 1385 # rows.
Chris@909 1386 # <b><tt>:skip_blanks</tt></b>:: When set to a +true+ value, FasterCSV
Chris@909 1387 # will skip over any rows with no
Chris@909 1388 # content.
Chris@909 1389 # <b><tt>:force_quotes</tt></b>:: When set to a +true+ value, FasterCSV
Chris@909 1390 # will quote all CSV fields it creates.
Chris@909 1391 #
Chris@909 1392 # See FasterCSV::DEFAULT_OPTIONS for the default settings.
Chris@909 1393 #
Chris@909 1394 # Options cannot be overriden in the instance methods for performance reasons,
Chris@909 1395 # so be sure to set what you want here.
Chris@909 1396 #
Chris@909 1397 def initialize(data, options = Hash.new)
Chris@909 1398 # build the options for this read/write
Chris@909 1399 options = DEFAULT_OPTIONS.merge(options)
Chris@909 1400
Chris@909 1401 # create the IO object we will read from
Chris@909 1402 @io = if data.is_a? String then StringIO.new(data) else data end
Chris@909 1403
Chris@909 1404 init_separators(options)
Chris@909 1405 init_parsers(options)
Chris@909 1406 init_converters(options)
Chris@909 1407 init_headers(options)
Chris@909 1408
Chris@909 1409 unless options.empty?
Chris@909 1410 raise ArgumentError, "Unknown options: #{options.keys.join(', ')}."
Chris@909 1411 end
Chris@909 1412
Chris@909 1413 # track our own lineno since IO gets confused about line-ends is CSV fields
Chris@909 1414 @lineno = 0
Chris@909 1415 end
Chris@909 1416
Chris@909 1417 #
Chris@909 1418 # The line number of the last row read from this file. Fields with nested
Chris@909 1419 # line-end characters will not affect this count.
Chris@909 1420 #
Chris@909 1421 attr_reader :lineno
Chris@909 1422
Chris@909 1423 ### IO and StringIO Delegation ###
Chris@909 1424
Chris@909 1425 extend Forwardable
Chris@909 1426 def_delegators :@io, :binmode, :close, :close_read, :close_write, :closed?,
Chris@909 1427 :eof, :eof?, :fcntl, :fileno, :flush, :fsync, :ioctl,
Chris@909 1428 :isatty, :pid, :pos, :reopen, :seek, :stat, :string,
Chris@909 1429 :sync, :sync=, :tell, :to_i, :to_io, :tty?
Chris@909 1430
Chris@909 1431 # Rewinds the underlying IO object and resets FasterCSV's lineno() counter.
Chris@909 1432 def rewind
Chris@909 1433 @headers = nil
Chris@909 1434 @lineno = 0
Chris@909 1435
Chris@909 1436 @io.rewind
Chris@909 1437 end
Chris@909 1438
Chris@909 1439 ### End Delegation ###
Chris@909 1440
Chris@909 1441 #
Chris@909 1442 # The primary write method for wrapped Strings and IOs, +row+ (an Array or
Chris@909 1443 # FasterCSV::Row) is converted to CSV and appended to the data source. When a
Chris@909 1444 # FasterCSV::Row is passed, only the row's fields() are appended to the
Chris@909 1445 # output.
Chris@909 1446 #
Chris@909 1447 # The data source must be open for writing.
Chris@909 1448 #
Chris@909 1449 def <<(row)
Chris@909 1450 # make sure headers have been assigned
Chris@909 1451 if header_row? and [Array, String].include? @use_headers.class
Chris@909 1452 parse_headers # won't read data for Array or String
Chris@909 1453 self << @headers if @write_headers
Chris@909 1454 end
Chris@909 1455
Chris@909 1456 # Handle FasterCSV::Row objects and Hashes
Chris@909 1457 row = case row
Chris@909 1458 when self.class::Row then row.fields
Chris@909 1459 when Hash then @headers.map { |header| row[header] }
Chris@909 1460 else row
Chris@909 1461 end
Chris@909 1462
Chris@909 1463 @headers = row if header_row?
Chris@909 1464 @lineno += 1
Chris@909 1465
Chris@909 1466 @io << row.map(&@quote).join(@col_sep) + @row_sep # quote and separate
Chris@909 1467
Chris@909 1468 self # for chaining
Chris@909 1469 end
Chris@909 1470 alias_method :add_row, :<<
Chris@909 1471 alias_method :puts, :<<
Chris@909 1472
Chris@909 1473 #
Chris@909 1474 # :call-seq:
Chris@909 1475 # convert( name )
Chris@909 1476 # convert { |field| ... }
Chris@909 1477 # convert { |field, field_info| ... }
Chris@909 1478 #
Chris@909 1479 # You can use this method to install a FasterCSV::Converters built-in, or
Chris@909 1480 # provide a block that handles a custom conversion.
Chris@909 1481 #
Chris@909 1482 # If you provide a block that takes one argument, it will be passed the field
Chris@909 1483 # and is expected to return the converted value or the field itself. If your
Chris@909 1484 # block takes two arguments, it will also be passed a FieldInfo Struct,
Chris@909 1485 # containing details about the field. Again, the block should return a
Chris@909 1486 # converted field or the field itself.
Chris@909 1487 #
Chris@909 1488 def convert(name = nil, &converter)
Chris@909 1489 add_converter(:converters, self.class::Converters, name, &converter)
Chris@909 1490 end
Chris@909 1491
Chris@909 1492 #
Chris@909 1493 # :call-seq:
Chris@909 1494 # header_convert( name )
Chris@909 1495 # header_convert { |field| ... }
Chris@909 1496 # header_convert { |field, field_info| ... }
Chris@909 1497 #
Chris@909 1498 # Identical to FasterCSV.convert(), but for header rows.
Chris@909 1499 #
Chris@909 1500 # Note that this method must be called before header rows are read to have any
Chris@909 1501 # effect.
Chris@909 1502 #
Chris@909 1503 def header_convert(name = nil, &converter)
Chris@909 1504 add_converter( :header_converters,
Chris@909 1505 self.class::HeaderConverters,
Chris@909 1506 name,
Chris@909 1507 &converter )
Chris@909 1508 end
Chris@909 1509
Chris@909 1510 include Enumerable
Chris@909 1511
Chris@909 1512 #
Chris@909 1513 # Yields each row of the data source in turn.
Chris@909 1514 #
Chris@909 1515 # Support for Enumerable.
Chris@909 1516 #
Chris@909 1517 # The data source must be open for reading.
Chris@909 1518 #
Chris@909 1519 def each
Chris@909 1520 while row = shift
Chris@909 1521 yield row
Chris@909 1522 end
Chris@909 1523 end
Chris@909 1524
Chris@909 1525 #
Chris@909 1526 # Slurps the remaining rows and returns an Array of Arrays.
Chris@909 1527 #
Chris@909 1528 # The data source must be open for reading.
Chris@909 1529 #
Chris@909 1530 def read
Chris@909 1531 rows = to_a
Chris@909 1532 if @use_headers
Chris@909 1533 Table.new(rows)
Chris@909 1534 else
Chris@909 1535 rows
Chris@909 1536 end
Chris@909 1537 end
Chris@909 1538 alias_method :readlines, :read
Chris@909 1539
Chris@909 1540 # Returns +true+ if the next row read will be a header row.
Chris@909 1541 def header_row?
Chris@909 1542 @use_headers and @headers.nil?
Chris@909 1543 end
Chris@909 1544
Chris@909 1545 #
Chris@909 1546 # The primary read method for wrapped Strings and IOs, a single row is pulled
Chris@909 1547 # from the data source, parsed and returned as an Array of fields (if header
Chris@909 1548 # rows are not used) or a FasterCSV::Row (when header rows are used).
Chris@909 1549 #
Chris@909 1550 # The data source must be open for reading.
Chris@909 1551 #
Chris@909 1552 def shift
Chris@909 1553 #########################################################################
Chris@909 1554 ### This method is purposefully kept a bit long as simple conditional ###
Chris@909 1555 ### checks are faster than numerous (expensive) method calls. ###
Chris@909 1556 #########################################################################
Chris@909 1557
Chris@909 1558 # handle headers not based on document content
Chris@909 1559 if header_row? and @return_headers and
Chris@909 1560 [Array, String].include? @use_headers.class
Chris@909 1561 if @unconverted_fields
Chris@909 1562 return add_unconverted_fields(parse_headers, Array.new)
Chris@909 1563 else
Chris@909 1564 return parse_headers
Chris@909 1565 end
Chris@909 1566 end
Chris@909 1567
Chris@909 1568 # begin with a blank line, so we can always add to it
Chris@909 1569 line = String.new
Chris@909 1570
Chris@909 1571 #
Chris@909 1572 # it can take multiple calls to <tt>@io.gets()</tt> to get a full line,
Chris@909 1573 # because of \r and/or \n characters embedded in quoted fields
Chris@909 1574 #
Chris@909 1575 loop do
Chris@909 1576 # add another read to the line
Chris@909 1577 begin
Chris@909 1578 line += @io.gets(@row_sep)
Chris@909 1579 rescue
Chris@909 1580 return nil
Chris@909 1581 end
Chris@909 1582 # copy the line so we can chop it up in parsing
Chris@909 1583 parse = line.dup
Chris@909 1584 parse.sub!(@parsers[:line_end], "")
Chris@909 1585
Chris@909 1586 #
Chris@909 1587 # I believe a blank line should be an <tt>Array.new</tt>, not
Chris@909 1588 # CSV's <tt>[nil]</tt>
Chris@909 1589 #
Chris@909 1590 if parse.empty?
Chris@909 1591 @lineno += 1
Chris@909 1592 if @skip_blanks
Chris@909 1593 line = ""
Chris@909 1594 next
Chris@909 1595 elsif @unconverted_fields
Chris@909 1596 return add_unconverted_fields(Array.new, Array.new)
Chris@909 1597 elsif @use_headers
Chris@909 1598 return FasterCSV::Row.new(Array.new, Array.new)
Chris@909 1599 else
Chris@909 1600 return Array.new
Chris@909 1601 end
Chris@909 1602 end
Chris@909 1603
Chris@909 1604 # parse the fields with a mix of String#split and regular expressions
Chris@909 1605 csv = Array.new
Chris@909 1606 current_field = String.new
Chris@909 1607 field_quotes = 0
Chris@909 1608 parse.split(@col_sep, -1).each do |match|
Chris@909 1609 if current_field.empty? && match.count(@quote_and_newlines).zero?
Chris@909 1610 csv << (match.empty? ? nil : match)
Chris@909 1611 elsif(current_field.empty? ? match[0] : current_field[0]) == @quote_char[0]
Chris@909 1612 current_field << match
Chris@909 1613 field_quotes += match.count(@quote_char)
Chris@909 1614 if field_quotes % 2 == 0
Chris@909 1615 in_quotes = current_field[@parsers[:quoted_field], 1]
Chris@909 1616 raise MalformedCSVError unless in_quotes
Chris@909 1617 current_field = in_quotes
Chris@909 1618 current_field.gsub!(@quote_char * 2, @quote_char) # unescape contents
Chris@909 1619 csv << current_field
Chris@909 1620 current_field = String.new
Chris@909 1621 field_quotes = 0
Chris@909 1622 else # we found a quoted field that spans multiple lines
Chris@909 1623 current_field << @col_sep
Chris@909 1624 end
Chris@909 1625 elsif match.count("\r\n").zero?
Chris@909 1626 raise MalformedCSVError, "Illegal quoting on line #{lineno + 1}."
Chris@909 1627 else
Chris@909 1628 raise MalformedCSVError, "Unquoted fields do not allow " +
Chris@909 1629 "\\r or \\n (line #{lineno + 1})."
Chris@909 1630 end
Chris@909 1631 end
Chris@909 1632
Chris@909 1633 # if parse is empty?(), we found all the fields on the line...
Chris@909 1634 if field_quotes % 2 == 0
Chris@909 1635 @lineno += 1
Chris@909 1636
Chris@909 1637 # save fields unconverted fields, if needed...
Chris@909 1638 unconverted = csv.dup if @unconverted_fields
Chris@909 1639
Chris@909 1640 # convert fields, if needed...
Chris@909 1641 csv = convert_fields(csv) unless @use_headers or @converters.empty?
Chris@909 1642 # parse out header rows and handle FasterCSV::Row conversions...
Chris@909 1643 csv = parse_headers(csv) if @use_headers
Chris@909 1644
Chris@909 1645 # inject unconverted fields and accessor, if requested...
Chris@909 1646 if @unconverted_fields and not csv.respond_to? :unconverted_fields
Chris@909 1647 add_unconverted_fields(csv, unconverted)
Chris@909 1648 end
Chris@909 1649
Chris@909 1650 # return the results
Chris@909 1651 break csv
Chris@909 1652 end
Chris@909 1653 # if we're not empty?() but at eof?(), a quoted field wasn't closed...
Chris@909 1654 if @io.eof?
Chris@909 1655 raise MalformedCSVError, "Unclosed quoted field on line #{lineno + 1}."
Chris@909 1656 elsif @field_size_limit and current_field.size >= @field_size_limit
Chris@909 1657 raise MalformedCSVError, "Field size exceeded on line #{lineno + 1}."
Chris@909 1658 end
Chris@909 1659 # otherwise, we need to loop and pull some more data to complete the row
Chris@909 1660 end
Chris@909 1661 end
Chris@909 1662 alias_method :gets, :shift
Chris@909 1663 alias_method :readline, :shift
Chris@909 1664
Chris@909 1665 # Returns a simplified description of the key FasterCSV attributes.
Chris@909 1666 def inspect
Chris@909 1667 str = "<##{self.class} io_type:"
Chris@909 1668 # show type of wrapped IO
Chris@909 1669 if @io == $stdout then str << "$stdout"
Chris@909 1670 elsif @io == $stdin then str << "$stdin"
Chris@909 1671 elsif @io == $stderr then str << "$stderr"
Chris@909 1672 else str << @io.class.to_s
Chris@909 1673 end
Chris@909 1674 # show IO.path(), if available
Chris@909 1675 if @io.respond_to?(:path) and (p = @io.path)
Chris@909 1676 str << " io_path:#{p.inspect}"
Chris@909 1677 end
Chris@909 1678 # show other attributes
Chris@909 1679 %w[ lineno col_sep row_sep
Chris@909 1680 quote_char skip_blanks encoding ].each do |attr_name|
Chris@909 1681 if a = instance_variable_get("@#{attr_name}")
Chris@909 1682 str << " #{attr_name}:#{a.inspect}"
Chris@909 1683 end
Chris@909 1684 end
Chris@909 1685 if @use_headers
Chris@909 1686 str << " headers:#{(@headers || true).inspect}"
Chris@909 1687 end
Chris@909 1688 str << ">"
Chris@909 1689 end
Chris@909 1690
Chris@909 1691 private
Chris@909 1692
Chris@909 1693 #
Chris@909 1694 # Stores the indicated separators for later use.
Chris@909 1695 #
Chris@909 1696 # If auto-discovery was requested for <tt>@row_sep</tt>, this method will read
Chris@909 1697 # ahead in the <tt>@io</tt> and try to find one. +ARGF+, +STDIN+, +STDOUT+,
Chris@909 1698 # +STDERR+ and any stream open for output only with a default
Chris@909 1699 # <tt>@row_sep</tt> of <tt>$INPUT_RECORD_SEPARATOR</tt> (<tt>$/</tt>).
Chris@909 1700 #
Chris@909 1701 # This method also establishes the quoting rules used for CSV output.
Chris@909 1702 #
Chris@909 1703 def init_separators(options)
Chris@909 1704 # store the selected separators
Chris@909 1705 @col_sep = options.delete(:col_sep)
Chris@909 1706 @row_sep = options.delete(:row_sep)
Chris@909 1707 @quote_char = options.delete(:quote_char)
Chris@909 1708 @quote_and_newlines = "#{@quote_char}\r\n"
Chris@909 1709
Chris@909 1710 if @quote_char.length != 1
Chris@909 1711 raise ArgumentError, ":quote_char has to be a single character String"
Chris@909 1712 end
Chris@909 1713
Chris@909 1714 # automatically discover row separator when requested
Chris@909 1715 if @row_sep == :auto
Chris@909 1716 if [ARGF, STDIN, STDOUT, STDERR].include?(@io) or
Chris@909 1717 (defined?(Zlib) and @io.class == Zlib::GzipWriter)
Chris@909 1718 @row_sep = $INPUT_RECORD_SEPARATOR
Chris@909 1719 else
Chris@909 1720 begin
Chris@909 1721 saved_pos = @io.pos # remember where we were
Chris@909 1722 while @row_sep == :auto
Chris@909 1723 #
Chris@909 1724 # if we run out of data, it's probably a single line
Chris@909 1725 # (use a sensible default)
Chris@909 1726 #
Chris@909 1727 if @io.eof?
Chris@909 1728 @row_sep = $INPUT_RECORD_SEPARATOR
Chris@909 1729 break
Chris@909 1730 end
Chris@909 1731
Chris@909 1732 # read ahead a bit
Chris@909 1733 sample = @io.read(1024)
Chris@909 1734 sample += @io.read(1) if sample[-1..-1] == "\r" and not @io.eof?
Chris@909 1735
Chris@909 1736 # try to find a standard separator
Chris@909 1737 if sample =~ /\r\n?|\n/
Chris@909 1738 @row_sep = $&
Chris@909 1739 break
Chris@909 1740 end
Chris@909 1741 end
Chris@909 1742 # tricky seek() clone to work around GzipReader's lack of seek()
Chris@909 1743 @io.rewind
Chris@909 1744 # reset back to the remembered position
Chris@909 1745 while saved_pos > 1024 # avoid loading a lot of data into memory
Chris@909 1746 @io.read(1024)
Chris@909 1747 saved_pos -= 1024
Chris@909 1748 end
Chris@909 1749 @io.read(saved_pos) if saved_pos.nonzero?
Chris@909 1750 rescue IOError # stream not opened for reading
Chris@909 1751 @row_sep = $INPUT_RECORD_SEPARATOR
Chris@909 1752 end
Chris@909 1753 end
Chris@909 1754 end
Chris@909 1755
Chris@909 1756 # establish quoting rules
Chris@909 1757 do_quote = lambda do |field|
Chris@909 1758 @quote_char +
Chris@909 1759 String(field).gsub(@quote_char, @quote_char * 2) +
Chris@909 1760 @quote_char
Chris@909 1761 end
Chris@909 1762 @quote = if options.delete(:force_quotes)
Chris@909 1763 do_quote
Chris@909 1764 else
Chris@909 1765 lambda do |field|
Chris@909 1766 if field.nil? # represent +nil+ fields as empty unquoted fields
Chris@909 1767 ""
Chris@909 1768 else
Chris@909 1769 field = String(field) # Stringify fields
Chris@909 1770 # represent empty fields as empty quoted fields
Chris@909 1771 if field.empty? or
Chris@909 1772 field.count("\r\n#{@col_sep}#{@quote_char}").nonzero?
Chris@909 1773 do_quote.call(field)
Chris@909 1774 else
Chris@909 1775 field # unquoted field
Chris@909 1776 end
Chris@909 1777 end
Chris@909 1778 end
Chris@909 1779 end
Chris@909 1780 end
Chris@909 1781
Chris@909 1782 # Pre-compiles parsers and stores them by name for access during reads.
Chris@909 1783 def init_parsers(options)
Chris@909 1784 # store the parser behaviors
Chris@909 1785 @skip_blanks = options.delete(:skip_blanks)
Chris@909 1786 @encoding = options.delete(:encoding) # nil will use $KCODE
Chris@909 1787 @field_size_limit = options.delete(:field_size_limit)
Chris@909 1788
Chris@909 1789 # prebuild Regexps for faster parsing
Chris@909 1790 esc_col_sep = Regexp.escape(@col_sep)
Chris@909 1791 esc_row_sep = Regexp.escape(@row_sep)
Chris@909 1792 esc_quote = Regexp.escape(@quote_char)
Chris@909 1793 @parsers = {
Chris@909 1794 :any_field => Regexp.new( "[^#{esc_col_sep}]+",
Chris@909 1795 Regexp::MULTILINE,
Chris@909 1796 @encoding ),
Chris@909 1797 :quoted_field => Regexp.new( "^#{esc_quote}(.*)#{esc_quote}$",
Chris@909 1798 Regexp::MULTILINE,
Chris@909 1799 @encoding ),
Chris@909 1800 # safer than chomp!()
Chris@909 1801 :line_end => Regexp.new("#{esc_row_sep}\\z", nil, @encoding)
Chris@909 1802 }
Chris@909 1803 end
Chris@909 1804
Chris@909 1805 #
Chris@909 1806 # Loads any converters requested during construction.
Chris@909 1807 #
Chris@909 1808 # If +field_name+ is set <tt>:converters</tt> (the default) field converters
Chris@909 1809 # are set. When +field_name+ is <tt>:header_converters</tt> header converters
Chris@909 1810 # are added instead.
Chris@909 1811 #
Chris@909 1812 # The <tt>:unconverted_fields</tt> option is also actived for
Chris@909 1813 # <tt>:converters</tt> calls, if requested.
Chris@909 1814 #
Chris@909 1815 def init_converters(options, field_name = :converters)
Chris@909 1816 if field_name == :converters
Chris@909 1817 @unconverted_fields = options.delete(:unconverted_fields)
Chris@909 1818 end
Chris@909 1819
Chris@909 1820 instance_variable_set("@#{field_name}", Array.new)
Chris@909 1821
Chris@909 1822 # find the correct method to add the coverters
Chris@909 1823 convert = method(field_name.to_s.sub(/ers\Z/, ""))
Chris@909 1824
Chris@909 1825 # load converters
Chris@909 1826 unless options[field_name].nil?
Chris@909 1827 # allow a single converter not wrapped in an Array
Chris@909 1828 unless options[field_name].is_a? Array
Chris@909 1829 options[field_name] = [options[field_name]]
Chris@909 1830 end
Chris@909 1831 # load each converter...
Chris@909 1832 options[field_name].each do |converter|
Chris@909 1833 if converter.is_a? Proc # custom code block
Chris@909 1834 convert.call(&converter)
Chris@909 1835 else # by name
Chris@909 1836 convert.call(converter)
Chris@909 1837 end
Chris@909 1838 end
Chris@909 1839 end
Chris@909 1840
Chris@909 1841 options.delete(field_name)
Chris@909 1842 end
Chris@909 1843
Chris@909 1844 # Stores header row settings and loads header converters, if needed.
Chris@909 1845 def init_headers(options)
Chris@909 1846 @use_headers = options.delete(:headers)
Chris@909 1847 @return_headers = options.delete(:return_headers)
Chris@909 1848 @write_headers = options.delete(:write_headers)
Chris@909 1849
Chris@909 1850 # headers must be delayed until shift(), in case they need a row of content
Chris@909 1851 @headers = nil
Chris@909 1852
Chris@909 1853 init_converters(options, :header_converters)
Chris@909 1854 end
Chris@909 1855
Chris@909 1856 #
Chris@909 1857 # The actual work method for adding converters, used by both
Chris@909 1858 # FasterCSV.convert() and FasterCSV.header_convert().
Chris@909 1859 #
Chris@909 1860 # This method requires the +var_name+ of the instance variable to place the
Chris@909 1861 # converters in, the +const+ Hash to lookup named converters in, and the
Chris@909 1862 # normal parameters of the FasterCSV.convert() and FasterCSV.header_convert()
Chris@909 1863 # methods.
Chris@909 1864 #
Chris@909 1865 def add_converter(var_name, const, name = nil, &converter)
Chris@909 1866 if name.nil? # custom converter
Chris@909 1867 instance_variable_get("@#{var_name}") << converter
Chris@909 1868 else # named converter
Chris@909 1869 combo = const[name]
Chris@909 1870 case combo
Chris@909 1871 when Array # combo converter
Chris@909 1872 combo.each do |converter_name|
Chris@909 1873 add_converter(var_name, const, converter_name)
Chris@909 1874 end
Chris@909 1875 else # individual named converter
Chris@909 1876 instance_variable_get("@#{var_name}") << combo
Chris@909 1877 end
Chris@909 1878 end
Chris@909 1879 end
Chris@909 1880
Chris@909 1881 #
Chris@909 1882 # Processes +fields+ with <tt>@converters</tt>, or <tt>@header_converters</tt>
Chris@909 1883 # if +headers+ is passed as +true+, returning the converted field set. Any
Chris@909 1884 # converter that changes the field into something other than a String halts
Chris@909 1885 # the pipeline of conversion for that field. This is primarily an efficiency
Chris@909 1886 # shortcut.
Chris@909 1887 #
Chris@909 1888 def convert_fields(fields, headers = false)
Chris@909 1889 # see if we are converting headers or fields
Chris@909 1890 converters = headers ? @header_converters : @converters
Chris@909 1891
Chris@909 1892 fields.enum_for(:each_with_index).map do |field, index| # map_with_index
Chris@909 1893 converters.each do |converter|
Chris@909 1894 field = if converter.arity == 1 # straight field converter
Chris@909 1895 converter[field]
Chris@909 1896 else # FieldInfo converter
Chris@909 1897 header = @use_headers && !headers ? @headers[index] : nil
Chris@909 1898 converter[field, FieldInfo.new(index, lineno, header)]
Chris@909 1899 end
Chris@909 1900 break unless field.is_a? String # short-curcuit pipeline for speed
Chris@909 1901 end
Chris@909 1902 field # return final state of each field, converted or original
Chris@909 1903 end
Chris@909 1904 end
Chris@909 1905
Chris@909 1906 #
Chris@909 1907 # This methods is used to turn a finished +row+ into a FasterCSV::Row. Header
Chris@909 1908 # rows are also dealt with here, either by returning a FasterCSV::Row with
Chris@909 1909 # identical headers and fields (save that the fields do not go through the
Chris@909 1910 # converters) or by reading past them to return a field row. Headers are also
Chris@909 1911 # saved in <tt>@headers</tt> for use in future rows.
Chris@909 1912 #
Chris@909 1913 # When +nil+, +row+ is assumed to be a header row not based on an actual row
Chris@909 1914 # of the stream.
Chris@909 1915 #
Chris@909 1916 def parse_headers(row = nil)
Chris@909 1917 if @headers.nil? # header row
Chris@909 1918 @headers = case @use_headers # save headers
Chris@909 1919 # Array of headers
Chris@909 1920 when Array then @use_headers
Chris@909 1921 # CSV header String
Chris@909 1922 when String
Chris@909 1923 self.class.parse_line( @use_headers,
Chris@909 1924 :col_sep => @col_sep,
Chris@909 1925 :row_sep => @row_sep,
Chris@909 1926 :quote_char => @quote_char )
Chris@909 1927 # first row is headers
Chris@909 1928 else row
Chris@909 1929 end
Chris@909 1930
Chris@909 1931 # prepare converted and unconverted copies
Chris@909 1932 row = @headers if row.nil?
Chris@909 1933 @headers = convert_fields(@headers, true)
Chris@909 1934
Chris@909 1935 if @return_headers # return headers
Chris@909 1936 return FasterCSV::Row.new(@headers, row, true)
Chris@909 1937 elsif not [Array, String].include? @use_headers.class # skip to field row
Chris@909 1938 return shift
Chris@909 1939 end
Chris@909 1940 end
Chris@909 1941
Chris@909 1942 FasterCSV::Row.new(@headers, convert_fields(row)) # field row
Chris@909 1943 end
Chris@909 1944
Chris@909 1945 #
Chris@909 1946 # Thiw methods injects an instance variable <tt>unconverted_fields</tt> into
Chris@909 1947 # +row+ and an accessor method for it called unconverted_fields(). The
Chris@909 1948 # variable is set to the contents of +fields+.
Chris@909 1949 #
Chris@909 1950 def add_unconverted_fields(row, fields)
Chris@909 1951 class << row
Chris@909 1952 attr_reader :unconverted_fields
Chris@909 1953 end
Chris@909 1954 row.instance_eval { @unconverted_fields = fields }
Chris@909 1955 row
Chris@909 1956 end
Chris@909 1957 end
Chris@909 1958
Chris@909 1959 # Another name for FasterCSV.
Chris@909 1960 FCSV = FasterCSV
Chris@909 1961
Chris@909 1962 # Another name for FasterCSV::instance().
Chris@909 1963 def FasterCSV(*args, &block)
Chris@909 1964 FasterCSV.instance(*args, &block)
Chris@909 1965 end
Chris@909 1966
Chris@909 1967 # Another name for FCSV::instance().
Chris@909 1968 def FCSV(*args, &block)
Chris@909 1969 FCSV.instance(*args, &block)
Chris@909 1970 end
Chris@909 1971
Chris@909 1972 class Array
Chris@909 1973 # Equivalent to <tt>FasterCSV::generate_line(self, options)</tt>.
Chris@909 1974 def to_csv(options = Hash.new)
Chris@909 1975 FasterCSV.generate_line(self, options)
Chris@909 1976 end
Chris@909 1977 end
Chris@909 1978
Chris@909 1979 class String
Chris@909 1980 # Equivalent to <tt>FasterCSV::parse_line(self, options)</tt>.
Chris@909 1981 def parse_csv(options = Hash.new)
Chris@909 1982 FasterCSV.parse_line(self, options)
Chris@909 1983 end
Chris@909 1984 end