Sha256: 3f6397dc7e21b11307ea83854e24a275717e4dbe0e6c18701b6e4721c635f893
Contents?: true
Size: 1.69 KB
Versions: 8
Compression:
Stored size: 1.69 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? return validate_with_param(target, validation, opts[:param]) if opts.keys == [:param] 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
8 entries across 8 versions & 1 rubygems