Sha256: a7cc86b3445d18868961fb2a64dc685d98895106a166613ba6f8f6168e896ba0

Contents?: true

Size: 1.09 KB

Versions: 1

Compression:

Stored size: 1.09 KB

Contents

require_relative "rails_bootstrap_error_renderer/version"

require "nokogiri"
require "active_support"
require "active_support/core_ext"

module RailsBootstrapErrorRenderer
  IGNORED_TYPES = %w[checkbox hidden]

  def self.render(html, instance)
    fragment = Nokogiri::HTML::DocumentFragment.parse(html)
    element = fragment.children[0]
    if should_process_element?(element)
      render_for_element(element, instance)
    else
      html
    end
  end

  def self.should_process_element?(element)
    return unless element
    element.attributes["data-render-errors"].to_s != "false"
  end

  def self.render_for_element(element, instance)
    element.add_class("is-invalid")
    if applicable_input? element
      msgs = Array.wrap(instance.error_message).map { |m| %(<div class="invalid-feedback">#{m}</div>) }.join("\n")
      instance.raw(
        %(#{element.to_html}\n#{msgs})
      )
    else
      instance.raw element.to_html
    end
  end

  def self.applicable_input?(element)
    %w[input select textarea].include?(element.name) && !IGNORED_TYPES.member?(element.attributes["type"]&.to_s)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rails_bootstrap_error_renderer-1.2.0 lib/rails_bootstrap_error_renderer.rb