Project

enumerate

0.0
No commit activity in last 3 years
No release in over 3 years
Enumerate adds an `enumerate` command to all ActiveRecord models, enabling you to work with string or integer columns as if they were enums. The following features are added to your model: Validation - ensures that the field only receives accepted values Predicate Methods - adds ? and ! functions for each enum value Scopes - you can easily query for values of the enum
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
 Dependencies

Development

>= 3.0.6, ~> 3.0
>= 0.3.8, ~> 0.3
>= 0.9.3, ~> 0.9
>= 2.3.0, ~> 2.3
>= 1.3.3, ~> 1.3
 Project Readme

Enumerate Build Status Gem Version Code Climate

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

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

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

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

# 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).

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

Event.canceled.count

Copyright (c) 2013 Dale Stevens, released under the MIT license