Skip to content

Instantly share code, notes, and snippets.

@petyosi
Created September 1, 2010 20:30
Show Gist options
  • Save petyosi/561303 to your computer and use it in GitHub Desktop.
Save petyosi/561303 to your computer and use it in GitHub Desktop.

enumed

Idea on usage

class User < ActiveRecord::Base
  enum :state, %w(new registered confirmed banned), :default => :new do
    action :register do |user| 
      change_to :registered  
    end

    action :next do |user|
      change! :from => :new, :to => :registered
      change! :from => :registered, :to => :confirmed
    end

  end

end

class User::State < Enumed::State
  states %w(new registered confirmed banned)
  default :new

  action :next do |user|
    ...
  end

  def some_method
    # record is returning user
  end

end

class User < ActiveRecord::Base
  enum :state, :class => User::State
end


user = User.new
user.state.to_s # new
user.register! # user.reload.state is now registered, record is saved. 
user.state.change_to :registered
user.state.change_to :registered
User.state.states # %w(new registered confirmed banned)
@skanev
Copy link

skanev commented Sep 1, 2010

What's the context of this? It's slightly reminiscent of the State design pattern

@petyosi
Copy link
Author

petyosi commented Sep 2, 2010

Glad I got your attention.

This is a wishful thinking of something I would like to write. A cleaner, lest awkward implementation of the state pattern;

  • supporting multiple columns
  • not polluting the model with additional methods
  • (optional) separate class definition
  • Free -named- scopes

I am aware of (and hating) aasm, and I am currently using enumerated attribute, but it is… clumsy.

However, I don't plan immediate migration to Rails 3, but writing a plugin for Rails 2 does not make any sense. So - consider the above a draft README.md for the gem I want to write one day :).

Comments, ideas, resources welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment