Module: PhcStringFormat::Validations::ClassMethods

Defined in:
lib/phc_string_format/validations.rb

Overview

class methods

Instance Method Summary collapse

Instance Method Details

#do_validate(that) ⇒ Object



28
29
30
31
# File 'lib/phc_string_format/validations.rb', line 28

def do_validate(that)
  @validators.each { |validator| validator.call(that) }
  that
end

#validate(name, **options) ⇒ Object



23
24
25
26
# File 'lib/phc_string_format/validations.rb', line 23

def validate(name, **options)
  @validators ||= []
  @validators << ->(object) { raise ArgumentError, options[:message] unless object.send(name) }
end

#validates(name, **options) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/phc_string_format/validations.rb', line 13

def validates(name, **options)
  @validators ||= []
  @validators << lambda { |object|
    value = object.instance_variable_get(name)
    return if options[:allow_nil] && !value
    regex = options.dig(:format, :with)
    raise ArgumentError, options[:message] unless !regex || value =~ regex
  }
end