Class: LcpRuby::Pages::DefinitionValidator

Inherits:
Object
  • Object
show all
Defined in:
lib/lcp_ruby/pages/definition_validator.rb

Class Method Summary collapse

Class Method Details

.install!(model_class) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lcp_ruby/pages/definition_validator.rb', line 4

def self.install!(model_class)
  fields = LcpRuby.configuration.page_model_fields.transform_keys(&:to_s)
  definition_field = fields["definition"]

  model_class.validate do |record|
    raw = record.public_send(definition_field)
    next if raw.blank?

    hash = raw.is_a?(String) ? JSON.parse(raw) : raw
    hash = LcpRuby::HashUtils.stringify_deep(hash)

    errors_list = []
    errors_list << "missing 'name'" unless hash["name"].present?
    errors_list << "missing 'zones' or empty zones array" unless hash["zones"].is_a?(Array) && hash["zones"].any?

    if errors_list.empty?
      begin
        LcpRuby::Metadata::PageDefinition.from_hash(hash)
        # Model-aware filter-form rules (FK column existence,
        # custom-field reject, api-backed multi reject, scope
        # existence). Loader is fully built by the time
        # DefinitionValidator runs — DB record save happens long
        # after boot. Shape rules already ran inside `from_hash`.
        LcpRuby::Pages::FilterFormValidator.validate_against_models!(
          hash, page_name: hash["name"], loader: LcpRuby.loader
        )
      rescue LcpRuby::MetadataError => e
        errors_list << e.message
      end
    end

    errors_list.each { |err| record.errors.add(definition_field, err) }
  rescue JSON::ParserError => e
    record.errors.add(definition_field, "contains invalid JSON: #{e.message}")
  end
end