Forum: Ruby on Rails conditional delete of a session

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.
171ea139761951336b844e708d1547ab?d=identicon&s=25 James Byrne (byrnejb)
on 2008-12-15 19:35
Rails 2.2.2
Ruby 1.8.6

ActiveRecord Session Store enabled

For testing purposes I wish to ensure that no session exists.  To
accomplish this I wrote:

  session.delete if session

But this fails if session == nil and I suspect that it does not work as
I anticipate if session exists.  In the console I see this behaviour:

$ script/console
Loading development environment (Rails 2.2.2)
>> app.session
NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.session
        from
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/test_process.rb:429:in
`session'
        from (irb):1

>> app.session.delete if app.session
NoMethodError: You have a nil object when you didn't expect it!
The error occurred while evaluating nil.session
        from
/usr/lib/ruby/gems/1.8/gems/actionpack-2.2.2/lib/action_controller/test_process.rb:429:in
`session'
        from (irb):2

>> app.get "/"
=> 200

>> app.session
=> #<CGI::Session:0xb723ba24
@dbman=#<CGI::Session::CookieStore:0xb723b8e4 @original=nil, ...

>> app.session.delete if app.session
=> []

>> app.session
=> #<CGI::Session:0xb723ba24
@dbman=#<CGI::Session::CookieStore:0xb723b8e4 @original=nil,

Now, I believed that nil == false and that the construct "object.method
if object" should work.  Evidently I am misinformed or there is
something exceptional about session that I do not know.

How is what I desire, to remove the session if one already exists,
accomplished?
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2008-12-18 02:39
(Received via mailing list)
James Byrne wrote:
> But this fails if session == nil and I suspect that it does not work as
>         from (irb):1
> => 200
> @dbman=#<CGI::Session::CookieStore:0xb723b8e4 @original=nil,
>
> Now, I believed that nil == false and that the construct "object.method
> if object" should work.  Evidently I am misinformed or there is
> something exceptional about session that I do not know.
>
> How is what I desire, to remove the session if one already exists,
> accomplished?

Perhaps

    session.delete if defined?(session) && session

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.