3

Suppose my views need to pass some params that are absolutely not related to a model. What are the best ways to sanitize the input in the controller ?

Eg - Validate inclusion of a parameter in a string array : display_type param that sets whether search results are displayed on a map or in a list, as cards, etc., but only a few are defined and available - Validate the type/numericality of some parameter (eg params[:page] should be an integer or fallback to default page 0

Currently I'm using something like

def validate_xxx_param
  if ['map', 'card'].include?(params[:display_type))
    ...
  else
    ...
  end
end

But is there a cleaner/better OOP way of doing that ?

Cyril Duchon-Doris
  • 12,964
  • 9
  • 77
  • 164

1 Answers1

0

You can move this validation to Service object

class ValidateXXXParam
  def initialize(param)
    @param = param
  end

  def call
    if ['map', 'card'].include?(@param)
      ...
    else
      ...
    end
  end
end

# call it in controller
ValidateXXXParam.new(params[:display_type]).call

This is a good way to keep your controller's code clean and dry.

Alex Kojin
  • 5,044
  • 2
  • 29
  • 31
  • Would you call it after/before checking for strong parameters ? How would you handle validation failures ? Raising an exception similarly to unpermitted parameters ? – Cyril Duchon-Doris Jan 02 '17 at 23:59