Sha256: 015ca0e1ee5b045feb0da44b6aa85f4485c7aaa06580db97c84f52eef30fba32

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 KB

Contents

# -*- encoding: utf-8 -*-
# -*- frozen_string_literal: true -*-
# -*- warn_indent: true -*-

module RailsBootstrapForm
  module Helpers
    module Errors
      extend ActiveSupport::Concern

      def self.included(base_class)
        def is_invalid?(attribute)
          (attribute && object.respond_to?(:errors) && object.errors[attribute].any?) ||
            has_association_error?(attribute)
        end

        # def input_with_error(attribute, &block)
        #   input = capture(&block)
        #   input << generate_error(attribute)
        #   input
        # end

        def generate_error(attribute)
          if is_invalid?(attribute)
            error_text = error_messages(attribute)
            error_klass = "invalid-feedback"

            tag.div(error_text, class: error_klass)
          end
        end

        def has_association_error?(attribute)
          object.class.try(:reflections)&.any? do |association_name, association|
            next unless is_belongs_to_association?(association)
            next unless is_association_same?(attribute, association)

            object.errors[association_name].any?
          end
        end

        def error_messages(attribute)
          messages = object.errors[attribute]

          object.class.try(:reflections)&.each do |association_name, association|
            next unless is_belongs_to_association?(association)
            next unless is_association_same?(attribute, association)

            messages << object.errors[association_name]
          end

          messages.flatten.to_sentence
        end

        def is_belongs_to_association?(association)
          association.is_a?(ActiveRecord::Reflection::BelongsToReflection)
        end

        def is_association_same?(attribute, association)
          (association.foreign_key == attribute.to_s)
        end

        private :is_invalid?, :generate_error, :has_association_error?,
                :error_messages, :is_belongs_to_association?, :is_association_same?
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rails_bootstrap_form-0.9.7 lib/rails_bootstrap_form/helpers/errors.rb