Search code examples
ruby-on-railsrubyactiverecordrubygemsransack

How do you configure ransack to strip leading and trailing whitespace as a default?


I have multiple search bars (over 20) in a web application that uses a ruby's ransack gem (https://github.com/activerecord-hackery/ransack).

Does anyone know of a how I can strip out the leading and trailing white spaces for all (20+) searches?

My current solution is to create the following method in the application helper:

def strip_query
  params[:q] = Hash[params[:q].map { |key, str| [key, str.strip] }] unless params[:q].blank?
end

And call the method at the start of each controller:

 include ApplicationHelper
 before_action :strip_query, only: :index

I am looking for a DRY method that does not repeat the code in all 20+ controllers.

https://github.com/activerecord-hackery/ransack/issues/332

Suggests it possible to create a new predicate in a config/initializers/ransack.rb file, but this would require altering the searches in each view to refer to the new predicate.

What is the best way of customizing this for my problem? Is it possible to configure ransack to strip white-spaces as a default for all search queries?


Solution

  • I would add a method like this to the application_controller.rb

    def query_params
      query = params[:q] || {}
      Hash[query.map { |key, value| [key, value.strip] }]
    end
    

    And then change the calls in your controllers from Foo.ransack(params[:q]) to:

    Foo.ransack(query_params)