README.md
# Enumerate [![Build Status](https://secure.travis-ci.org/TwilightCoders/enumerate.png)](http://travis-ci.org/TwilightCoders/enumerate) [![Gem Version](https://badge.fury.io/rb/enumerate.png)](http://badge.fury.io/rb/enumerate) [![Code Climate](https://codeclimate.com/github/TwilightCoders/enumerate.png)](https://codeclimate.com/github/TwilightCoders/enumerate)
Enumerate adds an enum command to all ActiveRecord models which enables you to work with integer and string attributes as if they were enums
## Installing
Just add the enumerate gem to your GemFile
```ruby
gem 'enumerate'
```
## How to use
Just call the enum function in any ActiveRecord object, the function accepts the field name as the first variable and the possible values as an array
```ruby
class Event < ActiveRecord::Base
enum :status, [:available, :canceled, :completed]
end
```
If your status column is of type integer, Enumerate will assign the indices of the array as the values stored in the database.
:available will be 0
:canceled will be 1
:completed will be 2
If you wish to specify yourself, simply use a hash
```ruby
class Event < ActiveRecord::Base
enum :status, {:available => 0, :canceled => 2, :completed => 5}
end
```
After that you get several autogenerated commands to use with the enum
```ruby
# Access through field name
event.status # returns the enum's current value as a symbol
event.status = :canceled # sets the enum's value to canceled (can also get a string)
# Shorthand methods, access through the possible values
event.available? # returns true if enum's current status is available
event.canceled! # changes the enum's value to canceled
# Get all the possible values
Event::STATUSES # returns all available status of the enum
```
## Options
#### :allow_nil
By default the enum field does not support a nil value. In order to allow nil values add the `allow_nil` option (similar to the Rails validation option).
```ruby
class Event < ActiveRecord::Base
enum :status, [:available, :canceled, :completed], :allow_nil => true
end
Event.create! # Is valid and does not throw an exception.
```
## Scopes
One last thing that the enumerate gem does is created scope (formerly nested_scopes) so you can easly query by the enum
For example if you want to count all the events that are canceled you can just run
```ruby
Event.canceled.count
```
---
Copyright (c) 2013 Dale Stevens, released under the MIT license