If the line is empty, return the default value

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

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

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

I created an extended String class using the or method

 class String def or(what) self.strip.blank? ? what : self end end @user.address.or("We don't know user address") 

Now he looks better. But he's still raw and rude

How it would be better to solve my problem. Perhaps it would be better to extend the ActiveSupport class or use a helper method or mixins or something else. What ruby โ€‹โ€‹ideology, your experience and best practices can tell me.

+78
ruby ruby-on-rails
Jan 27 2018-11-11T00:
source share
5 answers

ActiveSupport adds the presence method to all objects that return its receiver, if present? (the opposite of blank? ) and nil otherwise.

Example:

 host = config[:host].presence || 'localhost' 
+203
Jan 27 '11 at 19:24
source share

Phrogz kind of gave me an idea in a PofMagicfingers comment, but what about overriding | instead of this?

 class String def |(what) self.strip.blank? ? what : self end end @user.address | "We don't know user address" 
+12
Jan 27 2018-11-11T00:
source share

Since you are doing this in Ruby on Rails, it looks like you are working with a model. If you want to get a reasonable default value throughout your application, you can (for example) override the address method for your User model.

I don't know ActiveRecord well enough to provide good code for this; in Sequel it will be something like:

 class User < Sequel::Model def address if (val=self[:address]).empty? "We don't know user address" else val end end end 

... but for the example above, it looks like you are mixing the presentation logic in your model, which is not a good idea.

+2
Jan 27 2018-11-11T00:
source share

Your method or may have some unwanted side effects, since an alternative (default) value is always evaluated, even if the string is not empty.

for example

 @user.address.or User.make_a_long_and_painful_SQL_query_here 

will do extra work even if the address is not empty. Maybe you can update this a bit (sorry for the confusion with a single layer, trying to save it):

 class String def or what = "" self.strip.empty? ? block_given? ? yield : what : self end end @user.address.or "We don't know user address" @user.address.or { User.make_a_long_and_painful_SQL_query_here } 
+2
Jan 27 2018-11-11T00:
source share

It might be better to extend ActiveRecord or individual models instead of String.

In your opinion, you may prefer a more explicit pattern, for example

 @user.attr_or_default :address, "We don't know the user address" 
+2
Jan 27 '11 at 19:49
source share



All Articles