Skip to content

Instantly share code, notes, and snippets.

@kengos
Created April 22, 2012 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kengos/2464207 to your computer and use it in GitHub Desktop.
Save kengos/2464207 to your computer and use it in GitHub Desktop.
ActiveEnum i18n support patch
# In your config/initializers/active_enum.rb
# @see https://github.com/adzap/active_enum/pull/4
# @example
# * ja.yml
# active_enum:
# user:
# sex:
# male: '男性'
# female: '女性'
# * user.rb
# class User < ActiveRecord::Base
# class Sex < ActiveEnum::Base
# value id: 0, name: 'male'
# value id: 1, name: 'female'
# end
# end
# User::Sex.tr_to_select
# # => [['男性', 0], ['女性', 1]
# User::Sex.translate('male')
# # => '男性'
# User::Sex.translate(1)
# # => '女性'
# User::Sex.t('famale')
# # => '女性'
# User.new(sex: 0).sex(:t)
# # => '男性'
# User.new(sex: 1).sex(:translation)
# # => '女性'
module ActiveEnum
class Base
class << self
def tr_to_select
store.values.map do |v|
translated = I18n.translate(v[1].downcase.gsub(/\s/, '_'), scope: i18n_scope, default: v[1])
[translated, v[0]]
end
end
def translate(index)
if row = get_row(index)
I18n.translate(row[1].downcase.gsub(/\s/, '_'), scope: i18n_scope)
end
end
alias :t :translate
protected
def i18n_scope
[:active_enum, self.name.underscore.gsub(/\//, '.')]
end
def get_row(index)
if index.is_a?(Fixnum)
store.get_by_id(index)
else
store.get_by_name(index)
end
end
end
end
module Extensions
module ClassMethods
def define_active_enum_read_method(attribute)
class_eval <<-DEF
def #{attribute}(arg=nil)
value = super()
return if value.nil? && arg.nil?
enum = self.class.active_enum_for(:#{attribute})
case arg
when :id
value if enum[value]
when :name
enum[value]
when :enum
enum
when :translation, :t
enum.translate(value)
when Symbol
(enum.meta(value) || {})[arg]
else
#{ActiveEnum.use_name_as_value ? 'enum[value]' : 'value' }
end
end
DEF
end
end
end
end
@kengos
Copy link
Author

kengos commented Apr 22, 2012

ActiveEnumを使ってi18n対応させるためのパッチ

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