Class: LogSnag::Validator
- Inherits:
-
Object
- Object
- LogSnag::Validator
- Defined in:
- lib/logsnag/validator.rb
Overview
Provides helpers for validating data.
Class Method Summary collapse
-
.compact_hash!(hash, path) ⇒ Hash
Removes any nil values from the hash at the specified path.
-
.validate_allowed_keys(allowed_keys, data) ⇒ void
Ensure that the ‘data` hash only contains keys in the `allowed_keys` array.
-
.validate_hash(hash) ⇒ void
Ensures that the keys and values in the hash conform to the specified rules.
-
.validate_required_keys(required_keys, data) ⇒ void
Ensure that the ‘required_keys` are present in the `data` hash.
Class Method Details
.compact_hash!(hash, path) ⇒ Hash
Removes any nil values from the hash at the specified path.
30 31 32 33 |
# File 'lib/logsnag/validator.rb', line 30 def self.compact_hash!(hash, path) hash[path] = hash[path].compact if hash[path] hash end |
.validate_allowed_keys(allowed_keys, data) ⇒ void
This method returns an undefined value.
Ensure that the ‘data` hash only contains keys in the `allowed_keys` array.
21 22 23 24 |
# File 'lib/logsnag/validator.rb', line 21 def self.validate_allowed_keys(allowed_keys, data) invalid_keys = data.keys - allowed_keys raise ArgumentError, "Found invalid keys: #{invalid_keys}" unless invalid_keys.empty? end |
.validate_hash(hash) ⇒ void
This method returns an undefined value.
Ensures that the keys and values in the hash conform to the specified rules.
39 40 41 42 43 44 45 46 47 |
# File 'lib/logsnag/validator.rb', line 39 def self.validate_hash(hash) return unless hash hash.each do |key, value| raise ArgumentError, "Invalid key: '#{key}'. Keys must be lowercase and may include dashes." unless key.to_s.match?(/\A[a-z]+(-[a-z]+)*\z/) raise ArgumentError, "Invalid value for '#{key}': '#{value}'. Values must be a string, boolean, or number." unless [String, TrueClass, FalseClass, Numeric].any? { |type| value.is_a?(type) } end end |
.validate_required_keys(required_keys, data) ⇒ void
This method returns an undefined value.
Ensure that the ‘required_keys` are present in the `data` hash.
11 12 13 14 |
# File 'lib/logsnag/validator.rb', line 11 def self.validate_required_keys(required_keys, data) missing_keys = required_keys - data.keys raise ArgumentError, "Missing required keys: #{missing_keys}" unless missing_keys.empty? end |