5

I am using grape redtful-api. I am Unable to inherit common_params in Grape. I defined common _params in class API1 and called it in API2 throws the error. How can I change the code to make this work?

module Example
  class API1 < Grape::API
    version 'v1'
    format :json
    prefix :api

    resource :exc1 do
      common_params = proc do
        requires :param1
        requires :param2
      end

      params(&common_params)
      get :params_by_pair do
        p1 = params[:param1]
        p2 = params[:param2]
        response = "https://www.example1.com/#{p1}_#{p2}"
      end
    end
  end
end

module Example
  class API2 < API1
    version 'v1', using: :header, vendor: 'twitter'
    format :json
    prefix :api

    resource :exc2 do

      params(&common_params)
      get :params_by_pair do
        p1 = params[:param1]
        p2 = params[:param2]
        response = "https://www.example2.com/#{p1}_#{p2}"
      end
    end
  end
end
Sam
  • 5,040
  • 12
  • 43
  • 95

1 Answers1

2

The issue doesn't have much to do with Grape but rather the way variables' scope works in Ruby. common_params is just a local, it won't survive the end of the scope. You could make it work by using a class instance variable or similar but let's not go there. The way you're supposed to share helpers across different grapes is through a dedicated module.

module Example
  module SharedHelpers
    extend Grape::API::Helpers

    params :common_params do
      requires :param1
      requires :param2
    end
  end
end

And now in the different grapes you need to "include" the module and use the helper.

module Example
  class API1 < Grape::API
    helpers SharedHelpers # !!!

    version 'v1'
    format :json
    prefix :api

    resource :exc1 do
      params do
        use :common_params # !!!
      end

      get :params_by_pair do
        ...
      end
    end
  end
end

To use the helpers in the API2 grape, use the same technique.

Jiří Pospíšil
  • 14,296
  • 2
  • 41
  • 52