Inheritance doesn't work in grapes

I am using grape redtful-api. I cannot inherit common_params in Grape. I defined generic _params in class API1 and call it in API2 throws an 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

      

+3


source to share


1 answer


The problem has little to do with Grape, but rather how variable scoping works in Ruby. common_params

is only local, it will not sustain the end of the region. You can get it to work using an instance variable or similar , but don't let it go there. How you should share helpers in different grapes is 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 different grapes you need to "enable" the module and the use

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 grape helpers API2

, use the same technique.

+1


source







All Articles