Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Enumify adds an enum command to all ActiveRecord models which enables you to work with string attributes as if they were enums
tree: 22f37d9a03

Fetching latest commit…

Cannot retrieve the latest commit at this time

Failed to load latest commit information.
lib
spec
.gitignore
.rspec
Gemfile
Rakefile
Readme.md
enumify.gemspec

Readme.md

Enumify

This gem adds an enum command to all ActiveRecord models which enables you to work with string attributes as if they were enums

Installing

Just add the enumify gem to your GemFile

How to use

On a model that you have Lets say Event you want to add a status field it just accepts a call to the enum function with the field name and available values as symbols in an array class Event < ActiveRecord::Base enum :status, [:available, :canceled, :completed] 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

Callbacks

Another cool feature of enumify is the option to add a callback function that will be called each time the value of the field changes This is cool to do stuff like log stuff or create behaviour on state changes

All you need to do is add a x_changed method in your class and the enumify will call it

class Event < ActiveRecord::Base
    enum :status, [:available, :canceled, :completed]

    def status_changed(old, new)
        puts "status changed from #{old} to #{new}"
    end
end

Copyright (c) 2011 Yonatan Bergman, released under the MIT license

Something went wrong with that request. Please try again.