grape-swagger
grape-swagger copied to clipboard
Easy way to document only declared params
I'm using Grape Entity Swagger to document all my parameters inside the Entities instead of the endpoints like this:
# my endpoint does not document any parameter...
params = params do
requires :name, type: String
end
desc: 'Creates a product',
success: { code: 201, model: Product },
params: Product.params_doc(params)
post '/products' do
# ...
end
And to achieve this I'm using a custom method params_doc that returns only the declared params' documentation.
class CustomEntity < Grape::Entity
def self.params_doc(params)
declared_params = params.instance_variable_get('@declared_params').flatten
declared_params.reduce({}) do |memo, param|
key = param.is_a?(Hash) ? param.keys.first : param
memo[key] = documentation[key]
memo
end
end
end
class Product < CustomEntity
expose :id, documentation: { type: 'string', desc: 'The ID of the Product' }
expose :name, documentation: { type: 'string', desc: 'foo bar' }
end
This works as expected and only documents the :name parameter for the endpoint. However this feels hacky and have caused some trouble if params block is not specified before the desc call. So I'm wondering if there's an easier way to achieve this.
Any help is appreciated.