Frage

I have a database-less rails app which communicates with an API.

For authentication, I send the users credentials to the api and receive a session token if successful. Subsequently, every api request I make should contain that token.

api_request.rb:

class ApiRequest

  def initialize(relative_path,params={})
    params = _add_base_data params
    send_request relative_path, params
  end

  private
  def send_request(relative_path,params)
    conn = Faraday.new(:url => MyApp::Application.config.server) do |faraday|
      faraday.request  :url_encoded
      faraday.response :logger
      faraday.adapter  Faraday.default_adapter
    end

    encoded = conn.post relative_path,params
    @data = JSON.parse encoded.body
    @data
  end

  def _add_base_data params
    params[:session_token] = ?
    params
  end
end

my_session.rb:

class MySession
   def login? email,pass
      params = { :email => email, :password => pass }
      resp = ApiRequest.new '/user/login', params 
      if resp.failed?
        false
      else
        @session[:token] = resp.data['session_token']
        true
      end
    end
end

How can I make the session token available to the ApiRequest model for every call?

War es hilfreich?

Lösung

How about passing the session token as an argument to the ApiRequest instead? You could then wrap calls up in a simple method for use in your controllers:

# in base controller class
def api(resource, params)
  ApiRequest.new @session[:token], '/user/login', params 
end

This has the advantage that session parameters are kept at the controller level, eliminating the need to persist state information in your model (where it probably shouldn't be).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top