Class: FlexValidations::Predicate

Inherits:
Object
  • Object
show all
Includes:
Validation
Defined in:
lib/flex_validations/predicate.rb

Overview

Call predicate on object

Examples:

odd = FlexValidations::Predicate.new(:odd?)
odd.validate(1).success? #=> true

Description

> puts odd
value.odd? should succeed

Description of success result

> puts odd.validate(1)
1.odd? succeed

Description of fail result

> puts odd.validate(2)
2.odd? failed

Description when value doesn’t respond to method

> puts odd.validate("foo")
"foo" of String isn't respond to method odd?

Defined Under Namespace

Classes: FailedMessage, NotRespondMessage, SuccessMessage

Instance Method Summary collapse

Methods included from Validation

#===, #to_proc

Constructor Details

#initialize(method, *args) ⇒ Predicate

Returns a new instance of Predicate.



28
29
30
31
# File 'lib/flex_validations/predicate.rb', line 28

def initialize(method, *args)
  @method = method
  @args = args
end

Instance Method Details

#to_sString

Returns:

  • (String)


47
48
49
50
51
# File 'lib/flex_validations/predicate.rb', line 47

def to_s
  args = "(#{@args.map(&:inspect).join(', ')})" if @args.length > 0

  "value.#{@method}#{args} should succeed"
end

#validate(value) ⇒ FlexValidations::Result

Parameters:

  • value (Object)

    Value to be validated

Returns:



36
37
38
39
40
41
42
43
44
# File 'lib/flex_validations/predicate.rb', line 36

def validate(value)
  return not_respond(value) unless value.respond_to?(@method, false)

  ret = value.public_send(@method, *@args)

  return failed(value, ret) unless ret

  success(value, ret)
end