- Author
-
Jared Kuolt (me@superjared.com)
- Copyright
-
Copyright © 2009 Jared Kuolt
- License
-
MIT License
Enforce return values by type and with user-defined guards.
sudo gem install pedant
In defining your classes, you can define allowable return values for your methods by type and with user-defined guards. See how the returns
method is used in the following class definition:
require 'rubygems' require 'pedant' class Foo include Pedant::Returns def integer_only 100 end # We define that the method may *only* return an Integer returns(:integer_only, Integer) def integer_or_nil nil end # This method can return either an Integer or NilClass returns(:integer_or_nil, Integer, NilClass) def small_integer 10 end # This method will raise unless it returns an Integer less than 127 returns(:small_integer, Integer) {|return_value| return_value < 127 } # We can do the same for class methods class << self def string_or_symbol :foo end returns(:string_or_symbol, String, Symbol) end end
If the type doesn’t match, Pedant::TypeError
will be raised. If the user guard does not evaluate to true, Pedant::GuardError
will be raised.
Because this code can be destructive, especially in production, it is advised to use Pedant in development and staging environments. To do this, include Pedant::Dummy
instead of Pedant::Returns
. Pedant::Dummy
defines the returns method to do nothing and will no longer get in the way:
if environment == :production include Pedant::Dummy else include Pedant::Returns end