LoginSignup
2
3

More than 5 years have passed since last update.

【Active Decorator】ある変数が存在した時にのみ、前後に修飾語を付けたい時

Last updated at Posted at 2014-05-20

たとえば、年、月、日を変数として持っており

西暦2014年5月1日

5月1日

西暦2014年5月

のように各々の変数の有無で、表示する内容を変更したい時があったとします。

ActiveDecorator内で下記のようなメソッドを定義します。

module ProductDecorator
  def before_after(value, before, after, condition, not_adapted)
    if condition.call
      return before + value.to_s + after
    else
      return not_adapted
    end
  end
end
  sprintf("%s %s %s", before_after(year, "西暦", "年", lambda{year.present?}, ""), before_after(month, "", "月", lambda{month.present?}, ""), before_after(year, "", "日", lambda{day.present?}, ""))

とやれば、欲しいものが出てきます。before_afterの引数の中身は左から(対象変数、前につける修飾子、後につける修飾子、修飾子を付けたい時の対象変数の条件式、条件式が偽の時の文字列)

業務アプリケーションを作ってる時にはよく出てくるので、まとめてみました。

ちなみに条件式を変えれば、変数の有無だけでない処理が可能です。

なんか他にいい方法がありそうですが、、、
達人の皆様教えてください。

2
3
0

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
2
3