Ruby on Rails Friday, November 6, 2015

On Fri, Nov 6, 2015 at 10:03 AM Colin Law <clanlaw@gmail.com> wrote:
On 5 November 2015 at 23:17, wbsurfver@yahoo.com <wbsurfver@gmail.com> wrote:
>
> instead of this:
>
> def rqstate
>    self.quote_request.status rescue "unsubmitted"
> end
>
> I'm going for this, though maybe there is a good one liner I overlooked ?
>
> def rqstate
>     ret_res = "unsubmitted"
>     ret_res = quote_request.status || ret_res if quote_request
>     ret_res
>   end

How about
def rqstate
  (quote_request && quote_request.status)  ?  quote_request.status  :
"unsubmitted"
end

If you're using Rails, another approach is to use try (http://apidock.com/rails/Object/try).

def rqstate
  quote_request.try(:status) || "unsubmitted"
end
 
#try is very nice in this case, but avoid overdoing it. I have faced many codebases with tons of try methods chained and then you lose code readability.


Not only a one liner but I think easier to understand.  Assuming I
have got it right :)

Colin

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLtLLog2%2B3B0EV0gy4jwQLCt5FgUzBKZBRLRmmh95JEJQg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CACMkcE41cpqhNK-W9Y9XP2AummBfabOTQguTEtR2WmopR%2B3M%3Dg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment