Little helper to deal with nils, empty strings and arrays.
class ::Object
def blank?; false end
def or(default = nil)
blank? ? (block_given? ? yield : default) : self
end
def and
blank? ? nil : yield(self)
end
end
class ::FalseClass
def blank?; true end
end
class ::NilClass
def blank?; true end
end
class ::Array
def blank?; compact.empty? end
end
class ::String
def blank?; strip.empty? end
end
class ::Hash
def blank?; values.empty? end
end
Examples:
" ".or "Untitled" # => "Untitled"
" ".or { calculate_value } # => "42"
[nil].or { ["apple", "orange"] } # => ["apple", "orange"]
"data".and {|data| Wrapper.new(data) } # => wrapper
" ".and { ... } # => nil