ActsAsEnum

主要应用于有枚举类型属性的Model,这个插件会帮我们生成一些常用到的方法。

如:枚举数组常量,每个元素的常量和布尔方法,属性的名字,Named scope方法

Getting Started

In your Gemfile:

gem 'acts_as_enum'# Last officially released gem
# gem "acts_as_enum", :git => "git://github.com/liangwenke/acts_as_enum.git" # Track git repo

or, to install as a gem:

gem install acts_as_enum

or, to install as a plugin:

rails plugin install git://github.com/liangwenke/acts_as_enum.git

Usage

Default

class User < ActiveRecord::Base
  enum_attr :status, :in => %w(disable, enable)
end

Table column type as String

class User < ActiveRecord::Base
  acts_as_enum :status, :in => [ ['disable', '冻结'], ['enable', '激活'] ]
end
Or
class User < ActiveRecord::Base
  acts_as_enum :status, :in => { 'disable' => '冻结', 'enable' => '激活' }
end
class User < ActiveRecord::Base
  enum_attr :status, :in => { 'disable' => '冻结', 'enable' => '激活' }
end

Table column type as Integer

class User < ActiveRecord::Base
  acts_as_enum :status, :in => [ ['disable', 0, '冻结'], ['enable', 1, '激活'] ]
end

Table column type as String and Number

class User < ActiveRecord::Base
  acts_as_enum :status, :in => [ ['disable', '0', '冻结'], ['enable', '1', '激活'] ]
end

Table column type as Boolean

class User < ActiveRecord::Base
  acts_as_enum :status, :in => [ ['disable', false, '冻结'], ['enable', true, '激活'] ]
end

Also can usage alias enum_attr

enum_attr :status, :in => [ ['disable', '冻结'], ['enable', '激活'] ]
enum_attr :status, :in => [ ['disable', 0, '冻结'], ['enable', 1, '激活'] ]

Will generate bellow:

Constants: User::STATUSES, User::DISABLE, User::ENABLE
Named scopes: User.enable, User.disable
Class methods: User.status_options, User.status_options_i18n
Instance methods: user.status_name, user.status_name_i18n, user.enable?, user.disable?, user.enable!, user.disable!

If with option prefix is true:

acts_as_enum :status, :in => [ ['disable', '冻结'], ['enable', '激活'] ], :prefix => true

Will generate bellow:

User::STATUS_DISABLE, User::STATUS_ENABLE, User.status_enable, User.status_disable, user.status_enable?, user.status_disable?

Note

Copyright © 2010 [email protected], released under the MIT license