Easily Translate Enums in Rails
Ruby Shell
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
bin 🌔 Mar 7, 2017
lib Add default locale lookup Feb 1, 2018
spec Add default locale lookup Feb 1, 2018
.gitignore Add ActiveRecord optional extend Mar 7, 2017
.rspec 🌔 Mar 7, 2017
CHANGELOG.md Add default locale lookup Feb 1, 2018
Gemfile 🌔 Mar 7, 2017
README.md Add default locale lookup Feb 1, 2018
Rakefile 🌔 Mar 7, 2017
translate_enum.gemspec Add ActiveRecord optional extend Mar 7, 2017

README.md

Build Status Code Climate

TranslateEnum

Simple, zero-dependant enum translation gem for Rails

Installation

gem install translate_enum

Usage

Here is a regular use case. ActiveRecord model:

class Post < ActiveRecord::Base
  include TranslateEnum
  
  enum status: { published: 0, archive: 1 }
  translate_enum :status
end

Localization file

en:
  activerecord:
    attributes:
      post:
        status_list:
          published: Was published
          archive: Was archived

Or if you wish your locales to be available across all models

en:
  attributes:
    status_list:
      published: Was published
      archive: Was archived
Post.translated_status(:published) #=> "Was published"
Post.translated_statuses => [["Was published", :published, 0], ["Was archived", :archive, 1]]

@post = Post.new(status: :published)
@post.translated_status #=> "Was published"

Use in a Form

= form_for @post do |f|
  = f.select :status, options_for_select(f.object.class.translated_statuses.map { |translation, k, _v| [translation, k] })

Extending ActiveRecord

Be default you should extend each ActiveRecord model manually by including TranslateEnum module in it. You can extend ActiveRecord by requiring translate_enum/active_record in initializer or inside yout Gemfile:

Gemfile:

gem 'translate_enum', require: 'translate_enum/active_record'

Initializer:

# config/initializers/translate_enum.rb
require 'translate_enum/active_record'

Advanced options

class User < ActiveRecord::Base
  enum gender: [:male, :female]
  
  translate_enum :gender do |tr|
    tr.i18n_scope = 'activerecord.attributes'
    tr.i18n_key = 'gender_list'
    tr.enum_klass_method_name = 'genders'
    tr.enum_instance_method_name = 'gender'
    tr.method_name_singular = 'translated_gender'
    tr.method_name_plural = 'translated_genders'
  end
  
  # Or even provide your own logic
  def self.translated_gender(key)
    I18n.t(key, scope: 'global.gender_list')
  end
end