Module: Iron::FieldDefinition::Validations

Defined in:
app/models/iron/field_definition/validations.rb

Defined Under Namespace

Classes: Violation

Constant Summary collapse

RULES =
{
  "required" => { kind: :boolean },
  "allowed_values" => { kind: :string_list },
  "min_length" => { kind: :positive_integer, ceiling: "max_length" },
  "max_length" => { kind: :positive_integer },
  "min" => { kind: :number, ceiling: "max" },
  "max" => { kind: :number },
  "file_scope" => { kind: :file_scope },
  "selected_presets" => { kind: :preset_list }
}.freeze

Class Method Summary collapse

Class Method Details

.cast(kind, value) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
# File 'app/models/iron/field_definition/validations.rb', line 43

def cast(kind, value)
  return nil if value.nil?

  case kind
  when :boolean then cast_boolean(value)
  when :positive_integer then cast_positive_integer(value)
  when :number then cast_number(value)
  when :string_list then cast_string_list(value)
  when :file_scope then cast_file_scope(value)
  when :preset_list then cast_preset_list(value)
  end
end

.cast_rules(config) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'app/models/iron/field_definition/validations.rb', line 33

def cast_rules(config)
  return config unless config.is_a?(Hash)

  config.each_with_object({}) do |(key, value), typed|
    key = key.to_s
    rule = RULES[key]
    typed[key] = rule ? cast(rule.fetch(:kind), value) : value
  end
end

.keys_for(type_handle) ⇒ Object



17
18
19
# File 'app/models/iron/field_definition/validations.rb', line 17

def keys_for(type_handle)
  FieldDefinition.classify_type(type_handle).constantize.supported_validations
end

.violations(type_handle, metadata) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'app/models/iron/field_definition/validations.rb', line 21

def violations(type_handle, )
  return [ Violation.new(attribute: :metadata, message: "must be an object") ] unless .nil? || .is_a?(Hash)

  rules = ( || {}).transform_keys(&:to_s).slice(*RULES.keys).reject { |_key, value| absent?(value) }
  return [] if rules.empty?

  allowed = keys_for(type_handle)
  return [ Violation.new(attribute: :metadata, message: "type #{type_handle} supports no validations") ] if allowed.empty?

  rules.flat_map { |key, value| rule_violations(type_handle, allowed, key, value) } + bound_violations(rules, allowed)
end