Created
March 11, 2019 17:14
-
-
Save fernandes/80f5077c5509a49263d3a8f021560f9b to your computer and use it in GitHub Desktop.
validator contract
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Validator | |
include Contracts::Core | |
class InvalidTypeError < StandardError; end | |
Contract Contracts::Num => Contracts::Num | |
def self.decimal(value) | |
raise InvalidTypeError.new("Not allowed nil type") if value.nil? | |
return value if value.is_a?(Integer) | |
return value if value.is_a?(BigDecimal) | |
value | |
end | |
Contract ::String => Contracts::Num | |
def self.decimal(value) | |
return BigDecimal.new(value) | |
rescue ArgumentError => e | |
raise InvalidTypeError.new("Invalid string for decimal conversion") | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'test_helper' | |
class ValidatorTest < ActiveSupport::TestCase | |
test ".decimal validate decimal" do | |
assert_equal 1.7.to_d, Validator.decimal(1.7) | |
end | |
test ".decimal validate integer" do | |
assert_equal 1.to_d, Validator.decimal(1) | |
end | |
test ".decimal validate valid string" do | |
assert_equal 1.7.to_d, Validator.decimal("1.7") | |
end | |
test ".decimal exception for nil" do | |
err = assert_raises(ContractError) { Validator.decimal(nil) } | |
assert_match(/Expected: String,\n\s+Actual: nil\n/, err.message) | |
end | |
test ".decimal exception invalid string" do | |
err = assert_raises(Validator::InvalidTypeError) { Validator.decimal("a") } | |
assert_match(/Invalid string for decimal conversion/, err.message) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment