Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Testing for nil or empty params in Ruby on Rails (See related posts)

I find myself doing these 4 things a lot:
if params[:object] && !params[:object].empty
if params[:object] && params[:object] == value
if params[:object][:attribute] && !params[:object][:attribute].empty
if params[:object][:attribute] && params[:object][:attribute] == value

I put params_check() in my application.rb and it allows me to do this instead:
if params_check(:object)
if params_check(:object, value)
if params_check([:object, :attribute])
if params_check([:object, :attribute], value)

  def params_check(*args)
    if args.length == 1
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && !params[args[0][0]][args[0][1]].empty?
          true
        end
      else        
        if params[args[0]] && !params[args[0]].empty?
          true
        end
      end
    elsif args.length == 2
      if args[0].class == Array
        if params[args[0][0]][args[0][1]] && params[args[0][0]][args[0][1]] == args[1]
          true
        end
      else
        if params[args[0]] && params[args[0]] == args[1]
          true
        end
      end  
    end
  end

I stole this off another snippet and modified it to add more conditions. Thanks to whoever it was.

Comments on this post

vinterbleg posts on Apr 29, 2008 at 04:26
Another way to significantly reduce the readability of your code. :P

- Simon
alxx posts on Apr 29, 2008 at 07:04
I agree with Simon. What's wrong with simply comparing:

if params[:object][:attribute].to_s == value


(or to_i if you expect an integer, etc.)

Moreover, what you're doing there is mostly validations, which belong directly in the model, not the controller. So why not simply initialize the object with params[:object] and check the values where they should be checked, in the model?

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts