user1570144
user1570144

Reputation: 479

Accessing current_user variable in another controller

I am trying to access Devise's current_user variable inside a new instance of another controller. Here is my definition of GetsInterfaceController

class GetsInterfaceController < ApplicationController
  def select_current_signed_in_user
   @signed_in_user_here = current_user
  end
end

Then I instantiate a new instance of GetsInterfaceController in ClientsController

class ClientsController < ApplicationController
  def get_current_user
    @gets_interface_controller = GetsInterfaceController.new
    find_signed_in_user = @gets_interface_controller.select_current_signed_in_user
  end
end

But I get null error on the @signed_in_user_here = current_user line in GetsInterfaceController when I try this. Anyway to get to the current_user attribute from inside GetsInterfaceController ?

Upvotes: 1

Views: 1049

Answers (2)

max
max

Reputation: 101811

current_user is not a variable - it is a helper method. Thus it is already available in all your helpers and views.

Additionally you never instantiate controllers in Rails. The router does that for you.

The only public methods in your controllers should be the actions which respond to HTTP requests.

If you want to reuse a method in several controllers you should be using inheritance, modules (concerns) or helpers. Never by calling a method on another controller.


To call an external service you want to create an API client class:

# adapted from https://github.com/jnunemaker/httparty
require 'httparty'
class StackExchangeClient
  include HTTParty
  base_uri 'api.stackexchange.com'

  def initialize(service, page, user = nil)
    @user = user
    @options = { query: {site: service, page: page} }
  end

  def questions
    self.class.get("/2.2/questions", @options)
  end

  def users
    self.class.get("/2.2/users", @options)
  end
end

Or if you need to call an external service and for example create several models with the data a Service Object:

class SomeService
  def initialize(user, client: SomeClient)
    @user = user
    @client = client # for mocking
  end

  def call
     response = @client.get('/foo')
     response.each do |d|
        @user.baz << d[:woo]
     end
  end
end

SomeService.new(current_user).call

Upvotes: 1

user1570144
user1570144

Reputation: 479

I solved this by moving my code into a Module in lib directory. Works like a charm

Upvotes: 1

Related Questions