Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby one line "check value and return"

I'm digging through some interesting code which I'm convinced is wrong. I wondered whether anyone had a thought as to the syntax the developer was trying to use?

Heres' the bogus code:

render :nothing => true and return if params[:name].nil?

My naive fix alludes to my programming language background:

if params[:name].nil?
  render :nothing => true, :status => 404
  return
end

Is there a more elegant, more ruby-like way? (semicolons don't count :)

like image 293
Julian H Avatar asked Nov 29 '22 06:11

Julian H


2 Answers

Because in Ruby Operator Precedence, if has lower precedence than and, this works exactly as it reads, and is in fact quite common in a lot of rails code that I have seen.

like image 170
jamuraa Avatar answered Dec 06 '22 23:12

jamuraa


Simple:

return render(:nothing => true) unless params[:name]

But, better:

return render(:nothing => true)  if params[:name].blank?
like image 29
potapuff Avatar answered Dec 07 '22 00:12

potapuff