# 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