簡體   English   中英

如何讓這個Ruby方法更漂亮?

[英]How can I make this Ruby method more beautiful?

我相信條件可以寫得更好:

def update
  if allow_update?
    if @company.update_attributes(params[:company])
      flash.now[:success] = "success message"
    else
      flash.now[:error] = "error message"
    end
  else
    flash.now[:error] = "error message"
  end

  render :show
end

我怎么能改寫這個?

使用&&運算符,可以將兩個if合並為一個:

def update
  if allow_update? && @company.update_attributes(params[:company])
    flash.now[:success] = "success message"
  else
    flash.now[:error] = "error message"
  end

  render :show
end

您可以使用一些字符串插值和三元運算符來縮短代碼。

def update
  allow_update? && @company.update_attributes(params[:company]) ? result = "success" : 
  result = "error"
  flash.now[result.to_sym] = "#{result} messege"
  render :show
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM