Process validation messages with Decorator

There was a terrible situation, and I wanted to process the validation message after it was generated according to the input pattern of the form, so make a note. For example, suppose you have the following form.

new.slim


= form_for post_form, url: confirm_post_path do |f|
  - if post_form.errors.present?
    ul
      - post_form.errors.full_messages.each do |msg| 
        li = msg

However, suppose that you have added the requirement to change the validation message if you choose a particular option in the form. In this case, errors.full_messages is an Array, so I checked the contents one by one with Decorator and replaced them with brute force.

new.slim


= form_for post_form, url: confirm_post_path do |f|
  - post_form_decorator = ::PostFormDecorator.new(f.object)
  - if post_form.errors.present?
    ul
      - post_form_decorator.post_error_display(post_form.errors.full_messages).each do |msg|
        li = msg

post_form_decorator.rb


class PostFormDecorator
  delegate_missing_to :@post_form

  def initialize(post_form)
    @post_form = post_form
  end

  def post_error_display(error_full_messages)
    error_full_messages.each do |msg|
      if @post_form.category == 'music'
        msg.gsub!(/#{@post_form.model.class.human_attribute_name(:author)}/, 'singer')
      end
    end
  end
end

Note that since the contents are replaced by a destructive method, it will not be replaced by gsub unless "!" Is added.

Recommended Posts

Process validation messages with Decorator
JSON validation with JSON schema
Self-made Validation with Spring
[macOS] Process Target-Action with Combine
Validation of log messages using mockito
Get validation results with Spring Boot
Add Bean Validation with Micronaut (Java)
Easy input check with Bean Validation!
Process Communication using AMQP with RabbitMQ