fl00r
fl00r

Reputation: 83680

Working with cookies out of controller

I want to make simple authentication like

# SessionController
require 'session.rb'
def create
  Session.new(params[:email], params[:password])
end

# lib/session.rb
class Session
  def initialize(email, password)
    client = Client.find_by_email_and_password(email, password)
    cookies[:user_id] = client.id if client
  end
end

only problem here is that I can't use cookies or sessions out of controller. I can replace cookies setting into controller, but it isn't what I want :)

Question is how to use cookies out of controller and what are best practices.

Upvotes: 1

Views: 1431

Answers (1)

Brian Donovan
Brian Donovan

Reputation: 8390

Firstly, don't explicitly add '.rb' to a require statement. You'd just use require 'session' normally. Second, Rails will load it for you when you reference Session, so you don't need to require it explicitly. Also, client ? cookies[:user_id] = client.id is invalid Ruby code. You probably want cookies[:user_id] = client.id if client.

An obvious solution would be to simply pass the cookies object to the Session you're creating, but my recommendation would be to simply put the code in the controller. Why do you have a Session object in the first place? I'd recommend not overcomplicating things by creating an unnecessary class.

Update:

To illustrate my last comment, here's some sample code:

class Session
  attr_reader :controller

  def initialize(controller)
    @controller = controller
  end

  def client
    if controller.cookies[:user_id]
      return Client.find_by_id(controller.cookies[:user_id])
    elsif (email = controller.params[:email]) && (password = controller.params[:password])
      client = Client.find_by_email_and_password(email, password)
      controller.cookies[:user_id] = client.id if client
      return client
    end
  end
end

Upvotes: 1

Related Questions