[Rails] Parameters validation and type conversion with rails_param

Rails makes it easy to deal with HTTP parameters when they are linked to a model or an ActiveModel class.

Remember that it’s never a good thing to write big blocks of code in your controller just to validate and manipulate parameters.

If you are building a complex search form, don’t hesitate to link it to a non-persistent ActiveModel class, like ActiveModel::Model. There are many resources on the Web to learn this kind of good practices, and stay in the “thin controller” rule.

But sometimes, it’s not practical to create an external class just to validate and convert a few parameters.

Thanks to Vincent Ollivier I discovered the gem sinatra-param from Mattt Thompson. This gem is great as it provides a clean and readable way to do parameters validation and conversion for the Sinatra framework.

I decided to port it to Rails, and here it is : rails_param.

With rails_param, you can easily validate and convert the parameters using the param! method inside your controller actions.

As always, feel free to test, share and hack!

Here is a small example extracted from the README:


  # GET /search?q=example
  # GET /search?q=example&categories=news
  # GET /search?q=example&sort=created_at&order=asc
  def search
    param! :q,           String, required: true
    param! :categories,  Array
    param! :sort,        String, default: "title"
    param! :order,       String, in: %w(asc desc), transform: :downcase, default: "asc"
    param! :price,       String, format: "[<\=>]\s*\$\d+"

    {...}
  end
end
  1. nico-in-the-cloud posted this
blog comments powered by Disqus