简体   繁体   中英

Ruby class accessing application controller method

I have a rails app acting as an API client.

Once a user signs in, a token is saved to be sent with every following request to the API.

Here is my code (really simplified):

# /lib/api_client.rb
class ApiClient
  def get(path, options = {})
    # options.merge! headers: {'Authorization' => 'Token mytoken'}
    HTTParty.get("http://api.myapp.com/#{path}", options)
  end
end

# /app/models/user.rb
class User
  def self.exists?(id)
    api.get("users/#{id}").success?
  end

  def self.api
    @api ||= ApiClient.new
  end
end

# /app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def signed_in?
    current_auth_token.present?
  end

  def current_auth_token
    cookies.signed[:user_token]
  end
end

My problem is that ApiClient can t access the ApplicationController so it has no way to know if there is an auth_token` or not.

Now, what would be the best way to automatically add an Authorization header containing current_auth_token to every following call to ApiClient#get ?

Another solution I though of is to initialize the ApiClient in the controller, then I could just do something like api_client.auth_token = 'mytoken' . But then, is there a proper way to access it from a model?

You'd have to also set a current_api_client , so that each request gets its own instance of an api_client with the correct current_auth_token . Set the api_client in your application controller but assign it to a class variable so you can easily access it from the model:

class ApplicationController < ActionController::Base
  cattr_accessor :current_api_client
  # this will reset the api_client on every request using the current_auth_token
  before_filter do |c|
    ApplicationController.current_api_client = ApiClient.new token: current_auth_token # or however you set this in the client
  end

  #...
end

Now in your model you can access ApplicationController.current_api_client .

This is one of many ways to do it. It's quick and easy and fits your posted code without too many changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM