Forum: Ruby on Rails strange logic problem

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.
6a4bb8e775651d10ab23ab01e6982e8c?d=identicon&s=25 edlitmus (Guest)
on 2007-03-09 00:36
(Received via mailing list)
Hi all,

I have a template that is sometimes given a local like so:

render :partial => 'shared/new_addresses', :locals => {:addresses =>
addresses}

In the partial I do this to make sure everything is cool:

if defined? addresses && !addresses.nil? && addresses[:z_address]
    @address = addresses[:z_address]
end

Now, here's where things get weird. After the app has been running a
while in production I start getting exceptions being thrown due to
addresses being nil on the assignment line above. Even though I make
sure it isn't in the if statement!

If I do this:

if defined? addresses && !addresses.nil? && addresses[:z_address]
    if !addresses.nil?
  @address = addresses[:z_address]
    end
end

I don't get the errors.

Any one have a clue as to what is happening here?

Cheers,

--Ed
1f2eadfb41362800ebc2cf211b91d0f7?d=identicon&s=25 javier ramirez (Guest)
on 2007-03-09 01:07
(Received via mailing list)
> render :partial => 'shared/new_addresses', :locals => {:addresses =>
> addresses}
>
> In the partial I do this to make sure everything is cool:
>
> if defined? addresses && !addresses.nil? && addresses[:z_address]
>     @address = addresses[:z_address]
> end
>
>
defined? will not work as expected with variables passed as locals to a
partial. You should use instead
    local_assigns.has_key? addresses

You could also work aroud that by doing
    addresses ||= nil

That way if it was undefined initially, it will be nil after that, so
you can check it with addresses.nil? directly

regards,

javier ramirez

--
--------
Estamos de estreno... si necesitas llevar el control de tus gastos
visita http://www.gastosgem.com !!Es gratis!!
6a4bb8e775651d10ab23ab01e6982e8c?d=identicon&s=25 edlitmus (Guest)
on 2007-03-09 16:25
(Received via mailing list)
Thanks Javier! Using local_assigns.has_key? does the trick.

Cheers,

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