ruby-on-rails - 基于 1 个对象检查 2 个条件的更好方法
问题描述
我通常需要使用这种方法来检查对象是否存在以及该对象是否返回特定值或行为。这是编写此代码的更好方法吗?
def set_current_theme
if current_tenant && current_tenant.has_custom_domain?
@theme = Theme.last || Theme.create
end
end
乍一看,我只想添加一个条件:这就if current_tenant.has_custom_domain?
足够了。但结果通常是 nil 类没有这样的方法(在这种情况下has_custom_domain?
)。
解决方案
更短(我认为更好)的方法是像这样使用&.
(它的简写try!
)。
if current_tenant&.has_custom_domain?
@theme = Theme.last || Theme.create
end
推荐阅读
- r - 识别逆序组合
- c++ - SimpleElastix 构建错误 windows 10 Visual Studio 2017
- c - 无需 malloc 和 calloc 动态分配数组
- excel - 如何在excel中对一个单词进行子串并添加一个字母并转换为大写
- python - 如何在 Keras Tensorflow 中为采样创建自定义层?
- google-app-engine - Google Cloud SQL 实例的连接选项卡永远加载控制台界面
- java - Java.text.ParseException:无法解析的日期
- unity3d - 从服务器获取 AssetBundle 清单文件
- php - 如何从 2 个 URL 请求中一次性组合 2 个 json 响应
- elasticsearch - Vega 和 Kibana - 动态时间戳标签和过滤查询