3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

if hoge.present?はpresence.tryでifを消せたりする

Posted at

例えばviewファイルで

view.html.erb
<%# @model.hogehoge => 1 %>
<%= @model.hogehoge + '日' if @model.hogehoge.present? %>
<%# => 1日 %>

とか@model.hogehogeが2回出てくるのが憎い

こう書ける

view.html.erb
<%= @model.hogehoge.to_s.presence.try(:+, '日') %>

もっとも、このケースではtメソッドを使うべきですよね

view.html.erb
<%= @model.hogehoge.to_s.presence.try(:+, t('datetime.prompts.day')) %>

<%#= lazy lookupを使ってさらに簡潔に?(yml割愛しますが、hogehoge: "%{day}日"みたいな感じです。.to_sはずせますね) %>
<%= @model.hogehoge.presence.try{|s| t '.hogehoge', day: s} %>

localeの定義はこちらにあわせてます
https://github.com/svenfuchs/rails-i18n/blob/master/rails/locale/ja.yml


ちなみに

処理 if hogehoge.present?

も以下のように書ける時があります

hogehoge.presence && 処理

個人的にこっちの方が読みやすいです
ただし、厳密にはイコールではないので注意が必要です(思考停止の一括置換は危険)

3
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?