Skip to content

Commit

Permalink
Add ActiveModel’s Luhn Algorithm validator
Browse files Browse the repository at this point in the history
  • Loading branch information
Kimmie committed Jul 7, 2019
1 parent 9f3bea5 commit 8bba7db
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions lib/luhn_algorithm.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require 'luhn_algorithm/version'
require 'luhn_algorithm/validator'

module LuhnAlgorithm
NUMBER_ONLY = /^\d+$/
Expand Down
19 changes: 19 additions & 0 deletions lib/luhn_algorithm/validator.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
require 'active_model'

module ActiveModel
module Validations
# active model validator for Luhn Algorithm
class LuhnAlgorithmValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
return if LuhnAlgorithm.valid?(value)
record.errors.add(attribute, options[:message] || :invalid)
end
end

module HelperMethods
def validates_luhn_algorithm_of(*attr_names)
validates_with LuhnAlgorithmValidator, _merge_attributes(attr_names)
end
end
end
end
3 changes: 2 additions & 1 deletion luhn_algorithm.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@ Gem::Specification.new do |spec|
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

spec.add_dependency "activemodel", ">= 3", "<= 6"
spec.add_runtime_dependency "activemodel", ">= 3", "<= 6"

spec.add_development_dependency "bundler", "~> 1.17"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_development_dependency "byebug"
end
20 changes: 20 additions & 0 deletions spec/luhn_algorithm/validator_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class SampleModel
include ::ActiveModel::Validations

attr_accessor :number1, :number2

validates_luhn_algorithm_of :number1
validates :number2, luhn_algorithm: true
end

RSpec.describe ActiveModel::Validations::LuhnAlgorithmValidator do
let(:model) { SampleModel.new }

context 'validates attributes based on luhn_algorithm' do
it 'calls LuhnAlgorithm.valid?' do
model.number1 = 6_011_111_111_111_118
model.number2 = '4111111111111111'
expect(LuhnAlgorithm).to receive(:valid?).and_call_original.twice
end
end
end

0 comments on commit 8bba7db

Please sign in to comment.