grape
grape copied to clipboard
Helpers are not accessible from inside `params` block
Helpers can be accessed from before
and request blocks (e.g. get
, post
). But, params
block can not access helpers the same way.
In the following snippet, params
block throws a NoMethodError
for process_query
.
route_param :cat_id do
before do
@cat = Cat.find process_id(params[:cat_id])
end
desc "An endpoint"
params do
optional :query, type: String, coerce_with: ->(query){process_query query}
end
get :kittens do
process_id(params[:cat_id])
end
end
Is there a way to access helpers from inside the params
block?
Probably not right now, but we should support it. PRs welcome!
You can define a class that implements call
method and use that class in helper or in coerce_with.
class QueryPreprocessor
def self.call(query)
query.split(/\s+/).map(&:to_i)
end
end
# api
route_param :cat_id do
helpers do
def preprocess_query(query)
QueryPreprocessor.call(query)
end
end
params do
optional :query, type: String, coerce_with: ->(val) { QueryPreprocessor.call(val) }
end
...
end
More info, see README.
It would be great if this future feature included accessing helpers in the documentation blocks well.
Leaving a +1, we recently needed to parse an array of ids from a string like 1,2,3
and wanted to have a global helper function that does that.
You could monkey patch the ParamsScope class:
class Grape::Validations::ParamsScope
def process_query
-> (query) { puts 'some fancy processing' }
end
end
then:
params do
optional :query, type: String, coerce_with: process_query
end