将ApplicationController继承到Grape-API

时间:2014-09-30 10:23:58

标签: ruby-on-rails-3 grape-api

我正在使用Rails 3应用程序。我在我的应用程序的ApplicationController(如前面的过滤器)类中有几个重要的实现(比如设置租户ID,身份验证等)。现在,当我尝试使用Grape实现API时,我无法在Grape中重用applicationController逻辑。

Grape API类是否可以继承ApplicationController?万一,如果我在这里遗漏了什么,请教育我。

感谢。

1 个答案:

答案 0 :(得分:0)

我认为你不能让Rails控制器从Grape::API继承。你可以做的是:创建一个继承自Grape::API的基础API类,并实现必要的方法来模仿你的ApplicationController

Grape :: API提供了一些回调挂钩,所以你可以在你的基础api类中设置它们,比如(未测试):

class MyAPI < Grape::API
  before do
    authenticate!
  end

  helpers do
    def current_user
      @current_user ||= User.authorize!(env)
    end

    def authenticate!
      error!('401 Unauthorized', 401) unless current_user
    end
  end
end

class ProductAPI < MyAPI
  # Your code here
end