I am working in a Rails 3 application. I have few important implementations (like setting tenant id, authentication, etc) in the ApplicationController (as before filter) class of my application. Now when I try to implement API using the Grape, I am unable to re-use the applicationController logic in Grape.
Is it possible for Grape API classes to inherit ApplicationController? In case, if I am missing something here, please do educate me.
thanks.
I don't think you can let a Rails controller inherit from Grape::API
. What you could do is: create your own base API class that inherits from Grape::API
and implement the necessary methods to mimic your ApplicationController
.
Grape::API provides some callback-hooks, so you could set those in your base api class, like (not tested):
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