Class: Knight::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/knight/result.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(resource, rules) ⇒ Result

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initialize a validation result

Parameters:

  • resource (Object)
  • rules (Set(Rule))


29
30
31
32
# File 'lib/knight/result.rb', line 29

def initialize(resource, rules)
  @resource = resource
  @rules    = rules
end

Instance Attribute Details

#resourceObject (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the resource

Returns:

  • (Object)


12
13
14
# File 'lib/knight/result.rb', line 12

def resource
  @resource
end

#rulesSet(Rule) (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return the rule set

Returns:



19
20
21
# File 'lib/knight/result.rb', line 19

def rules
  @rules
end

Instance Method Details

#errorsSet(Error)

Return the result errors

Examples:

validator = Validator.new(Rule::Presence.new(:username))
user = User.new(username: 'john')

result = validator.run(resource)
result.errors

Returns:



63
64
65
66
67
68
# File 'lib/knight/result.rb', line 63

def errors
  rules.each_with_object(Set.new) do |rule, errors|
    error = attribute_check(rule)
    errors << error if error
  end
end

#on(attribute) ⇒ Set(Error)

Return the errors for specific attribute

Examples:

validator = Validator.new(Rule::Presence.new(:username))
user = User.new(username: 'john')

result = validator.run(resource)
result.on(:username)

Returns:



82
83
84
# File 'lib/knight/result.rb', line 82

def on(attribute)
  errors.select { |error| error.attribute_name == attribute }.to_set
end

#valid?true, false

Check the result valid or not

Examples:

validator = Validator.new(Rule::Presence.new(:username))
user = User.new(username: 'john')

result = validator.run(resource)
result.valid?

Returns:

  • (true)

    if valid

  • (false)

    otherwise



47
48
49
# File 'lib/knight/result.rb', line 47

def valid?
  errors.empty?
end