grape icon indicating copy to clipboard operation
grape copied to clipboard

Helpers are not accessible from inside `params` block

Open atshakil opened this issue 6 years ago • 5 comments

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?

atshakil avatar Oct 24 '18 02:10 atshakil

Probably not right now, but we should support it. PRs welcome!

dblock avatar Oct 24 '18 12:10 dblock

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.

darren987469 avatar Oct 28 '18 23:10 darren987469

It would be great if this future feature included accessing helpers in the documentation blocks well.

henrytseng avatar Sep 22 '20 15:09 henrytseng

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.

mcfoton avatar Nov 15 '21 13:11 mcfoton

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

LewisYoul avatar Aug 29 '22 10:08 LewisYoul