Class: FormTemplateYamlValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/validators/form_template_yaml_validator.rb

Constant Summary collapse

RESERVED_KEYWORDS =
%w[title body category category_id tags]
ALLOWED_TYPES =
%w[checkbox dropdown input multi-select textarea upload]

Instance Method Summary collapse

Instance Method Details

#check_allowed_types(record, yaml) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/validators/form_template_yaml_validator.rb', line 18

def check_allowed_types(record, yaml)
  yaml.each do |field|
    if !ALLOWED_TYPES.include?(field["type"])
      return(
        record.errors.add(
          :template,
          I18n.t(
            "form_templates.errors.invalid_type",
            type: field["type"],
            valid_types: ALLOWED_TYPES.join(", "),
          ),
        )
      )
    end
  end
end

#check_ids(record, yaml) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/validators/form_template_yaml_validator.rb', line 46

def check_ids(record, yaml)
  ids = []
  yaml.each do |field|
    next if field["id"].blank?

    if RESERVED_KEYWORDS.include?(field["id"])
      return(
        record.errors.add(:template, I18n.t("form_templates.errors.reserved_id", id: field["id"]))
      )
    end

    if ids.include?(field["id"])
      return(record.errors.add(:template, I18n.t("form_templates.errors.duplicate_ids")))
    end

    ids << field["id"]
  end
end

#check_missing_fields(record, yaml) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/validators/form_template_yaml_validator.rb', line 35

def check_missing_fields(record, yaml)
  yaml.each do |field|
    if field["type"].blank?
      return(record.errors.add(:template, I18n.t("form_templates.errors.missing_type")))
    end
    if field["id"].blank?
      return(record.errors.add(:template, I18n.t("form_templates.errors.missing_id")))
    end
  end
end

#validate(record) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'lib/validators/form_template_yaml_validator.rb', line 7

def validate(record)
  begin
    yaml = Psych.safe_load(record.template)
    check_missing_fields(record, yaml)
    check_allowed_types(record, yaml)
    check_ids(record, yaml)
  rescue Psych::SyntaxError
    record.errors.add(:template, I18n.t("form_templates.errors.invalid_yaml"))
  end
end