error when passing nil hash key to create
Reported by Ana Nelson | July 16th, 2008 @ 08:18 AM
I am creating a new object using:
Model.create!(hash)
I am creating the hash from FasterCSV, and the data file in question has some blank delimiters, so I get a hash like this:
{:attrib => "value", :another_attrib => "another_value", nil => nil}
Now, having a nil key causes DM to choke but with a rather cryptic error message (see stack trace below - my line numbers might be off slightly). Not sure whether you consider this a bug or not, but it might be nice to check for it.
A quick fix is adding unless k.nil? to L484:
setter = "#{k.to_s.sub(/\?\z/, '')}=" unless k.nil?
which leads to a "nil is not a symbol" error message, which is at least a clue as to the problem.
Or, if you want to just safely ignore nils then add a line before this line with:
next if k.nil?
I guess it should be if k.nil? || k.empty? since passing "" would lead to the same problem.
Or you could raise a more specific error:
raise NameError, "nil attribute key for value #{v.nil? ? "nil" : v.to_s}." if k.nil? || k.empty?
I think the 3rd option is safest, and it preserves the current convention of raising a NameError if something is in the hash which isn't a valid settable attribute.
hmm.. reading the stack trace again it does actually say "= is not a public property" but I didn't even notice the "=" at first since it's so close to the 'attributes='
/opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/resource.rb:490:in `attributes=': = is not a public property (NameError)
from /opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/resource.rb:483:in `each_pair'
from /opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/resource.rb:483:in `attributes='
from /opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/resource.rb:561:in `initialize'
from /opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/model.rb:257:in `new'
from /opt/local/lib/ruby/gems/1.8/gems/dm-core-0.9.3/lib/dm-core/model.rb:257:in `create'
from script/import.rb:10
from /opt/local/lib/ruby/gems/1.8/gems/fastercsv-1.2.3/lib/faster_csv.rb:659:in `each'
from /opt/local/lib/ruby/gems/1.8/gems/fastercsv-1.2.3/lib/faster_csv.rb:659:in `each'
from script/import.rb:7
Comments and changes to this ticket
Please Login or create a free account to add a new comment.
You can update this ticket by sending an email to from your email client. (help)
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
