Ruby one line "check value and return"

I dig some interesting code that I'm sure is wrong. I wondered if anyone thought of the syntax that the developer was trying to use?

Heres the dummy code:

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

My naive fix refers to my programming language:

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

Is there a more elegant, more ruby ​​way? (semicolons do not count :)

+4
source share
5 answers

Plain:

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

But better:

 return render(:nothing => true) if params[:name].blank? 
+5
source

Because in the Priority of the Ruby operator , if has a lower priority than and , it works exactly as it reads, and is actually quite common in many rails codecs that I have seen.

+12
source

As Jamuraa said, “a more elegant, more ruby-like path” is a “dummy code”. I think adding parens in this case makes it more readable.

 render(:nothing => true) and return if params[:name].nil? 
+4
source

I see some people suggest using "render xxx and return if ..." and I highly recommend against this practice.

The render and redirect APIs do not indicate that they should always return a true value. My preference for writing this is using this idiom:

 (render 'xyz'; return) if condition? (head :ok; return) unless record.invalid? 

You can talk about this about the Ruby bug tracker: https://bugs.ruby-lang.org/issues/6201

+1
source

An old question, but I thought I would provide some information on why this line will appear in case someone else comes across it. This is not fake; it is important to include "and return" to prevent DoubleRenderError. In the docs of ActionController :: Base:

If you need to redirect the condition to something, then be sure to add “and return” to stop execution.

 def do_something redirect_to(:action => "elsewhere") and return if monkeys.nil? render :action => "overthere" # won't be called if monkeys is nil end 
0
source

Source: https://habr.com/ru/post/1305008/


All Articles