Class: IuguLogger::Schema::Validator
- Inherits:
-
Object
- Object
- IuguLogger::Schema::Validator
- Defined in:
- lib/iugu_logger/schema.rb
Instance Attribute Summary collapse
-
#mode ⇒ Object
readonly
Returns the value of attribute mode.
Instance Method Summary collapse
- #event_definition(action) ⇒ Object
-
#initialize(registry: nil, mode: DEFAULT_MODE) ⇒ Validator
constructor
A new instance of Validator.
- #known?(action) ⇒ Boolean
-
#suggestions_for(action) ⇒ Object
Levenshtein-based typo suggestions for unknown actions.
- #validate(action, payload) ⇒ Object
Constructor Details
#initialize(registry: nil, mode: DEFAULT_MODE) ⇒ Validator
Returns a new instance of Validator.
60 61 62 63 64 65 66 67 68 |
# File 'lib/iugu_logger/schema.rb', line 60 def initialize(registry: nil, mode: DEFAULT_MODE) unless VALID_MODES.include?(mode) raise ConfigurationError, "unknown event_action_validator mode: #{mode.inspect} (expected :strict, :warn, :off)" end @mode = mode @registry = normalize_registry(registry) end |
Instance Attribute Details
#mode ⇒ Object (readonly)
Returns the value of attribute mode.
58 59 60 |
# File 'lib/iugu_logger/schema.rb', line 58 def mode @mode end |
Instance Method Details
#event_definition(action) ⇒ Object
76 77 78 79 80 |
# File 'lib/iugu_logger/schema.rb', line 76 def event_definition(action) return nil if @registry.nil? @registry['events'][action.to_s] end |
#known?(action) ⇒ Boolean
70 71 72 73 74 |
# File 'lib/iugu_logger/schema.rb', line 70 def known?(action) return false if @registry.nil? @registry['events'].key?(action.to_s) end |
#suggestions_for(action) ⇒ Object
Levenshtein-based typo suggestions for unknown actions.
95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/iugu_logger/schema.rb', line 95 def suggestions_for(action) return [] if @registry.nil? target = action.to_s @registry['events'].keys .map { |a| [a, levenshtein(target, a)] } .reject { |(_, dist)| dist > SUGGESTION_MAX_DISTANCE } .sort_by(&:last) .first(SUGGESTION_LIMIT) .map(&:first) end |
#validate(action, payload) ⇒ Object
82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/iugu_logger/schema.rb', line 82 def validate(action, payload) return Result.new(status: :off) if @mode == OFF || @registry.nil? defn = event_definition(action) return Result.new(status: :unknown_action, suggestions: suggestions_for(action)) if defn.nil? missing = (defn['required_fields'] || []).reject { |path| field_present?(payload, path) } return Result.new(status: :missing_required, missing_fields: missing) unless missing.empty? Result.new(status: :ok, event_kind: defn['event_kind']) end |