Hash Selectorパターン

Hash Selector Pattern」を読んだ。

if / elsecase / switchよりもHashを使用したほうが可読性が上がるよねという事例が紹介されている。

# if / elseの場合
if flash[:type] == :success
  'alert-success'
elsif flash[:type] == :error
  'alert-danger'
elsif flash[:type] == :warn
  'alert-warning'
elsif flash[:type] == :info
  'alert-info'
end

# case / switchの場合
case flash[:type]
when :success then 'alert-success'
when :error   then 'alert-danger'
when :warn    then 'alert-warning'
when :info    then 'alert-info'
end
# Hash Selectorパターンの場合
{ success: 'alert-success',
  error:   'alert-danger',
  notice:  'alert-info',
  warn:    'alert-warning' }[flash[:type]]

更に一歩進んでProcを使用したHash Selectorパターンが紹介されていて、勉強になった。

if @comment.save
  respond_with @post, @comment
else
  xms_error @comment
end

これが以下のように書ける。

{ true  => -> { self.respond_with @post, @comment },
  false => -> { self.xms_error @comment } 
}[@comment.save].call

確かに後者のほうが簡潔だ。