Module: ErrorProne::Rule

Included in:
PresenceRule
Defined in:
lib/error_prone.rb

Overview

Mixed in to objects that can verify whether an Model is valid or not.

Examples:

class FakeRule

  include ErrorProne::Rule
  validates_as :not_nil

  def verify!
    !value.nil?
  end

  def message
    :field_nil
  end
end

Defined Under Namespace

Modules: ClassMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#fieldObject (readonly)

Returns the value of attribute field.



73
74
75
# File 'lib/error_prone.rb', line 73

def field
  @field
end

#objectObject (readonly)

Returns the value of attribute object.



73
74
75
# File 'lib/error_prone.rb', line 73

def object
  @object
end

#valueObject (readonly)

Returns the value of attribute value.



73
74
75
# File 'lib/error_prone.rb', line 73

def value
  @value
end

Class Method Details

.included(klazz) ⇒ Object



105
106
107
# File 'lib/error_prone.rb', line 105

def self.included(klazz)
  klazz.extend(ClassMethods)
end

Instance Method Details

#initialize(object, field, options = {}) ⇒ Object

Parameters:

  • object (Object)

    Object to verify conforms to a rule

  • field (Symbol)

    Field on the object that must conform to the rule

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

    often specific to the the Rule



77
78
79
80
81
# File 'lib/error_prone.rb', line 77

def initialize(object, field, options = {})
  @object = object
  @field = field
  @options = options
end

#messageSymbol

Message to add when validate! finds an error. Must override in implementing classes.

Returns:

  • (Symbol)


95
96
97
# File 'lib/error_prone.rb', line 95

def message
  raise "You must set a message for rules to work"
end

#validate!Boolean

Adds error to the object if verify! fails

Returns:

  • (Boolean)


85
86
87
88
89
90
# File 'lib/error_prone.rb', line 85

def validate!
  @value = object.send(field)
  return true if verify!
  object.add_error(field, message)
  false
end

#verify!Boolean

Verifies if the rule is followed. Must override in implementing classes.

Returns:

  • (Boolean)


101
102
103
# File 'lib/error_prone.rb', line 101

def verify!
  raise "You must provide a verify! method for rules to work. verify! should return a boolean"
end