I was working with a Grape API and got into a situation where I was kind of reimplementing some methods on more than one mounted API. So naturally, I wanted to refactor the code, keep it DRY and extract it as helper methods and eventually into helper module.
So here is what my base API class looks like:
# /app/api/api.rb class API < Grape::API format :json version 'v1', using: :path mount V1::A mount V1::B end
and here goes my helper module, nothing fancy, just pretty basic stuff:
# /app/api/v1/helpers/authentication_helpers.rb module V1 module Helpers module AuthenticationHelpers extend Grape::API::Helpers def current_operator @current_operator ||= authenticate! end def authenticate! # Handle the authentication stuff end end end end
So now we have our AuthenticationHelpers available, we can just go ahead and include them in any or every API that is mounted.
Loading helpers for every mounted API
We can include and load our AuthenticationHelper across all the mounted APIs by just including them in our base class and then making all other classes inherit from the base class API.
# /app/api/api.rb class API < Grape::API include V1::Helpers format :json version 'v1', using: :path mount V1::A mount V1::B end class A < API # ... end class B < API # ... end
Loading helpers for a single mounted API
If we just want to include our AuthenticationHelper for one or two APIs only, we can go ahead and just include them on the individual classes.
# /app/api/v1/a.rb module V1 class A < Grape::API helpers V1::Helpers # ... end end # /app/api/v1/B.rb module V1 class B < Grape::API helpers V1::Helpers #... end end