Ruby-on-rails – If string is empty then return some default value

rubyruby-on-rails

Often I need to check if some value is blank and write that "No data present" like that:

@user.address.blank? ? "We don't know user's address" : @user.address

And when we have got about 20-30 fields that we need to process this way it becomes ugly.

What I've made is extended String class with or method

class String
  def or(what)
    self.strip.blank? ? what : self
  end
end

@user.address.or("We don't know user's address")

Now it is looking better. But it is still raw and rough

How it would be better to solve my problem. Maybe it would be better to extend ActiveSupport class or use helper method or mixins or anything else. What ruby idealogy, your experience and best practices can tell to me.

Best Answer

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'