faster_csv.rb 73 KB

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