Class: Cure::Validator::Candidate

Inherits:
Object
  • Object
show all
Includes:
Helpers::ObjectHelpers, Log
Defined in:
lib/cure/validator/candidate.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  fail_on_error: false
}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Log

#log_debug, #log_error, #log_info, #log_trace, #log_warn

Methods included from Helpers::ObjectHelpers

#class_exists?

Constructor Details

#initialize(column, named_range, options = {}) ⇒ Candidate

Returns a new instance of Candidate.



29
30
31
32
33
34
# File 'lib/cure/validator/candidate.rb', line 29

def initialize(column, named_range, options={})
  @column = column
  @named_range = named_range || "_default"
  @options = DEFAULT_OPTIONS.merge(options)
  @rules = []
end

Instance Attribute Details

#columnString (readonly)

Lookup column name for CSV.

Returns:



19
20
21
# File 'lib/cure/validator/candidate.rb', line 19

def column
  @column
end

#named_rangeString (readonly)

Named range that column exists in

Returns:



15
16
17
# File 'lib/cure/validator/candidate.rb', line 15

def named_range
  @named_range
end

#rulesObject (readonly)

# What sort of data needs to be generated. # @return [Array<Cure::Validator::BaseRule>]



23
24
25
# File 'lib/cure/validator/candidate.rb', line 23

def rules
  @rules
end

Instance Method Details

#perform(value) ⇒ Object



36
37
38
39
40
41
42
43
44
# File 'lib/cure/validator/candidate.rb', line 36

def perform(value)
  result = @rules.filter_map do |rule|
    rule.process(value) ? nil : "#{rule} failed -> [#{@column}][#{value}]"
  end

  raise "Validation failed:\n#{result.join("\n")}" if @options[:fail_on_error] && !result.empty?

  result
end

#with_rule(method_name, options = {}) ⇒ Object



46
47
48
49
50
51
# File 'lib/cure/validator/candidate.rb', line 46

def with_rule(method_name, options={})
  klass_name = "Cure::Validator::#{method_name.to_s.split("_").map(&:capitalize).join}Rule"
  raise "#{method_name} is not valid" unless class_exists?(klass_name)

  @rules << Kernel.const_get(klass_name).new(@named_range, @column, options)
end