Search code examples
ruby-on-rails-5

how to validate parameter value in ruby on rails?


example contrived for this question. what is the best way to validate values of parameters passed in ruby on rails. I want to make sure the value of property parameter is one of the allowed values ( auto , home, boat). also what is the best way to validate id is a valid numeric value.

Module Lib
 class Service
  include HTTParty 
  base_uri "https://www.quotescomare.com"

  class << self

    def QuoteSearch (property, id)
     begin 
       response = HTTParty.get(url/property/id)
       if response.successful?
         filter_json(response)
       else
         raise 'invalid response'
       end
     end
   end
  end
 end
end

Solution

  • Regarding the allowed values, you can create a simple constant with the valid values, like this:

    PERMITTED_PROPERTIES = %w(auto home boat).freeze
    

    And then you can check if the property is one of them:

    PERMITTED_PROPERTIES.include?(property)
    

    About the check to see if the id is numeric, you can do this:

    id.is_a? Numeric