Sha256: 2aa14bd94ec9874c70eb6ceb64a5e8af67cbed09077d447e8df60dffe67ad5ec

Contents?: true

Size: 1.71 KB

Versions: 2

Compression:

Stored size: 1.71 KB

Contents

# frozen_string_literal: true

module Lipstick
  module Helpers
    class FormValidationBuilder
      def initialize(sym)
        @rules = {}
        @messages = {}
        @sym = sym
      end

      def to_h
        { rules: @rules, messages: @messages }
      end

      def validate_field(field, opts)
        target = wrap_name(field)

        opts.each do |k, v|
          next validate_with_hash(target, k, v) if v.is_a?(Hash)
          validate_with_param(target, k, v)
        end
      end

      def auto_validate(obj, *fields)
        unless obj.class.respond_to?(:lipstick_auto_validators)
          raise("#{obj.class.name} does not include Lipstick::AutoValidation")
        end

        validators = obj.class.lipstick_auto_validators
        validators.slice(*fields).each do |field, opts|
          validate_field(field, opts)
        end
      end

      private

      def validate_with_hash(target, validation, opts)
        message = opts.delete(:message)
        add_message(target, validation, message) if message

        return validate_with_param(target, validation, true) if opts.empty?

        if opts.keys == [:param]
          return validate_with_param(target, validation, opts[:param])
        end

        add_rule(target, validation, opts)
      end

      def validate_with_param(target, validation, param)
        add_rule(target, validation, param)
      end

      def add_rule(target, key, value)
        @rules[target] ||= {}
        @rules[target][key] = value
      end

      def add_message(target, key, value)
        @messages[target] ||= {}
        @messages[target][key] = value
      end

      def wrap_name(name)
        return name if @sym.nil?
        "#{@sym}[#{name}]"
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
aaf-lipstick-3.0.4 lib/lipstick/helpers/form_validation_builder.rb
aaf-lipstick-3.0.2 lib/lipstick/helpers/form_validation_builder.rb