Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 変数へif文の結果を格納する場合の記述法の一例(Active::Supportのコードより)

概要

変数へif文の結果を格納する場合の記述法の一例(Active::Supportのコードより)

詳細

変数へif文の結果を格納する場合の記述法の一例がActive::Supportのcore_ext/string/filters.rb
にあった。

おそらく、三項演算子にするには横に長くなりすぎるような場合に利用するのだろう。
実際にActiveSupportのコミットログ上で

 -    length_with_room_for_omission = length - options[:omission].length
 -    stop = options[:separator] ?
 -      (rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission) : length_with_room_for_omission
 +    length_with_room_for_omission = truncate_at - options[:omission].length
 +    stop = \
 +      if options[:separator]
 +        rindex(options[:separator], length_with_room_for_omission) || length_with_room_for_omission
 +      else
 +        length_with_room_for_omission
 +      end

となっているし。
Alexey Gazievさんって方のコミット。こういうときblame機能いいですね。
rubocopなり、のツールで1行が長すぎる=>リファクタリング、の流れかな?
コミットコメントは
「AS core_ext refactoring」

該当処理が気になる方はこちらへ。truncateメソッドを見てください。
https://github.com/rails/rails/tree/master/activesupport/lib/active_support/core_ext/string/filters.rb

サンプル

# encoding: utf-8
require 'tbpgr_utils'

def hoge_or_hige(is_hoge)
  variable = \
    if is_hoge
      # 本当はもっと横に長いコードだと思って見てください
      "hoge"
    else
      # 本当はもっと横に長いコードだと思って見てください
      "hige"
    end

  # other logic

  variable
end

bulk_puts_eval binding, <<-EOS
hoge_or_hige true
hoge_or_hige false
EOS

__END__
下記はTbpgrUtils gemの機能

bulk_puts_eval

詳しくは下記参照
https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

hoge_or_hige true # => "hoge"
hoge_or_hige false # => "hige"