From a9cbaadbc0dbd7fa418800919debadd259614f68 Mon Sep 17 00:00:00 2001 From: "Gregory N. Schmit" Date: Tue, 14 Feb 2023 14:55:25 -0600 Subject: [PATCH] Add integration for translate_enum. --- Gemfile | 5 ++++- Gemfile.lock | 3 +++ lib/rest_framework/controller_mixins/models.rb | 6 ++++++ test/app/models/user.rb | 3 +++ test/config/locales/en.yml | 6 ++++++ 5 files changed, 22 insertions(+), 1 deletion(-) create mode 100644 test/config/locales/en.yml diff --git a/Gemfile b/Gemfile index 0275095..4011784 100644 --- a/Gemfile +++ b/Gemfile @@ -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" diff --git a/Gemfile.lock b/Gemfile.lock index 0592229..f9a27ce 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -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) @@ -232,6 +234,7 @@ DEPENDENCIES simplecov simplecov-lcov (= 0.8.0) sqlite3 (~> 1.4.0) + translate_enum web-console webrick diff --git a/lib/rest_framework/controller_mixins/models.rb b/lib/rest_framework/controller_mixins/models.rb index 23a6c20..7b430c4 100644 --- a/lib/rest_framework/controller_mixins/models.rb +++ b/lib/rest_framework/controller_mixins/models.rb @@ -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 diff --git a/test/app/models/user.rb b/test/app/models/user.rb index c08c484..e878947 100644 --- a/test/app/models/user.rb +++ b/test/app/models/user.rb @@ -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 @@ -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 diff --git a/test/config/locales/en.yml b/test/config/locales/en.yml new file mode 100644 index 0000000..ae62045 --- /dev/null +++ b/test/config/locales/en.yml @@ -0,0 +1,6 @@ +en: + activerecord: + attributes: + user: + state_list: + banned: BANNED