Class: MiniDefender::Rules::MinDigits

Inherits:
MiniDefender::Rule show all
Defined in:
lib/mini_defender/rules/min_digits.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from MiniDefender::Rule

#active?, available?, #bails?, #coerce, #default_value, #defaults?, #error_message, #excluded?, #force_coerce?, #implicit?, #priority, #stops?, #with_message

Constructor Details

#initialize(limit) ⇒ MinDigits

Returns a new instance of MinDigits.

Raises:

  • (ArgumentError)


4
5
6
7
8
# File 'lib/mini_defender/rules/min_digits.rb', line 4

def initialize(limit)
  raise ArgumentError, 'Limit must be a string.' unless limit.is_a?(Integer)

  @limit = limit
end

Class Method Details

.make(args) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
# File 'lib/mini_defender/rules/min_digits.rb', line 14

def self.make(args)
  raise ArgumentError, 'Expected at least one argument for min_digits.' unless args.length == 1

  new(args[0].to_i)
end

.signatureObject



10
11
12
# File 'lib/mini_defender/rules/min_digits.rb', line 10

def self.signature
  'min_digits'
end

Instance Method Details

#message(attribute, value, validator) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/mini_defender/rules/min_digits.rb', line 25

def message(attribute, value, validator)
  if @integers
    'The field should only contain digits.'
  else
    "The field should have at least #{@limit} digits."
  end
end

#passes?(attribute, value, validator) ⇒ Boolean

Returns:



20
21
22
23
# File 'lib/mini_defender/rules/min_digits.rb', line 20

def passes?(attribute, value, validator)
  @integers = valid = value.is_a?(Integer) || value.is_a?(String) && value.match?(/^\d+$/)
  valid && value.to_s.length >= @limit
end