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

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).


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'