Rails Grape, DRY Helpers require common parameters

Purpose. Use shared pairs from a helper module without adding syntax helpers Helper::Modulefor each installed API.

Example code that works:

# /app/api/v1/helpers.rb
module V1
  module Helpers
    extend Grape::API::Helpers

    params :requires_authentication_params do
      requires :user_email,           type: String
      requires :authentication_token, type: String
    end
  end
end

# /app/api/api.rb
class API < Grape::API
  format :json
  version 'v1', using: :path

  mount V1::A
  mount V1::B
end

# /app/api/v1/a.rb
module V1
  class A < Grape::API
    helpers V1::Helpers

    desc 'SampleA'
    params do
      use :requires_authentication_params
    end
    get 'sample_a/url' do
      #...
    end
  end
end

# /app/api/v1/B.rb
module V1
  class B < Grape::API
    helpers V1::Helpers

    desc 'SampleB'
    params do
      use :requires_authentication_params
    end
    get 'sample_b/url' do
      #...
    end
  end
end

The problem arises when I try to move the call helpers V1::Helpersfrom Aand Bto the class APIthat mounts them, throwing an exception:

block (2 levels) in use': Params :requires_authentication_params not found! (RuntimeError)

Interestingly, the module really turns on, because if I add some instance method to the class V1::Helpers, I can use them inside Aand B.

So the question is: what would be the best solution for DRY this and follow best practices?

+4
1

, V1::Helpers API A B 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
0

All Articles