LoginSignup
4

More than 5 years have passed since last update.

devise_error_messages!をbootstrap3で表示しつつrubocopの指摘も回避する

Posted at

やりたいこと

  • devise_error_messages! を bootstrap3 で綺麗に表示したい
  • 下記の記事を参考に実装したが、昔の記事なので rubocop に怒られた

rubocopに怒られないように修正

devise_helper.rb
module DeviseHelper
  def devise_error_messages!
    return '' if resource.errors.empty?

    html = []
    html << content_tag(:div, class: 'alert alert-danger', role: 'alert') do
      content_tag(:ul) do
        resource.errors.full_messages.each do |error_message|
          concat content_tag(:li, error_message.to_s)
        end
      end
    end

    safe_join html
  end

  def devise_error_messages?
    resource.errors.empty? ? false : true
  end
end
こんな感じでエラー表示

rubocop のエラーとその対処法

  • http://www.rubydoc.info/gems/rubocop/0.41.0/RuboCop/Cop/Rails/OutputSafety
  • html_safe ではなく safe_join を使いなさいと言われるので、 html変数を文字列から配列に変更
  • htmlを直書き(or ヒアドキュメント)するのではなく content_tag を使い、タグを入れ子にしたいのでブロックで処理する
  • ただし、 <li> タグは concat で対応

参考記事

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
4