Rails Grape, DRY Helpers call for shared params
Asked Answered
M

1

6

Objective: Use grape Shared Params from a helper module, without having to add the syntax helpers Helper::Module on every mounted 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 arise when I try to move the helpers V1::Helpers call from A and B to the API class that mounts them, throwing the exception:

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

As an interesting note, the module does get included, because if I add any instance method to the class V1::Helpers I can use them inside A and B.

So the question, What would be the best solution to DRY this and follow best practices?

Mecham answered 10/11, 2014 at 22:57 Comment(0)
P
0

What if you include V1::Helpers on API and then make A and B inherit from API? E.g:

# /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
Procure answered 11/11, 2014 at 2:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.