开发者

ruby one line "check value and return"

开发者 https://www.devze.com 2022-12-24 17:38 出处:网络
I\'m digging through some interesting code which I\'m co开发者_如何学JAVAnvinced is wrong. I wondered whether anyone had a thought as to the syntax the developer was trying to use?

I'm digging through some interesting code which I'm co开发者_如何学JAVAnvinced 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 :)


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.


Simple:

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

But, better:

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


As jamuraa said, the "more elegant, more ruby-like way" is the "bogus code". I think adding parens in this case makes it more readable.

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


I see some people suggesting to use "render xxx and return if ..." and I'd strongly recommend against this practice.

The render and redirect API don't state they should always return a truthy value. My preference for writing this is using this idiom:

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

You can find some discussion about this also on Ruby bug's tracker: https://bugs.ruby-lang.org/issues/6201


Old question, but I thought I'd provide a little background on why this line would appear in case somebody else comes across it. This is not bogus at all; it's important to include the "and return" in order to prevent a DoubleRenderError. From the ActionController::Base docs:

If you need to redirect on the condition of something, then be sure to add “and return” to halt 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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号