Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If string is empty then return some default value

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.

like image 957
fl00r Avatar asked Jan 27 '11 14:01

fl00r


People also ask

Is string empty by default?

Empty is not a compile-time constant. It is a static property defined in the string class. Because it is not a compile constant, you cannot use it for the default value for a parameter.

What is the default value of null?

The value produced by setting all value-type fields to their default values and all reference-type fields to null . An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.

What is empty return string?

C++ String empty() Function returns a Boolean value either true or false.

What is the value of string empty?

An empty string is a string instance of zero length, whereas a null string has no value at all. An empty string is represented as "" . It is a character sequence of zero characters. A null string is represented by null .


1 Answers

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' 
like image 118
David Phillips Avatar answered Sep 22 '22 17:09

David Phillips