Andreas S. wrote:
oh great, thanks lutz!
I am pretty new to RoR - and sometimes I think I still code ASP but
using RoR syntax - when I look at the oder code examples - I feel far
away from âaaaah, I get it!â. Most of the time I canât find things in
the Api references - it is a bit complicated to find things here. I also
ask myself why to use classes? My code looks like asp classic I hope
this will change over the next weeks and month.
your idea about the session is good - I read about sessions and that
they can store complete objects.
thanks again
-Andreas
Firstly, if a filter explicitly returns a âfalseâ value than rails
thinks you want to abort the processing of the action and halts
execution. When there is no cookie the last statement executed in the
filter method is:
$login_ok = false
and assigments always return the new value. So the filter itself
returns false.
Second, global variables will get you in trouble. If more than one
person at a time is using your app, the globals variable could have to
wrong values since they are global for all users in you app. This is
further complicated that most production rails sites runs multiple
server processes, each with it own global environment, and which process
serves the request is mostly random.
And for the most part, for ruby in general, embrace scope and simply
donât use globals. Unless you have a very good reason.
Third, as mentioned, this is what sessions are for. You can store
entire record objects in the session but its not recomended since they
may become stale since they are not tied to the database without being
explicitly refreshed. Itâs better to simply fetch a fresh objet on each
requet with a before_filter.
Here is how I would handle it:
before_filter :get_user
def get_user
session[:user_id] ||= cookies[:user_id]
session[:user_sid] ||= cookies[:user_sid]
@user = User.find_by_id(session[:user_id])
end
The cookies are fetched only if session[:user_id] is nil, meaning if you
assign a user_id another way, the potentially missing cookie values wont
overwrite them.
Then we create an instance variable for the user. Using find_by_id
instead of just âfindâ prevents a record not found error, and simply
returns nil instead if the record doesnât exist.
Then if someone is logged in, @user is a User object for that person.
And if no one is logged in, @user is nil. And @user is accessible in
all controllers and views. This lets you do simple things like:
def index
if @user
redirect_to :action => âshowâ, :id => @user
else
redirect_to :action => âsignupâ
end
end
or
<% if @user %>
<%= link_to âLogoutâ, :action = âlogoutâ %>
<% else %>
<%= link_to âLoginâ, :action => âloginâ %>
<% end %>