Testing for nil or empty params in Ruby on Rails
1 2 if params[:object] && !params[:object].empty 3 if params[:object] && params[:object] == value 4 if params[:object][:attribute] && !params[:object][:attribute].empty 5 if params[:object][:attribute] && params[:object][:attribute] == value
I put params_check() in my application.rb and it allows me to do this instead:
1 2 if params_check(:object) 3 if params_check(:object, value) 4 if params_check([:object, :attribute]) 5 if params_check([:object, :attribute], value)
1 2 def params_check(*args) 3 if args.length == 1 4 if args[0].class == Array 5 if params[args[0][0]][args[0][1]] && !params[args[0][0]][args[0][1]].empty? 6 true 7 end 8 else 9 if params[args[0]] && !params[args[0]].empty? 10 true 11 end 12 end 13 elsif args.length == 2 14 if args[0].class == Array 15 if params[args[0][0]][args[0][1]] && params[args[0][0]][args[0][1]] == args[1] 16 true 17 end 18 else 19 if params[args[0]] && params[args[0]] == args[1] 20 true 21 end 22 end 23 end 24 end
I stole this off another snippet and modified it to add more conditions. Thanks to whoever it was.