Tuesday, September 13, 2011

Validating integer ranges in Rails

Taking my friend Matt's advice, I redid the validation and logic for my models in Manticore tonight. Didn't take too long and the new way makes more sense than before.

Here's what I had before:

class Initiative < ActiveRecord::Base   belongs_to :character   validates_presence_of :dex, :misc, :speed   validates_numericality_of :dex, :misc, :speed   def total     dex + misc   end end

And I've changed it to:

class Initiative < ActiveRecord::Base   belongs_to :character   validates_numericality_of :dex, :misc, :speed   validates_inclusion_of :dex, :misc, :in => -10..20, :message => "must be between -10 and 20."
  validates_inclusion_of :speed, :in => 20..200, :message => "must be at least 20."

  def total
    dex.to_i + misc.to_i

A pretty minor change, but here's what this is doing. First off, there's no need to validate both for presence_of and numericality_of an object. Validating numericality_of an object will in effect also validate_presence_of that object, since it must be an integer to pass validation.

Secondly, I've added a validates_inclusion_of to ensure that all integers make sense within Dungeons and Dragons rules. For example, :speed refers to how many feet a character can move per round. The vast majority of characters are going to be either 20 or 30, so I set 20 as the base. However, there are ways to get higher speeds, through class benefits, spells, magical items and so on, so I set the upper limit at 200. I don't use this object to make any calculations, but it's nice to have information that makes sense for a Dungeons and Dragons character, since Manticore is a Dungeons and Dragons character database program.

Lastly (and I think this might be a bit of overkill) I added .to_i to my logic, which will ensure all objects are integers before attempting to perform calculations. Am I right about this one? It also sets nil to 0, right? Pretty handy, considering I was wanting a way to set nil to 0 a while back.

I started to bang out a question, but as I was writing I got an idea of how to do what I want to do, so I'll give it a shot before asking for help

No comments:

Post a Comment