Alex Rivera | Logout

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

Asked 2010-09-02T22:26:23.163
13

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.

Edit
Report

1 Answer

1

Perhaps this might serve:

class Object
  def subst_if(condition, replacement)
    condition = send(condition) if condition.respond_to?(:to_sym)
    if condition
      replacement
    else  
      self
    end
  end
end

Used like so:

p ''.subst_if(:empty?, 'empty')       # => "empty"
p 'foo'.subst_if(:empty?, 'empty')    # => "foo"

It also takes stand-alone conditions, not related to the object:

p 'foo'.subst_if(false, 'bar')    # => 'foo'
p 'bar'.subst_if(true,  'bar')    # => 'bar'

I'm not crazy about the name subst_if. I'd borrow whatever name Lisp uses for this function, if I knew it (assuming it exists).

answered 2010-09-02T23:49:19.350

Your Answer