Rails bitten by Ruby’s nil.to_f

I guess I’m still new enough to Ruby that this does not make sense to me:

>> nil.to_f
=> 0.0

Magically, from nothing, you have something. I suppose it might be convenient in places, but today I ran into a minor bug in Rails that causes problems when trying to get the average of a column that doesn’t have any entries.

So what is the reasoning behind nil.to_f being 0.0 (and nil.to_i being 0, to_s being “”), anyway?

Permission denied to get property Object.constructor

I struggled a little bit to figure out what was going on with the Prototype javascript library in terms of this error I was getting in my application, rather cryptically reported as:

[Exception... "'Permission denied to get property 
Object.constructor' when calling method:
[nsIDOMEventListener::handleEvent]" nsresult: "0x8057001e
(NS_ERROR_XPC_JS_THREW_STRING)" location: "<unknown>" data: no]

I was setting up an observer to make some async requests when a checkbox is set or unset. Setting the checkbox to true worked just fine, but unsetting it seems to cause the above exception. It turns out the fix is pretty simple. Instead of this:

<%= observe_field('blah_yes', :url =>
                  {:action => 'set_blah', :id => @someobj.id},
                  :update => 'blahmessages') %>

I made sure to use a :with parameter:

<%= observe_field('blah_yes', :url =>
                  {:action => 'set_blah', :id => @someobj.id},
                  :update => 'blahmessages', :with => 'yes') %>

My guess as to what’s occuring comes from the parameters passed into my controller. Before the modification:

{"action"=>"set_blah", "id"=>"4", "1"=>"", "controller"=>"xyz"}

That “1” is being passed as the variable name, rather than its value… After adding the with, the parameters come in like so when it’s being set:

{"action"=>"set_blah", "id"=>"4", "controller"=>"xyz", "yeah"=>"1"}

And like so when it isn’t… aha!

 {"action"=>"set_blah", "id"=>"4", "controller"=>"xyz", "yeah"=>"null"}

I bet that null is what was causing problems.

I thought I’d publish it so that an answer is available for those searching with google, as I wasn’t able to find one.

Perhaps the Prototype library should be a little bit more careful with its data somewhere in order to fail more gracefully, but I’m not sure where one would go about looking.