Array of session variables possible?

Hello all,

Is it possible to create an array of session[:values]? Or a hash of
session[:values]?

I have a web application where I manage session variables for saving
various control states (within the session; not persisting across
sessions), such as whether a checkbox was set, or text typed into a
textbox. Doing this helps the application to “remember” what the user
has done within the session so the user doesn’t have to retype this
information each time they revisit the same page.

I now want to create an admin user who can become an existing user by
selecting from a droplist within the admin session. For example, I
want the admin to become John, and set a checkbox within the John
session. Then become Jane and set some other control within the Jane
session. And, then return back to John’s session with all control
states set back to the John session.

In effect, I want to maintain an array or hash of session variables:
one set of session variables for each of a list of users. And, of
course, this list of users is dynamic (users getting added and removed
all the time).

While I know I can do this by persisting this information (write/read
to/from a database), I’d prefer not to do this (though for performance
reasons, I may find persisting to be faster as the number of users
increases).

So, my question is: is it possible to create an array of
session[:values]? Or a hash of session[:values]? If so, what is the
syntax for such a creation?

Thanks much.

You can treat the session just like any other variable in Ruby.

One thing you may want to consider is creating your own Ruby class Foo
that stores all of this information. Then you can store it in the
session like this:

a = Foo.new
a.name = ‘Wyatt G.’
a.other_data = ‘fork’
session[:foo] = a

You can have different Foo objects for the admin, for John, etc. They
can easily be changed:

session[:foo] = admin_foo
session[:foo] = john_foo

This isn’t the only way of doing this, but it might work well.

Cheers!
Wyatt G.

Oh, and by the way, it’s true that you can treat the session like any
other variable in Ruby. It behaves like a hash, but keep in mind that
it’s not strictly a Ruby hash. Rails extends its behavior a bit.