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.
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.
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.
C++ String empty() Function returns a Boolean value either true or false.
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 .
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With