Skip to content

Commit

Permalink
Add integration for translate_enum.
Browse files Browse the repository at this point in the history
  • Loading branch information
gregschmit committed Feb 14, 2023
1 parent d892ac9 commit a9cbaad
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 1 deletion.
5 changes: 4 additions & 1 deletion Gemfile
Expand Up @@ -16,11 +16,14 @@ if Gem::Version.new(RUBY_VERSION) >= Gem::Version.new("3")
gem "webrick"
end

# Include gem active_model_serializers so we can test against their interface (Rails >=6 only).
# Include `active_model_serializers` for custom integration (Rails >=6 only).
if RAILS_VERSION > Gem::Version.new("6")
gem "active_model_serializers", "0.10.13"
end

# Include `translate_enum` for custom integration.
gem "translate_enum"

group :development do
gem "annotate"
gem "better_errors"
Expand Down
3 changes: 3 additions & 0 deletions Gemfile.lock
Expand Up @@ -199,6 +199,8 @@ GEM
sqlite3 (1.4.4)
thor (1.2.1)
timeout (0.3.1)
translate_enum (0.2.0)
activesupport
tzinfo (2.0.6)
concurrent-ruby (~> 1.0)
unicode-display_width (2.4.2)
Expand Down Expand Up @@ -232,6 +234,7 @@ DEPENDENCIES
simplecov
simplecov-lcov (= 0.8.0)
sqlite3 (~> 1.4.0)
translate_enum
web-console
webrick

Expand Down
6 changes: 6 additions & 0 deletions lib/rest_framework/controller_mixins/models.rb
Expand Up @@ -207,6 +207,12 @@ def get_fields_metadata
# Get enum variants.
if type.is_a?(ActiveRecord::Enum::EnumType)
metadata[:enum_variants] = type.send(:mapping)

# Custom integration with `translate_enum`.
translate_method = "translated_#{f.pluralize}"
if model.respond_to?(translate_method)
metadata[:enum_translations] = model.send(translate_method)
end
end
end
end
Expand Down
3 changes: 3 additions & 0 deletions test/app/models/user.rb
Expand Up @@ -29,6 +29,8 @@ class User < ApplicationRecord
"offline" => "Offline",
"busy" => "Busy",
}
include TranslateEnum

belongs_to :manager, class_name: "User", optional: true
has_and_belongs_to_many :movies
has_many :emails
Expand All @@ -37,6 +39,7 @@ class User < ApplicationRecord
has_one :phone_number

enum state: {default: 0, pending: 1, banned: 2, archived: 3}
translate_enum :state

attribute :secret_number, :integer

Expand Down
6 changes: 6 additions & 0 deletions test/config/locales/en.yml
@@ -0,0 +1,6 @@
en:
activerecord:
attributes:
user:
state_list:
banned: BANNED

0 comments on commit a9cbaad

Please sign in to comment.