Archive for March, 2007

Validating Positive With Infinity

Sunday, March 18th, 2007

Ruby has a nifty feature to be able to use a special constant that represents infinity, accessible as follows:

irb(main):001:0> 1.0/0
=> Infinity

Recently, I needed to validate that a field in my Rails model would be positive. While there are countless ways to do this, I was very happy to find a fun and practical use for infinity.

validates_inclusion_of :some_attribute, :within => 1..1.0/0, :allow_nil => true, :message => 'should be positive'

The attribute is validated to be within positive one (inclusive) and positive infinity (technically exclusive.) This is done with Rails’ validates_inclusion_of for numeric data, Ruby’s range operator .., and the infinity constant 1.0/0.

Huzzah!