Module: Tram::Validators
- Defined in:
- lib/tram/validators.rb
Constant Summary collapse
- CONDITIONS =
Standard conditions to check
{ equal_to: ->(value, limit) { value == limit }, other_than: ->(value, limit) { value != limit }, less_than: ->(value, limit) { value < limit }, less_than_or_equal_to: ->(value, limit) { value <= limit }, greater_than: ->(value, limit) { value > limit }, greater_than_or_equal_to: ->(value, limit) { value >= limit } }.freeze
Class Method Summary collapse
-
.chained_value(record, chain) ⇒ Object
Gets value of chained attribute.
-
.copy_errors(source, target, name, key, value, **opts) ⇒ Object
Copies errors from source to target if either nested or original keys selected.
-
.nested_key(target, source) ⇒ Object
Builds nested key.
-
.validators(attr, options, *blacklist) ⇒ Object
Extracts nested validators from options.
Class Method Details
.chained_value(record, chain) ⇒ Object
Gets value of chained attribute
18 19 20 |
# 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) ⇒ Object
Copies errors from source to target if either nested or original keys selected
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# 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..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) ⇒ Object
Builds nested key
39 40 41 42 43 44 45 46 |
# 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) ⇒ Object
Extracts nested validators from options
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/tram/validators.rb', line 49 def validators(attr, , *blacklist) .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 |