Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there built in support in rails for the default value substitution idiom?

I often write code to provide a default value upon encountering nil/empty value.

E.g:

category = order.category || "Any"
#  OR
category = order.category.empty? ? "Any" : order.category

I am about to extend the try method to handle this idiom.

category = order.try(:category, :on_nill => "Any")
#  OR
category = order.try(:category, :on_empty=> "Any")

I am wondering if Rails/Ruby has some method to handle this idiom?

Note:

I am trying to eliminate repetition of || / or / ? operator based idioms.

Essentially I am looking for a equivalent of try method for handling default substitution scenarios.

Without try method:

product_id = user.orders.first.product_id unless user.orders.first.nil? 

With try method:

product_id = user.orders.first.try(:product_id)

It is easy to implement a generic approach to handle this idiom, but I want to make sure I do not reinvent the wheel.

like image 445
Harish Shetty Avatar asked Sep 02 '10 22:09

Harish Shetty


2 Answers

Pretty sure its not baked in. Here is a link to a similar question/answer. It is the approach that I take. Leveraging the ruby: ||= syntax

An aside: This question also reminds me of the first Railscasts of all time: Caching with instance variables which is a useful screencast if you need to do this kind of operation in a Controller

like image 51
Jonathan Avatar answered Oct 19 '22 10:10

Jonathan


See this question. ActiveSupport adds a presence method to all objects that returns its receiver if present? (the opposite of blank?), and nil otherwise.

Example:

host = config[:host].presence || 'localhost'
like image 22
David Phillips Avatar answered Oct 19 '22 10:10

David Phillips