I want to use enums with MongoMapper and rails 4. I know there are gems out there (enumerize) which adds this behaviour but it seems like a lot to add for a small feature.
What is the easiest way of creating an enum for an ActiveModel class?
I want to use enums with MongoMapper and rails 4. I know there are gems out there (enumerize) which adds this behaviour but it seems like a lot to add for a small feature.
What is the easiest way of creating an enum for an ActiveModel class?
Using getters, setters and an array of constants this can be quickly achieved:
class Subscription
include MongoMapper::Document
...
key :status, Integer
STATE = [:queued, :submitted, :processing, :payment_received, :fully_paid, :error]
def status=(str)
@status = STATE.index(str)
end
def status
STATE[@status]
end
end
You could even add checks for common queries, eg the error state may need to be checked more often than others and you can skip the symbol > integer conversion:
def errors?
@status == 5
end