The Magic of Enums in Rails

Ruby on Rails has special under-the-hood magic that will patch four methods onto your models for each enum value you specify. That means if you specify an enum with 3 values, Rails gives you 12 magic methods associated with names based on these values.

Take the example above:

def Invoice < ActiveResource
  enum status: [:pending: 'pending', in_progress: 'in_progress', finished:   

Rails will put 4 methods for each enum:

IN this example invoice represents an instance of a since invoice and Invoice represents the Invoice class.

for our Invoice example…
Bang (!)Tells the object to become that status.invoice.pending! will tell the invoice to turn its status into pending
Interrogative (?)Asks the object if it is in that statusinvoice.pending? returns true if the invoice is in pending status; false if not
Scope (…)When used on the class, provides a scope that will get all of the object in this stateInvoice.pending will return a scope that can be used to find all of the pending invoices
Negative scope (not_*)Invoice.not_pending will return a scope that can be used to find all of the invoices not in pending status

Remember, the scopes are ActiveRecord chain-able scopes, so they can be used in conjunction with other valid scopes too. (Invoices.pending.not_paid for example).