SimpleEnum
==========
[![Gem Version](https://badge.fury.io/rb/simple_enum.svg)](https://badge.fury.io/rb/simple_enum)
[![Build Status](https://travis-ci.org/lwe/simple_enum.svg)](https://travis-ci.org/lwe/simple_enum)
[![Code Climate](https://codeclimate.com/github/lwe/simple_enum.svg)](https://codeclimate.com/github/lwe/simple_enum)
Unobtrusive enum-like fields for ActiveRecord and Ruby, brings enums functionality
to ActiveRecord and Mongoid models (built for Rails 4+).
Since version 2.0, simple_enum is no longer compatible with Rails 3.x or Ruby 1.8,
use version 1.6 instead: https://github.com/lwe/simple_enum/tree/legacy-1.x
*Note*: a recent search on github for `enum` turned out, that there are many,
many similar solutions. In fact starting with Rails 4.1, there's `ActiveRecord::Enum`
which provides **some** of the functionality, but is IMHO pretty limited and too
strict in the defaults it provides.
ActiveRecord Quick start
------------------------
Add this to a model:
```ruby
class User < ActiveRecord::Base
as_enum :gender, female: 1, male: 0
end
```
Then create the required `gender_cd` column using migrations:
```ruby
class AddGenderColumnToUser < ActiveRecord::Migration
def self.up
add_column :users, :gender_cd, :integer
end
def self.down
remove_column :users, :gender_cd
end
end
```
Mongoid Quick start
-------------------
Due to the dependency on ActiveModel 4.x, the Mongoid integration is only
available for mongoid 4.0.0 (which is at beta1 at the moment). If you intend
to use simple_enum with another version of mongoid, use version 1.6 instead.
Load mongoid support in the `Gemfile`:
```ruby
gem 'simple_enum', '~> 2.3.0' , require: 'simple_enum/mongoid'
```
Add this to a model:
```ruby
class User
include Mongoid::Document
include SimpleEnum::Mongoid
as_enum :gender, female: 1, male: 0
end
```
The primary difference between AR and mongoid is, that additionaly a field is
added to mongoid automatically, the field can be customized by setting `field:`
option, or disabled by setting `field: false`.
Working with enums
------------------
Now it's possible to pull some neat tricks on the new column, yet the original
db column (`gender_cd`) is still intact and not touched by anything.
```ruby
jane = User.new
jane.gender = :female
jane.female? # => true
jane.male? # => false
jane.gender # => :female
jane.gender_cd # => 1
```
Easily switch to another value using the bang methods, this does not save
the record, only switch the value.
```ruby
joe = User.new
joe.male! # => :male
joe.gender # => :male
joe.gender_cd # => 0
```
Accessing actual enum values is possible at the class level:
```ruby
User.genders # => #<SimpleEnum::Enum:0x0....>
User.genders[:male] # => 0
User.genders.values_at(:male, :female) # => [0, 1] (since 2.1.0)
User.females # => #<ActiveRecord::Relation:0x0.....> (WHERE gender_cd = 1)
```
By default, scope names are generated as pluralized forms of the defined enum values e.g.
```ruby
class Booking < ActiveRecord::Base
as_enum :status, %i{active cancelled pending}
end
```
would generate the following:
```ruby
Booking.actives # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 1)
Booking.cancelleds # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 2)
Booking.pendings # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 3)
```
By setting `pluralize_scopes: false` will not generate pluralized versions of scopes e.g.
```ruby
class Booking < ActiveRecord::Base
as_enum :status, %i{active cancelled pending}, pluralize_scopes: false
end
```
would generate the following:
```ruby
Booking.active # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 1)
Booking.cancelled # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 2)
Booking.pending # => #<ActiveRecord::Relation:0x0.....> (WHERE status_cd = 3)
```
### Wait, there's more!
- Too tired of always adding the integer values? Try:
```ruby
class User < ActiveRecord::Base
as_enum :status, %i{deleted active disabled}
# translates to: { deleted: 0, active: 1, disabled: 2 }
end
```
**Disclaimer**: if you _ever_ decide to reorder this array, beware that any
previous mapping is lost. So it's recommended to create mappings (that might
change) using hashes instead of arrays. For stuff like gender it might be
probably perfectly fine to use arrays though.
- You can store as string values instead of integer values if your database column
has the type `string` or `text`:
```ruby
class User < ActiveRecord::Base
as_enum :status, [:deleted, :active, :disabled], map: :string
end
User.create!(status: :active) #=> #<User id: 1, status_cd: "active">
```
- Want to use `SimpleEnum` in an ActiveModel, or other class, just add:
```ruby
class MyModel
extend SimpleEnum::Attribute
attr_accessor :gender_cd
as_enum :gender, [:male, :female]
end
```
- Maybe you've columns named differently than the proposed `{column}_cd` naming scheme, feel free to use any column name
by providing an option:
```ruby
class User < ActiveRecord::Base
as_enum :gender, [:male, :female], source: :sex
end
```
Starting with 2.0 it's possible to use the same source name as column name.
- By default ActiveRecord dirty methods are generated:
```ruby
user = User.male.first
user.gender = :female
user.gender_was
# => :male
```
- Need to provide custom options for the mongoid field, or skip the automatically generated field?
```ruby
# skip field generation
field :gender_cd # <- create field manually (!)
as_enum :gender, [:male, :female], field: false
# custom field options (directly passed to Mongoid::Document#field)
as_enum :gender, [:male, :female], field: { :type => Integer, :default => 1 }
```
- To validate enum values simply make use of a `validates :gender, presence: true` validation.
If an invalid value is assigned, the gender is set to `nil` by default.
- If the shortcut methods (like `female?`, `female!` or `User.male`) conflict with something in your class, it's possible to
define a prefix:
```ruby
class User < ActiveRecord::Base
as_enum :gender, %w{male female}, prefix: true
end
jane = User.new gender: :female
jane.gender_female? # => true
User.gender_females # => <ActiveRecord::Relation...WHERE gender_cd = 1.>
```
The `:prefix` option not only takes a boolean value as an argument, but instead can also be supplied a custom
prefix, so with `prefix: 'foo'` all shortcut methods would look like: `foo_<symbol>`
- To define which methods are generated it's possible to set `with:` option, by
default `with:` is set to `[:attribute, :dirty, :scope]`.
1. `:attribute` - generates the `male?` and `male!` accessor methods
2. `:dirty` - adds the `gender_was` and `gender_changed?` dirty methods
3. `:scope` - adds the class level scopes, **if** the `scope` method is present
- By default the value is set to `nil` when the user sets an invalid value,
this behavior can be changed by setting the `accessor:` option. At the moment
there are three different behaviors:
1. `:default` - which sets the value simply to `nil`
2. `:whiny` - raises an ArgumentError when trying to set an invalid value
3. `:ignore` - keeps the existing value
```ruby
class User < ActiveRecord::Base
as_enum :gender, %w{male female}, accessor: :whiny
end
User.new(gender: "dunno") # => raises ArgumentError
```
See `lib/simple_enum/accessors/*` for more.
- To define any option globally, e.g. never generating dirty methods, create
an initializer and add:
```ruby
# See lib/simple_enum.rb for other options
SimpleEnum.with = [:attribute, :scope]
```
### View Helpers
Require translated enum values? See [SimpleEnum::ViewHelpers][VE.rb] for more
details and functions. _Disclaimer_: these methods are release candidate quality
没有合适的资源?快使用搜索试试~ 我知道了~
simple_enum, 支持ActiveModel的简单 enum ( 包括验证和 i18n ).zip
共41个文件
rb:25个
gemfile:10个
gemspec:1个
需积分: 9 0 下载量 171 浏览量
2019-09-18
22:43:22
上传
评论
收藏 30KB ZIP 举报
温馨提示
simple_enum, 支持ActiveModel的简单 enum ( 包括验证和 i18n ) SimpleEnum 对于ActiveRecord和 ruby,低调的枚举像字段一样,给ActiveRecord和Mongoid模型( 为 Rails 4 构建) 带来了枚举功能。从 2.0版本开始,simple_enum
资源推荐
资源详情
资源评论
收起资源包目录
simple_enum.zip (41个子文件)
simple_enum-master
.gitignore 79B
README.md 11KB
gemfiles
mongoid-7.0.gemfile 308B
rails-4.2.gemfile 359B
rails-4.1.gemfile 359B
rails-4.0.gemfile 359B
rails-5.2.gemfile 347B
rails-5.1.gemfile 347B
mongoid-6.0.gemfile 308B
mongoid-5.0.gemfile 320B
mongoid-4.0.gemfile 320B
Gemfile 347B
simple_enum.gemspec 1KB
LICENSE 1KB
spec
support
model_support.rb 1005B
i18n_support.rb 381B
mongoid_support.rb 1KB
active_record_support.rb 830B
simple_enum
mongoid_spec.rb 1015B
hasher_spec.rb 2KB
view_helpers_spec.rb 2KB
enum_spec.rb 3KB
attribute_spec.rb 9KB
accessors_spec.rb 9KB
translation_spec.rb 2KB
spec_helper.rb 590B
.travis.yml 2KB
lib
simple_enum.rb 1KB
simple_enum
attribute.rb 4KB
view_helpers.rb 2KB
mongoid.rb 1KB
accessors.rb 779B
railtie.rb 449B
hasher.rb 705B
version.rb 81B
enum.rb 926B
translation.rb 615B
accessors
whiny_accessor.rb 291B
accessor.rb 1KB
ignore_accessor.rb 216B
Rakefile 633B
共 41 条
- 1
资源评论
weixin_38744207
- 粉丝: 343
- 资源: 2万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功