Check your params

I just asked myself (and the community) where validating and cleaning up the GET/POST parameters would fit best in Rails. lebreeze at Stackoverflow suggested a sanitize_params method that is called by a before_filter in the ApplicationController. I agree that the ApplicationController is a good place, but I don’t like the fact that it is called and parameters are checked for every controller and action (since they all inherit from the ApplicationController by default) regardless of whether any parameters are needed at all in the action. A workaround would be to check the controller name and action (by using controller_name and action_name methods) in the sanitize_params method and act accordingly, but this is not very intuitive in my opinion. So I decided against a before_filter and call a fetch_param method from within every action with the parameter name I’d like to fetch. That way one could also pass extra options that influence how the parameters are fetched. Here is a little example how the fetch_param method in the ApplicationController may look like. By setting it as helper_method I also ensure that it can be accessed by the view templates.

If you have a better (or alternative) solution then I would like to hear.

# app/controllers/application_controller.rb
...
helper_method :fetch_param
 
def fetch_param(:name, :options = {})
@fetched_params ||= Hash.new
 
  if name == :page
    @fetched_params[:page] ||= check_integer(params[:page], 1, :min => 1)
  elsif name == :per_page
    @fetched_params[:per_page] ||= check_integer(params[:per_page], 25, :min => 1, :max => options[:max])
  elsif ...
  ...
end
...

The check_integer method is part of a small gem named ParamChecker that I created for handling those recurring parameter checking tasks. ParamChecker also contains functions for checking floats (check_float), strings (check_string), symbols (check_symbol) and booleans (check_boolean).

For more info please see the ParamChecker GitHub repository.