Last active
October 11, 2019 10:48
-
-
Save nathan-appere/3ed13e25be7df00efcdabfd1f904fbdf to your computer and use it in GitHub Desktop.
Example of ruby contracts
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 RGB | |
# First step ----------------------------------------------------------------- | |
before ->(r:, g:, b:) { (0..255) === r && (0..255) === g && (0..255) === b } | |
after [ | |
->(result:) { result.is_a?(String) }, | |
->(result:) { result.start_with?('#') }, | |
->(result:) { result.length.in?([4, 7]) }, | |
] | |
def self.rgb_to_hex_1a(r:, g:, b:) | |
"+" << [r, g, b].map { |el| el.to_s(16) }.join | |
end | |
# Or | |
contracts_attributes = { | |
before: ->(r:, g:, b:) { (0..255) === r && (0..255) === g && (0..255) === b } | |
after: [ | |
->(result:) { result.is_a?(String) }, | |
->(result:) { result.start_with?('#') }, | |
->(result:) { result.length.in?([4, 7]) }, | |
], | |
} | |
contract contracts_attributes | |
def self.rgb_to_hex_1b(r:, g:, b:) | |
"+" << [r, g, b].map { |el| el.to_s(16) }.join | |
end | |
# Second step ---------------------------------------------------------------- | |
RgbType = Types::Int.values(0..255) | |
before { r: RgbType, g: RgbType, b: RgbType, } | |
after [ | |
Types::String, | |
->(result:) { result.start_with?('#') }, | |
->(result:) { result.length.in?([4, 7]) }, | |
] | |
def self.rgb_to_hex2(r:, g:, b:) | |
"+" << [r, g, b].map { |el| el.to_s(16) }.join | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment