[英]Check if not nil and not empty in Rails shortcut?
I have a show page for my Users and each attribute should only be visible on that page, if it is not nil and not an empty string. 我为用户提供了一个显示页面,并且每个属性仅在该页面上可见,如果它不是nil且不是空字符串。 Below I have my controller and it is quite annoying having to write the same line of code
@user.city != nil && @user.city != ""
for every variable. 下面我有我的控制器,为每个变量写同一行代码
@user.city != nil && @user.city != ""
很烦人。 I am not too familiar with creating my own methods, but can I somehow create a shortcut to do something like this: @city = check_attr(@user.city)
? 我对创建自己的方法不太熟悉,但是我可以以某种方式创建执行以下操作的快捷方式:
@city = check_attr(@user.city)
吗? Or is there a better way to shorten this procedure? 还是有缩短此过程的更好方法?
users_controller.rb 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
There's a method that does this for you: 有一种方法可以为您做到这一点:
def show
@city = @user.city.present?
end
The present?
present?
method tests for not- nil
plus has content. 对于不可─方法测试
nil
加了内容。 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: 由于这种模式非常普遍,因此ActiveRecord中甚至有一个快捷方式:
def show
@city = @user.city?
end
This is roughly equivalent. 这大致相等。
As a note, testing vs nil
is almost always redundant. 注意,测试vs
nil
几乎总是多余的。 There are only two logically false values in Ruby: nil
and false
. 在Ruby中只有两个逻辑上错误的值:
nil
和false
。 Unless it's possible for a variable to be literal false
, this would be sufficient: 除非将变量的字面值设为
false
,否则就足够了:
if (variable)
# ...
end
This is preferable to the usual if (!variable.nil?)
or if (variable != nil)
stuff that shows up occasionally. 这比通常的
if (!variable.nil?)
或if (variable != nil)
偶尔出现的东西要好。 Ruby tends to wards a more reductionist type of expression. Ruby倾向于使用一种更为简化的表达方式。
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. 您要与
nil
进行比较的一个原因是,如果您具有可以为true
, false
或nil
的三态变量,并且需要区分最后两个状态。
You can use .present? 您可以使用.present吗? which comes included with ActiveSupport.
这是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?
值得注意的是,如果要测试是否为空白,可以使用
.blank?
(this is the opposite of .present?
) (这与
.present?
相反)
Also, don't use foo == nil
. 另外,不要使用
foo == nil
。 Use foo.nil?
使用
foo.nil?
instead. 代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.