如果字符串为空则返回一些默认值
我经常需要检查某个值是否为空并像这样写没有数据存在":
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
当我们有大约 20-30 个字段需要以这种方式处理时,它就会变得丑陋.
And when we have got about 20-30 fields that we need to process this way it becomes ugly.
我所做的是使用 or
方法扩展 String 类
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
如何更好地解决我的问题.也许最好扩展 ActiveSupport class
或使用辅助方法或 mixins 或其他任何东西.Ruby 的理念、您的经验和最佳实践可以告诉我什么.
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.
ActiveSupport 添加了 如果
方法> 否则.present?
(与blank?
相反)和nil
,则对所有返回其接收者的对象进行presence
ActiveSupport adds a presence
method to all objects that returns its receiver if present?
(the opposite of blank?
), and nil
otherwise.
示例:
host = config[:host].presence || 'localhost'