Forum: Ruby on Rails Shortcircuit evaluations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
William L. (Guest)
on 2006-02-24 08:35
This is probably a Ruby questions but since my issue exists in a Rails
validation I thought I'd post here. I have the following validator

validates_each  :thumbnail, :regular  do |record, attribute, value|
                                          unless value.nil? &&
value.valid?
                                            record.errors.add(
attribute, value.errors.full_messages[0])
                                          end
                                        end

I'm getting a 'nil object when you didn't expect it error' because the
condition is evaluating value.valid?. I was under the impression that if
the first condition (value.nil?) returned True then the second condition
would not be evaluated.

Does anyone know what I'm missing here?

If I rewrite it as:
validates_each  :thumbnail, :regular  do |record, attribute, value|
                                          unless value.nil?
                                            record.errors.add(
attribute, value.errors.full_messages[0])  unless value.valid?
                                          end
                                        end

it works fine.

Thanks for any education,
    William
Matt Burrows (Guest)
on 2006-02-24 11:07
William LeFevre wrote:
> This is probably a Ruby questions but since my issue exists in a Rails
> validation I thought I'd post here. I have the following validator
>
> validates_each  :thumbnail, :regular  do |record, attribute, value|
>                                           unless value.nil? &&
> value.valid?
>                                             record.errors.add(
> attribute, value.errors.full_messages[0])
>                                           end
>                                         end
>
> I'm getting a 'nil object when you didn't expect it error' because the
> condition is evaluating value.valid?. I was under the impression that if
> the first condition (value.nil?) returned True then the second condition
> would not be evaluated.

Logic error I believe. That is an AND condition, therefore if the LHS is
true it has to evaluate the RHS. If the LHS was false then it would
short circuit the evaluation of the RHS. You probably want a ! in there
somewhere.
Derrick S. (Guest)
on 2006-02-24 15:27
(Received via mailing list)
Logic error.  Use OR instead of AND.

-Derrick S.
This topic is locked and can not be replied to.