Sha256: 9fe573db66f2f1695e7dc32f512c3f8cf041e1e485c4f0bf88bcdf20d8c84c3c

Contents?: true

Size: 677 Bytes

Versions: 41

Compression:

Stored size: 677 Bytes

Contents

# frozen_string_literal: true

class MiniDefender::Rules::Luhn < MiniDefender::Rule
  def self.signature
    'luhn'
  end

  def self.valid_luhn?(value)
    value = value.to_s
    return false unless value.match?(/\A\d+\z/)

    double_sum = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]
    sum = 0

    value.to_i.digits.each_with_index do |digit, index|
      sum += index.even? ? digit : double_sum[digit]
    end

    sum % 10 === 0
  end

  def coerce(value)
    value.to_s
  end

  def passes?(attribute, value, validator)
    value.is_a?(String) && self.class.valid_luhn?(value)
  end

  def message(attribute, value, validator)
    'The value must be a valid Luhn string.'
  end
end

Version data entries

41 entries across 41 versions & 1 rubygems

Version Path
mini_defender-0.6.8 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.7 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.5 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.4 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.3 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.2 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.1 lib/mini_defender/rules/luhn.rb
mini_defender-0.6.0 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.8 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.7 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.6 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.5 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.4 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.3 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.2 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.1 lib/mini_defender/rules/luhn.rb
mini_defender-0.5.0 lib/mini_defender/rules/luhn.rb
mini_defender-0.4.1 lib/mini_defender/rules/luhn.rb
mini_defender-0.4.0 lib/mini_defender/rules/luhn.rb
mini_defender-0.3.14 lib/mini_defender/rules/luhn.rb