Ruby on Rails Helpful Helpers: Defaulting Variables

One piece of code I find myself using a lot is for defaulting values using a simple conditional if statement: condition ? true : false. This isn’t bad in itself, but it also isn’t very powerful and dynamic. I wrote a small application helper which wraps this function and provides a pretty nice way of setting default values.

  def default(object, default = 'n/a')
    return default if object.blank?
    block_given? ? yield(object) : object
  end

Usage

A very simple example:

#
# Simple Example
#

my_string = ''
puts default(my_string, 'String is empty')
# => 'String is empty'

my_string = 'hello world'
puts default(my_string, 'String is empty')
# => 'hello world'

my_string = 'hello world'
puts default(my_string, 'String is empty') { |str| str.titleize }
# => 'Hello World'

#
# Yielding example
#

puts default(current_user, 'Guest') { |user| user.name.titleize }


Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow



About Author

Rob Hurring

Ruby, Rails, PHP, bash... oh my!