Customize from enumize
Extend methods enum to I18n enum in Rails
Add this line to your application's Gemfile:
gem 'enum_render', "~> 1.0"And then execute:
$ bundle install
# app/model/event.rb
class Event
enum status: {pending: 0, approved: 1, declined: 2}
endIn I18n translate file:
# config/locales/en.yml
en:
enums:
event:
status:
pending: "Pending"
approved: "Approved"
declined: "Declined"
# config/locales/ja.yml
ja:
enums:
event:
status:
pending: "保留中"
approved: "承認済み"
declined: "辞退"We have methods: Event.statuses and Event.first.status
After install we have methods:
[2] pry(main)> Event.status_options
[{"key"=>"pending", "value"=>"保留中"}, {"key"=>"approved", "value"=>"承認済み"}, {"key"=>"declined", "value"=>"辞退"}][6] pry(main)> Event.first.status_option
{"key"=>"approved", "value"=>"承認済み"}[9] pry(main)> Event.first.status_name
=> "承認済み"[8] pry(main)> Event.first.status_value
=> 1[10] pry(main)> Event.status_select
=> [["保 留 中 ", "pending"], ["承 認 済 み ", "approved"], ["辞 退 ", "declined"]]Issues: rails/rails#13971
Currently, if a "bad" value (say, "canceled") is passed in, an ArgumentError is raised.
After install you can validate them by inclusion validates
# app/model/event.rb
class Event
enum status: {pending: 0, approved: 1, declined: 2}
validates :status, presence: true, inclusion: {in: statuses.keys}
endThe gem is available as open source under the terms of the MIT License.
Everyone interacting in the EnumRender project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.