Giter Club home page Giter Club logo

enumify's Introduction

Enumify Build Status

Enumify 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

gem 'enumify'

How to use

Just call the enumify 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
    enumify :status, [:available, :canceled, :completed]
end

Usage

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
    enumify :status, [:available, :canceled, :completed], :allow_nil => true
end

Event.create! # Is valid and does not throw an exception.

:prefix

By default all enum values are available as scopes, bang and query methods based on the value. You can add a prefix for the enum values in order to differentiate different enums on the same object.

class Event < ActiveRecord::Base
    enumify :status, [:available, :canceled, :completed], :prefix => true
    enumify :subtype, [:company, :personal], :prefix => 'type'
end

event.available?            # Not available anymore
event.status_available?     # when prefix true
event.type_company?         # you can set a specific name for your prefix

:constant

By default, a constant is created on the class, containing the enum values. You can remove the constant by passing a falsy value (i.e: nil, false) or rename it by passing a symbol or a string with a different name.

class Event < ActiveRecord::Base
    enumify :status, [:available, :canceled, :completed]
    enumify :without_const, [:foo, :bar], :constant => false
    enumify :custom_name, [:a, :b, :c], :constant => :special_name
end

event::STATUSES             # returns [:available, :canceled, :completed]
event::WITHOUT_CONST        # raises NameError
event::SPECIAL_NAME         # returns [:a, :b, :c]. Note the name was not pluralized.
event::CUSTOM_NAME          # raises NameError

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
    enumify :status, [:available, :canceled, :completed]

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

Scopes

One last thing that the enumify 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

In addition you can also use a negation scope to retrieve all the records that are not set to the given value. For example to count all the events that are not canceled you can run

Event.not_canceled.count

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

enumify's People

Contributors

gerev avatar ifeins avatar petergoldstein avatar yonbergman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

enumify's Issues

how to override Rails 4's native enum with enumify's?

after upgrading to rails 4 i prefer to keep using enumify. how would you do that?

The reason is because Rails 4's enum are based on integers and persist the ordinal number of the enum value, unlike enumify which persists the string value. so its a hassle to update the models.

Does not work in Rails 4.0

class Partners::Contact < ActiveRecord::Base
enum :status, [:pending, :active]
end

rails s
$ h.contacts.first.status
NoMethodError: undefined method empty?' for 1:Fixnum from /Users/volte/a2/vendor/bundle/gems/enumify-0.0.5/lib/enumify/model.rb:11:inblock in enum'
from (irb):6

allow_nil doesn't allow setting a field to nil

If I have an enum with :allow_nil => true, then it can be read from the db as nil, but I cannot set the field to nil using update or simple assignment (=).

If I try to do that I get: NoMethodError: undefined method to_sym' for nil:NilClass`

Not an issue, just questions about getting index of values

This gem is exactly what I've been looking for. Sorry to post this in issues, but heck if I can find a better place to ask questions.

What's the best way to get the index of the value in an enumify field? In my projects, I frequently do things like:

if status_index > 2; something; end

where status_index is the value index according to a mysql query on the enum field

select status+0 status_index from orders...

I also do things like

self.status = 2
save

What about ActiveRecord queries with an enumify field in the :conditions?

:conditions=>{:status=>"submitted"}

or

:conditions=>"orders.status > 2"

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.