Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would suggest using the <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-i-header_row-3F" rel="nofollow">CSV::header_row</a> function to perform the check, and raising an error if it's not what you expect. Something like:</p> <pre><code>def ReadLongFile(longFile) CSV.foreach(longFile, :headers =&gt; true, :return_headers =&gt; true, :col_sep =&gt; '|') do |row| if row.header_row? then raise ArgumentError, "Bad headers" unless header_sane?(row) end # Otherwise do the processing end end </code></pre> <p>Your implemenation of <code>header_sane?</code> will perform the validation that you need to ensure the file is what you expect it to be. Your calling code can rescue the ArgumentError if it can recover from it, or just let it fail :-)</p> <p>Note: Updated to reflect error noted in the comments below. Be sure to set the :return_headers option when calling <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-c-foreach" rel="nofollow">CSV::foreach</a>.</p> <p>If you are worried about the minimal overhead of calling header_row? for each of the row entries, you can construct a CSV instance and use <a href="http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html#method-i-shift" rel="nofollow">shift</a> to manually check the first row before continuing. For instance:</p> <pre><code>def ReadLongFile(longFile) File.open(longFile) do |file| reader = CSV.new(file, {:col_sep =&gt; '|', :headers =&gt; true, :return_headers =&gt; true}) header_row = reader.shift raise ArgumentError, "Bad file headers" unless header_sane?(header_row) reader.each do |row| p row end end end </code></pre> <p>Implemented as above, the following behavior holds true:</p> <pre><code>[4] pry(main)&gt; def header_sane? row [4] pry(main)* true [4] pry(main)* end =&gt; nil [5] pry(main)&gt; ReadLongFile("file.csv") #&lt;CSV::Row "date":"2010-01-01" "time":"07:00:00" "account":"A1"&gt; #&lt;CSV::Row "date":"2010-01-01" "time":"07:00:01" "account":"A2"&gt; =&gt; nil [6] pry(main)&gt; def header_sane? row [6] pry(main)* false [6] pry(main)* end =&gt; nil [7] pry(main)&gt; ReadLongFile("file.csv") ArgumentError: Bad file headers from (pry):7:in `block in ReadLongFile' </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload