Skip to content

Instantly share code, notes, and snippets.

@wangjohn
Last active December 15, 2015 18:29
Show Gist options
  • Select an option

  • Save wangjohn/5304371 to your computer and use it in GitHub Desktop.

Select an option

Save wangjohn/5304371 to your computer and use it in GitHub Desktop.
Static-Like Checking in Rails Tests

My idea is to create something in rails where you can do checking on your rails app which is similar to statically-typed languages. When you define a method, you can specify asserts on the inputs and outputs. Imagine that @return is the return value of the method, then you could write:

#
# assert ids.all? do { |id| id.kind_of?(Integer) }
# assert @return.kind_of?(ActiveRecord)
# 
def find(*ids)
  ...
end

Then there will be a configuration option where you can specify config.static_type_checking = true which will turn on the assertion checking, and log any assertions that fail. Note that assertion failure will not cause the method to raise an error, though, so everything else will run just as if the assertions didn't exist. Later you can go ahead and check when the argument and return types don't match after the fact in the logs.

For performance (since you probably don't want to be calling this all the time in production) you can specify a probability config.static_type_checking_probability = 0.01 of actually doing a static-check on any given method call.

The method will only be called if static-typing has been defined in the comments.

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