Mega Validations, State Machine, and Accounting Tests

One of my favorite things about Ruby on Rails is the amazing validation capabilities. So it should come as no surprise that I am leveraging them heavily in Regdel.

For example, I want to make sure that entries balance, but they can’t balance all the time - especially when they are works in progress, i.e. they are not posted. The model has a posted attribute, so I’m doing something like this:

validate :credits_and_debits_must_balance, :if => :posted?

The problem is that the posted attribute must be set before the validation is run. As such, I’m planning on changing the posted attribute to be a part of the state machine setup. I’ll have to create a posted? accessor to check the state, not a problem.

The issue with that is that I’m planning to use the state machine differently for different classes, and the entry model uses single table inheritance (STI). I wonder if its possible to have more than one status column for different states on different classes. Not sure if I want to do that though.

UPDATE: Whoa - looks like state_machine supports namespaces. AWESOME! So for the base Entry class:

  state_machine :initial => :draft do

    event :post do
      transition :draft => :posted
    end 

    event :reconcile do
      transition :posted => :reconciled
    end 

  end 

and for the Invoice class:

  state_machine :initial => :open, :namespace => :invoice_state do

    event :issue do
      transition :matched => :sent
    end 

    event :reconcile do
      transition :posted => :reconciled
    end 
  end 

After reviewing these factors, another great aspect of Rails comes to mind: the testing frameworks!

By Albert on August 9, 2011 4:34 PM

Categories