Module: AdfBuilder::Validations

Included in:
Nodes::Node
Defined in:
lib/adf_builder/validations.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



5
6
7
# File 'lib/adf_builder/validations.rb', line 5

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#validate!Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/adf_builder/validations.rb', line 27

def validate!
  self.class.validations.each do |validation|
    if validation[:type] == :inclusion
      value = @attributes[validation[:attribute]]
      next if value.nil?

      allowed = validation[:in]
      # Normalize for comparison (allow string/symbol interchangeably)
      value_s = value.to_s
      allowed_s = allowed.map(&:to_s)

      unless allowed_s.include?(value_s)
        raise AdfBuilder::Error,
              "Invalid value for #{validation[:attribute]}: #{value}. Allowed: #{allowed.join(", ")}"
      end
    elsif validation[:type] == :presence
      # Check children for a node with tag_name == attribute
      target_tag = validation[:attribute]
      found = @children.any? { |c| c.tag_name == target_tag }
      unless found
        raise AdfBuilder::Error, "Missing required Element: #{target_tag} in #{tag_name || self.class.name}"
      end
    end
  end

  # Recursively validate children
  @children.each(&:validate!)
end