Fixing CSV parsing bug (NoMethodError arity for NilClass)
We were working with some pure-Ruby CSV parsing code today and got a confusing error.
NoMethodError:
undefined method `arity' for nil:NilClass
We weren’t doing anything that looked special, just something like this:
CSV.parse(string, :converters => [:strip])
We narrowed it down to the point that we knew that just CSV.parse(string)
worked, so we knew it must have to do with the :converters
option. Not knowing the API backwards and forwards, I had thought that :strip
was built into Ruby’s CSV
library. It turns out that this error was happening because we hadn’t required our custom converter definition, which was in another file. It was something like this:
CSV::Converters[:strip] = lambda { |s| s.strip rescue s }
After making that definition available, our NoMethodError
went away.
This happened at least in part because we were writing fast specs, which needs all the necessary files to be required. However, we did end up refactoring our implementation as a result, since it was not obvious that the custom CSV converters even existed when the code was used within Rails.
Versions: Ruby 2.0.0, and the included CSV
library (based on FasterCSV
).