Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

How can I use cookies in a helper file #176

Closed
gaoguoxin opened this Issue May 23, 2012 · 2 comments

Comments

Projects
None yet
2 participants

recently I use grape for an api server and I servered a login method:

get 'login' do
user = User.authenticate(params[:mobile], params[:password])
if user.present?
cookies[:auth_token] = user.auth_token
end
Rails.logger.info("*************************")
Rails.logger.info(cookies[:auth_token])
Rails.logger.info("**
***********************")
end

when each time I login I log the cookies and everytime I can get the auth_token with cookies

but when I use it in helpers.rb ,it seems that somethin went wrong:
in helpers.rb:

def current_user
if cookies[:auth_token].present?
current_user = User.find_by_auth_token(cookies[:auth_token])
else
current_user = nil
end
end

and in api.rb I required the helpers.rb and I nonce all method in helpers.rb :
require "api/helpers"
helpers APIHelpers

but when I use current_user in a get request,something went wrong:

get 'favourite' do
@Stores = current_user.stores.order("id desc").page(params[:page]).per(page_size)
end

undefined method `stores' for nil:NilClass.

So,as you know,the current_user is nil .Of course I log the cookies in helpers.rb:

def current_user
Rails.logger.info("*************************")
Rails.logger.info(cookies[:auth_token])
Rails.logger.info("**
***********************")
if cookies[:auth_token].present?
current_user = User.find_by_auth_token(cookies[:auth_token])
else
current_user = nil
end
end
and I get nothing in the log of the cookies. So my question is if the cookies can be used in helper method? or somewhere I went wrong? thanks.

Owner

dblock commented May 28, 2012

I wrote a test for this and couldn't repro the issue.

    it 'should retrieve cookies from a helper' do
      subject.helpers do
        def cookie_value
          cookies[:cookie]
        end
      end

      subject.get('/eat') do
        cookie_value
      end

      get('/eat', {}, 'HTTP_COOKIE' => 'cookie=chocolate')
      last_response.body.should == 'chocolate'
    end

If you could make a nice packaged repro, would be glad to take a look. Cookies are nothing else than a @cookies class variable that contains the cookies, examine what you get in self inside the helper.

Owner

dblock commented Jan 5, 2013

Closing.

@dblock dblock closed this Jan 5, 2013

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment