Validating Positive With Infinity
March 18th, 2007Ruby 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!

December 25th, 2007 at 12:31 am
validates_numericality_of :some_attribute, :greater_than => 0, :allow_nil => true, :message => ’should be positive’
would work also. I really do like your use of Infinity though, very clever.