28th August 2013

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 ARLikeAPI
2 def self.find_by_email(email)
3 SomeApi.where("email", email)
4 end
Language ruby

Say 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 ARLikeAPI
2 include Expects
4 def self.find_by_email(email)
5 expects email, String
7 SomeApi.where("email", email)
8 end
Language 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 (email) and the expected input (String)

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]
Language 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, /^.*@.*$/
Language 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.