Module: Rxhp::AttributeValidator

Included in:
CustomElement, HtmlElement
Defined in:
lib/rxhp/attribute_validator.rb

Overview

Provide support for limiting or requiring attributes.

Attributes can be:

Requiring an attribute automaticaly whitelists it.

To use:

Subclasses will automatically have validated attributes, and will copy the rules from their parent class. Additional attributes can be accepted or required in subclasses without affecting the parent class.

Defined Under Namespace

Modules: ClassMethods Classes: MissingRequiredAttributeError, UnacceptableAttributeError

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.match?(matcher, name, value) ⇒ Boolean

Returns:

  • (Boolean)

91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/rxhp/attribute_validator.rb', line 91

def self.match? matcher, name, value
  case matcher
  when Array
    matcher.any? { |x| match? x, name, value }
  when Hash
    matcher.any? do |name_matcher, value_matcher|
      name_match = match_value?(name_matcher, name_from_symbol(name))
      if name_match
        match_value?(value_matcher, value)
      else
        false
      end
    end
  else
    match_value? matcher, name
  end
end

Instance Method Details

#valid_attributes?Boolean

Whether or not the attributes are acceptable.

If you need more details than just “it's invalid”, call #validate_attributes! instead and examine the exceptions it raises.

Returns:

  • (Boolean)

    whether or not the attributes are all whitelisted, and all required attributes are provided.


47
48
49
50
51
52
53
54
# File 'lib/rxhp/attribute_validator.rb', line 47

def valid_attributes?
  begin
    self.validate_attributes!
    true
  rescue ValidationError
    false
  end
end

#validate_attributes!true

Check if attributes are valid, and raise an exception if they're not.

Returns:

  • (true)

    if the attribute are all valid, and all required attributes are provided.

Raises:


64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rxhp/attribute_validator.rb', line 64

def validate_attributes!  # Check for required attributes

  self.class.required_attributes.each do |matcher|
    matched = self.attributes.any? do |key, value|
      key = key.to_s
      Rxhp::AttributeValidator.match? matcher, key, value
    end
    if !matched
      raise MissingRequiredAttributeError.new(self, matcher)
    end
  end

  # Check other attributes are acceptable
  return true if self.attributes.empty?
  self.attributes.each do |key, value|
    key = key.to_s
    matched = self.class.acceptable_attributes.any? do |matcher|
      Rxhp::AttributeValidator.match? matcher, key, value
    end

    if !matched
      raise UnacceptableAttributeError.new(self, key, value)
    end
  end
  true
end