Glenn Gillenは、 Rails での便利なフラッシュ メッセージと呼ばれるアプローチを採用しています。
私は彼のコード スニペットをもう少し慣用的なものに変更しました (少なくとも私にとっては)。
コントローラーは次のようにフラッシュを塗りつぶします。
flash[:notice] = "Your profile was updated. %s"
flash[:notice_item] = ["Edit again?", edit_profile_path(@profile)]
次に、次のようなヘルパーを作成できます。
def render_flash_messages(*keys)
messages = keys.collect do |key|
content_tag(:p, flash_message_with_item(key), :class => "flash #{key}") if flash[key]
end.join
content_tag(:div, messages, :id => "flash_messages") unless messages.blank?
end
def flash_message_with_item(key)
item = flash["#{key}_item".to_sym]
substitution = item.is_a?(Array) ? link_to(*item) : item
flash[key] % substitution
end
ビューは次のようになります。
<%= render_flash_messages(:error, :notice, :warning) %>
ビューは (flash_message_with_item
ヘルパーを介して) アンカー タグの作成を担当しますが、コントローラーは、さらなるアクションのためのオプションのリソースを含むフラッシュ メッセージに入る内容を管理します。