Read cookies in application_helper.rb?

Hi there,

I am trying to write a simple function that checks if a user is logged
in based on a cookie value.

def isLoggedIn()

    if cookies[:userid] != ""
      isLoggedIn = true
    else
      isLoggedIn = false
    end

end

however, when I call this function from my application-wide view, I get
the following error:

undefined local variable or method `cookies' for
#<#<Class:0xb6e0e920>:0xb6e0e86c>

Can anyone help me understand how I can access my cookies from anywhere
other than an action in a controller?

Thanks,

Bryan

But how long is a session active for in Rails? Is ASP it's good for 20
minutes.

I don't want the user to have to log in every time they come to the
site. So I wouldn't think a session variable is the way to go.

Let's table the discussion of cookie vs session. Where am I allowed to
read cookies and why?

Bry

comicgeekspeak@gmail.com wrote:

I am trying to write a simple function that checks if a user is logged
in based on a cookie value.

def isLoggedIn()

    if cookies[:userid] != ""
      isLoggedIn = true
    else
      isLoggedIn = false
    end

end

however, when I call this function from my application-wide view, I get
the following error:

undefined local variable or method `cookies' for
#<#<Class:0xb6e0e920>:0xb6e0e86c>

Can anyone help me understand how I can access my cookies from anywhere
other than an action in a controller?

Add to your ApplicationController class (in application.rb)

      helper_method :cookies

Awesome! This worked like a charm. Thank you.

Now, I have another problem. My function is always returning true.
Even if I change it and force it return something else. For example:

def isLoggedIn()

    isLoggedIn = "bob"

end

so when I do this:

<%= isLoggedIn %>

I am seeing: true

How do I get my function to actually return "bob"

Bry

Why not just do something like this

def isLoggedIn()

    cookies[:userid] ? true : false

end

I don't understand that syntax at all? Question mark? colon?

Also, when I try to call a function in my view <% if isLoggedIn() ==
true %> I receive an "undefined method" error.

Bry

To make it easier for your to read try this

def isLoggedIn()

    return true unless cookies[:userid].nil?
    return false

end

that should return true only if the cookie[:userid] value is set.

then in your view just do <% if isLoggedIn() %>

you dont need <% if isLoggedIn() == true %> since isLoggedIn() is by
nature either true or false.

btw

the tertiary operator ( ? : ) is just a more succinct way of doing an
if .. then .. else statement

It's called a ternary operator. The expression before the ? is
evaluated, and if true whatever is between the ? and : is returned.
If the expression before ? is false, then whatever is after the : is
returned.

Chris

my mistake, you are right. its the "ternary" not the "tertiary"
operator. don't know what i was thinking of. haha