Expects is lightweight DSL for defining what you expect a method to receive as input.
I’d expect this gem to be used more as a support gem, being a dependancy for other gems to use to make sure that what the end user/developer was passing met with requirements.
Expects is pretty simple to use, say you had this class
1class ARLikeAPI2 def self.find_by_email(email)3 SomeApi.where("email", email)4 end5endLanguage ruby
SomeApi.where raises an exception if email isn’t a string, you could call
email.to_s to convert email to a string, but what happens if email is some random class that can’t be converted? If you add expects to this class like this:
1class ARLikeAPI2 include Expects34 def self.find_by_email(email)5 expects email, String67 SomeApi.where("email", email)8 end9endLanguage ruby
Now a call to
ARLikeAPI.find_by_email that isn’t passed a string will raise
UnexpectedInput which contains a human readable message of the problem as aswell as the subject (
You can also pass an array of classes to allow multiple types e.g.
1def add(num1, num2)2 expects num1, [Fixnum, Float]3 expects num2, [Fixnum, Float]4endLanguage ruby
This would let a number of either Fixnum or Float through but raise an exception if anything else was passed.
There is an inverse method called
reject which as the name implies lets anything through except for the items in the list.
Expects can also be used to validate input for example
1def send_email(email)2 expects email, /^.*@.*$/3endLanguage ruby
This would raise an exception if the supplied string didn’t have an @ somewhere in the middle.
As I have said Expects main audience is Gem Developers who want to stop their code doing something damaging when the end user gives it an input that its not expecting.
All content is my own unless otherwise stated.
My content is licensed under the CC-BY-NC-SA 4.0 license