I assume that you want to analyze the CSV and do something with the analysis results. The worst case is that your CSV is valid and that you are parsing the file again. I would write something like this to cancel the result, so you only need to parse the CSV:
module FasterCSV
def self.parse_and_validate(file, options = {})
begin
@parsed_result = FasterCSV.parse(file, options) { |row| }
rescue FasterCSV::MalformedCSV
@invalid = true
end
end
def self.is_valid?
!@invalid
end
def self.parsed_result
@parsed_result if self.valid?
end
end
And then:
class CsvImporter
include ActiveRecord::Validations
validates_presence_of :file
validate check_file_format
def do_your_parse_stuff
here you would use FasterCSV::parsed_result
end
...
private
def check_file_format
FasterCSV::parse_and_validate(file)
errors.add :file, "Malformed CSV! Please check syntax" unless FasterCSV::is_valid?
end
end
In the above case, you can move the material to another class, which takes care of exchanging information with FasterCSV and eliminates the analysis result, because I do not think my example is thread safe :)
xinit source
share