Module: ConstraintValidations::Engine::ValidationMessageExtension

Defined in:
lib/constraint_validations/engine.rb

Instance Method Summary collapse

Instance Method Details

#renderObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/constraint_validations/engine.rb', line 52

def render
  index = @options.fetch("index") { @options.fetch(:index, @auto_index) }
  validation_message_id = FormBuilder.validation_message_id(@template_object, @object_name, @method_name, index: index, namespace: @options[:namespace])

  attributes = @options

  if @html_options.is_a?(Hash)
    attributes = @html_options
    attributes.reverse_merge!("required" => @options.delete("required"))
  end

  if FormBuilder.visible?(self)
    attributes["aria-errormessage"] ||= validation_message_id
  end

  if @object.present? && FormBuilder.visible?(self)
    config = Rails.configuration.constraint_validations
    source =
      if @object.respond_to?(@method_name)
        config.validation_messages_for_object
      else
        config.validation_messages_for_object_name
      end

    attributes["data-validation-messages"] ||= source.call(**instance_values.to_options).to_json
  end

  if FormBuilder.errors(@object, @method_name).any? && FormBuilder.visible?(self)
    value = attributes["aria-describedby"] || attributes.dig(:aria, :describedby)
    tokens = value.to_s.split(/\s/)
    tokens.unshift validation_message_id

    if attributes.dig(:aria, :describedby)
      attributes.deep_merge! aria: { describedby: tokens }
    else
      attributes.merge! "aria-describedby" => tokens.join(" ")
    end
  end

  super
end