-
-
Save waterlink/0fbcfe53b0663b9b3f47 to your computer and use it in GitHub Desktop.
contracts.ruby :: Non-type checking example
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
# Classical defensive programming | |
def do_something_useful(active_user) | |
return unless active_user.last_action_date < 2.weeks.ago | |
# do something useful with active user | |
end | |
# ---- | |
# With contracts: | |
Contract ActiveUser => Any | |
def do_something_useful(active_user) | |
# do something useful with active user, but it is already a guarantee, that it is active, you don't need to guard against that | |
end | |
# Definition of ActiveUser contract (it is not a class of active_user) | |
class ActiveUser | |
def self.valid?(user) | |
active_user.last_action_date < 2.weeks.ago | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With contracts it will look very elegantly