Class: DailyAffirmation::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/daily_affirmation/validator.rb

Instance Method Summary collapse

Constructor Details

#initialize(object, attribute, opts = {}) ⇒ self

Initializes a new validator to validate the given object/attribute combination.

Parameters:

  • object (Object)

    the object to validate.

  • attribute (Symbol)

    the attribute to validate. The object must ‘respond_to?` a method with the name `attribute` with no arguments.

  • opts (Hash) (defaults to: {})

    any special options related to the affirmation.

Options Hash (opts):

  • :if (Proc)

    evaluated before affirmation to ensure we should run validation.

  • :allow_nil (true, false)

    determines if we skip validation of ‘nil` valued attributes.



16
17
18
19
20
21
# File 'lib/daily_affirmation/validator.rb', line 16

def initialize(object, attribute, opts = {})
  self.object = object
  self.attribute = attribute
  self.value = object.send(attribute)
  self.opts = opts
end

Instance Method Details

#affirmArray(Boolean, [nil, String])

Returns an array of length 2 telling you if the object passes this affirmation along with an error message if it doesn’t.

Returns:

  • (Array(Boolean, [nil, String]))

    Array of length 2 containing validation results.



28
29
30
# File 'lib/daily_affirmation/validator.rb', line 28

def affirm
  @affirm ||= [valid?, valid? ? nil : error_message]
end

#error_messageString

Note:

This method will always return the associated error message, even

Returns the error message related to this validation.

if the object passes validation.

Returns:

  • (String)


48
49
50
# File 'lib/daily_affirmation/validator.rb', line 48

def error_message
  i18n_error_message(:none)
end

#valid?true, false

Note:

Subclasses of DailyAffirmation::Validator must implement this

Tells you if the object is valid based on this affirmation.

method.

Returns:

  • (true, false)

Raises:

  • (StandardError)


38
39
40
# File 'lib/daily_affirmation/validator.rb', line 38

def valid?
  raise StandardError, "must implement #valid?"
end