module Tram::Validators

Constants

CONDITIONS

Standard conditions to check

Public Class Methods

chained_value(record, chain) click to toggle source

Gets value of chained attribute

# File lib/tram/validators.rb, line 18
def chained_value(record, chain)
  chain.to_s.split(".").inject(record) { |obj, name| obj&.send(name) }
end
copy_errors(source, target, name, key, value, **opts) click to toggle source

Copies errors from source to target if either nested or original keys selected

# File lib/tram/validators.rb, line 24
def copy_errors(source, target, name, key, value, **opts)
  nested   = opts[:nested_keys]
  original = opts[:original_keys]

  if !nested && !original
    target.errors.add(name, key, record: target, value: value)
  else
    source.errors.messages.each do |k, texts|
      target_key = nested ? nested_key(name, k) : k
      texts.each { |text| target.errors.add(target_key, text) }
    end
  end
end
nested_key(target, source) click to toggle source

Builds nested key

# File lib/tram/validators.rb, line 39
def nested_key(target, source)
  source.to_s
        .split(/\[|\]/)
        .compact
        .reject { |key| %w(base itself).include? key.to_s }
        .inject(target) { |obj, key| "#{obj}[#{key}]" }
        .to_sym
end
validators(attr, options, *blacklist) click to toggle source

Extracts nested validators from options

# File lib/tram/validators.rb, line 49
def validators(attr, options, *blacklist)
  options.map.with_object({}) do |(key, opts), obj|
    name = key.to_s

    next if blacklist.map(&:to_s).include? name
    next if %w(allow_nil if unless on message).include? name

    opts = {} unless opts.is_a? Hash
    obj[key] = find_validator_by_name(name).new(attributes: attr, **opts)
  end
end

Private Class Methods

find_validator_by_name(name) click to toggle source
# File lib/tram/validators.rb, line 63
def find_validator_by_name(name)
  klass_name = "#{name.camelize}Validator"
  klass_name.constantize
rescue
  ActiveModel::Validations.const_get(klass_name)
end