Sha256: eb723d995456965a5d2c65731f09f7e2bb94b69ca1bbc41ec5c3d08f4bbbcf9c

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

# frozen_string_literal: true

module Fields
  module Validations::Format
    extend ActiveSupport::Concern

    included do
      embeds_one :format, class_name: "Fields::Validations::Format::FormatOptions"
      accepts_nested_attributes_for :format

      after_initialize do
        build_format unless format
      end
    end

    def interpret_to(model, field_name, accessibility, options = {})
      super
      format&.interpret_to model, field_name, accessibility, options
    end

    class FormatOptions < FieldOptions
      attribute :with, :string, default: ""
      attribute :message, :string, default: ""

      validate do
        Regexp.new(with) if with.present?
      rescue RegexpError
        errors.add :with, :invalid
      end

      def interpret_to(model, field_name, _accessibility, _options = {})
        return if with.blank?

        with = Regexp.new(self.with)

        options = {with: with}
        options[:message] = message if message.present?

        model.validates field_name, format: options, allow_blank: true
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
script_core-0.1.0 spec/dummy/app/models/concerns/fields/validations/format.rb