Skip to content

Instantly share code, notes, and snippets.

@fernandes
Created March 11, 2019 17:14
Show Gist options
  • Save fernandes/80f5077c5509a49263d3a8f021560f9b to your computer and use it in GitHub Desktop.
Save fernandes/80f5077c5509a49263d3a8f021560f9b to your computer and use it in GitHub Desktop.
validator contract
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
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