在 Rails 快捷方式中检查是否为空?

我有一个显示我的用户页面和每个属性应该只有在该页面上可见,如果它不是 nil 和不是一个空字符串。下面我有我的控制器,它是相当恼人的编写相同的代码行 @user.city != nil && @user.city != ""为每个变量。我不太熟悉创建我自己的方法,但是我可以创建一个快捷方式来做这样的事情: @city = check_attr(@user.city)?还是有更好的办法缩短手术时间?

Users _ controller. rb

def show
@city = @user.city != nil && @user.city != ""
@state = @user.state != nil && @user.state != ""
@bio = @user.bio != nil && @user.bio != ""
@contact = @user.contact != nil && @user.contact != ""
@twitter = @user.twitter != nil && @user.twitter != ""
@mail = @user.mail != nil && @user.mail != ""
end
177852 次浏览

You can use .present? which comes included with ActiveSupport.

@city = @user.city.present?
# etc ...

You could even write it like this

def show
%w(city state bio contact twitter mail).each do |attr|
instance_variable_set "@#{attr}", @user[attr].present?
end
end

It's worth noting that if you want to test if something is blank, you can use .blank? (this is the opposite of .present?)

Also, don't use foo == nil. Use foo.nil? instead.

There's a method that does this for you:

def show
@city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
@city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
# ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.