Domanda

So I am building an application that I am trying to never need a database as the application will just be a portal to an API. I have a sessions controller and I am trying to use a cookie based session but the setter method is never being hit. Here is what I have at this point.

sessions_controller.rb

class SessionsController < ApplicationController

  def new
    if current_user
      redirect_to snapshots_path
    end
  end

  def create
    api = API.new
    response = api.authenticate_user(params[:session][:username].downcase, params[:session][:password])
    if response["Message"] == "success"
      current_user = response["User"]
      binding.pry
      redirect_to snapshots_path, notice: "Signed in successfully."
    else
      flash.now[:error] = "Invalid username/password combination."
      render :new
    end
  end

  def destroy
    current_user = nil
    redirect_to sign_in_path
  end

end

sessions_helper.rb

module SessionsHelper

  def current_user=(user)
    binding.pry
    if user
      @current_user = user
      cookies[:userdata] = { :value => user, :expires => 8.hours.from_now.utc }
    else
      @current_user = nil
      cookies.delete(:userdata)
    end
  end

  def current_user
    binding.pry
    @current_user ||= (cookies[:userdata] ? cookies[:userdata] : nil)
  end

end

The getter method is hit correctly every time but the setter is never getting hit. Any ideas as how to fix this thanks.

È stato utile?

Soluzione

When you are assigning to current_user it's treating it as a local variable. To solve that simply assign to self.current_user instead. The getter doesn't need that because there is no local variable named that so ruby looks for a method and uses that. If you reference the getter as self.current_user that would also work.

For example change:

current_user = response["User"]

to:

self.current_user = response["User"]

Altri suggerimenti

Include SessionsHelper in your SessionsController in order to access SessionHelper methods within SessionsController.

Code will work fine without any modification i.e., you would be able to access current_user and current_user= directly.

class SessionsController < ApplicationController
 include SessionsHelper  ## Just add this
 ..
end
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top