SIOC Post profile for "larrytheliquid" A SIOC profile describes the structure and contents of a weblog in a machine readable form. For more information please refer to http://sioc-project.org/. Validating Positive With Infinity 61e0bfc1e407d0a6c3aea5498450906712b7aa84 2007-03-19T01:28:06Z 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! 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!

]]>