Skip to content

Instantly share code, notes, and snippets.

@waterlink
Created March 10, 2015 23:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save waterlink/0fbcfe53b0663b9b3f47 to your computer and use it in GitHub Desktop.
Save waterlink/0fbcfe53b0663b9b3f47 to your computer and use it in GitHub Desktop.
contracts.ruby :: Non-type checking example
# 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
@waterlink
Copy link
Author

With contracts it will look very elegantly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment