I just ran into some behavior with the check_box helper that seems a
little counter-intuitive...

If I have something like -

----
    form_for @some_object
      check_box :some_attribute
    end
-----

and :some_attribute is nil, it turns out that the checkbox will be
rendered with the box checked - which is not what I would have
expected.

I went looking to figure out why, and it's connected with the method
update_bound_check_box that is called (indirectly) from check_box. It
looks like this -

-----
    def update_bound_check_box(method, attrs)
      raise ArgumentError, ":value can't be used with a
bound_check_box" if attrs.has_key?(:value)

      attrs[:boolean] = attrs.fetch(:boolean, true)

      val = control_value(method)
      attrs[:checked] = attrs.key?(:on) ? val == attrs[:on] :
considered_true?(val)
    end
-----

So in the absence of :on and :off options, whether the box is checked
or not depends on whether :some_attribute (which is what produces val)
is "considered true", as defined by -

-----
    def considered_true?(value)
      value && value != "false" && value != "0" && value != 0
    end
-----

On the face of it this looks ok, except that control_value(method) in
update_bound_check_box calls 'to_s' on the value it returns. What this
means is that a resource attribute whose value is nil will result in
val = "", i.e. an empty string. And an empty string fails the
considered_true test.

Now I can get around this easily enough by setting :on and :off
options in the call to check_box or by initializing :some_attribute to
false in my controller's 'new' action. But as well as complicating the
use of the helper for what doesn't seem like a terribly good reason,
it seems a little weird that a nil resource attribute should be
'considered true'.

One solution would be to modify considered_true? to -
      value && value != "false" && value != "0" && value != 0 &&
value != ""

Are there any reasons that this would not be a good idea?
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"merb" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to [email protected]
For more options, visit this group at http://groups.google.com/group/merb?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to