1

我正在使用 Rails 中的 heroku api,遇到了一个潜在的问题。

提交登录表单后,我正在实例化 heroku 对象。

heroku = Heroku::API.new(:username => USERNAME, :password => PASSWORD)

然后我想在所有控制器中使用 heroku 对象来进一步查询 api。我试过@heroku、@@heroku 和$heroku,但都没有。这可能吗?

我发现它的唯一解决方案是使用 api 获取用户 api 密钥,将其存储在会话中,然后使用它在每个控制器方法中重新实例化 heroku 对象。这是最好/唯一的解决方案吗?

4

1 回答 1

1

一般来说, abefore_filter可以解决您的重新实例化问题。如果您想设置一个可用于每个控制器方法的实例变量,请执行以下操作:

class UsersController < ApplicationController

  before_filter :get_user

  def profile
    # @user is accessible here
  end

  def account
    # @user is accessible here
  end

  private 

  def get_user
    @user = User.find(params[:id])
  end

end

您还可以在应用程序控制器中使用 before_filters来设置可在所有控制器中访问的实例变量。 在此处阅读有关过滤器的信息

至于将 API 密钥存储到会话中,这是可行的,但如果您想要长期访问,您可能希望将 API 密钥写入数据库。结合之前的过滤器,您可以执行以下操作:

class ApplicationController < ActionController::Base

  before_filter :setup_heroku

  def setup_heroku
    if current_user && current_user.heroku_api_key
      @heroku = Heroku::API.new(:api_key => current_user.heroku_api_key)
    end
  end

end
于 2012-11-04T09:26:17.350 回答