awesome_model_translations 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: d685fdb24edf2a610296eeaed9b1451d77a3c740a5e795f34349aa26fb08e5b5
4
+ data.tar.gz: bd45b672348ca62bf79685c9d61dcc0f4714cf40ef6f2aa47f2360c5deb7de26
5
+ SHA512:
6
+ metadata.gz: 4a624e297b2322973cee6abdeda2235bb725d2f96436d6210cc5a75d59e58b4759b30e5bac8bbcc18ae445e2f0279486317282ada8dd42ac0965b778a913b984
7
+ data.tar.gz: 1ff917307cc959031d9a57d62fade905cccc2fea0979be8a5a98408de6c0ea429b366fe21a43719c13ecb539237ab0f93a39bc66f4c59265840652e5ebd893c9
data/MIT-LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ Copyright 2023 kaspernj
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,51 @@
1
+ # AwesomeModelTranslations
2
+ Short description and motivation.
3
+
4
+ ## Usage
5
+
6
+ Add a translated attribute to your model:
7
+ ```ruby
8
+ class Project < ApplicationRecord
9
+ translates :name
10
+ end
11
+ ```
12
+
13
+ You can set the name in the current locale like this:
14
+ ```ruby
15
+ I18n.locale = :en
16
+ project.name = "English name"
17
+ project.name #=> "English name"
18
+ ```
19
+
20
+ Or set the name for a specific locale like this:
21
+ ```ruby
22
+ I18n.locale = :en
23
+ project.name_da = "Dansk navn"
24
+ project.name #=> "Dansk navn"
25
+ ```
26
+
27
+ ## Installation
28
+ Add this line to your application's Gemfile:
29
+
30
+ ```ruby
31
+ gem "awesome_model_translations"
32
+ ```
33
+
34
+ And then execute:
35
+ ```bash
36
+ $ bundle
37
+ ```
38
+
39
+ Or install it yourself as:
40
+ ```bash
41
+ $ gem install awesome_model_translations
42
+ ```
43
+
44
+ Install the migrations and run them:
45
+ ```bash
46
+ rake railties:install:migrations
47
+ rails db:migrate
48
+ ```
49
+
50
+ ## License
51
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ require "bundler/setup"
2
+
3
+ APP_RAKEFILE = File.expand_path("spec/dummy/Rakefile", __dir__)
4
+ load "rails/tasks/engine.rake"
5
+
6
+ load "rails/tasks/statistics.rake"
7
+
8
+ require "bundler/gem_tasks"
@@ -0,0 +1 @@
1
+ //= link_directory ../stylesheets/awesome_model_translations .css
@@ -0,0 +1,15 @@
1
+ /*
2
+ * This is a manifest file that'll be compiled into application.css, which will include all the files
3
+ * listed below.
4
+ *
5
+ * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
6
+ * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
7
+ *
8
+ * You're free to add application-wide styles to this file and they'll appear at the bottom of the
9
+ * compiled file so the styles you add here take precedence over styles defined in any other CSS/SCSS
10
+ * files in this directory. Styles in this file should be added after the last require_* statement.
11
+ * It is generally better to create a new file per style scope.
12
+ *
13
+ *= require_tree .
14
+ *= require_self
15
+ */
@@ -0,0 +1,2 @@
1
+ class AwesomeModelTranslations::ApplicationController < ActionController::Base
2
+ end
@@ -0,0 +1,2 @@
1
+ module AwesomeModelTranslations::ApplicationHelper
2
+ end
@@ -0,0 +1,2 @@
1
+ class AwesomeModelTranslations::ApplicationJob < ActiveJob::Base
2
+ end
@@ -0,0 +1,4 @@
1
+ class AwesomeModelTranslations::ApplicationMailer < ActionMailer::Base
2
+ default from: "from@example.com"
3
+ layout "mailer"
4
+ end
@@ -0,0 +1,3 @@
1
+ class AwesomeModelTranslations::ApplicationRecord < ActiveRecord::Base
2
+ self.abstract_class = true
3
+ end
@@ -0,0 +1,7 @@
1
+ class AwesomeModelTranslations::Slug < AwesomeModelTranslations::ApplicationRecord
2
+ self.table_name = "slugs"
3
+
4
+ belongs_to :sluggable, polymorphic: true
5
+
6
+ validates :slug, presence: true
7
+ end
@@ -0,0 +1,15 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Awesome model translations</title>
5
+ <%= csrf_meta_tags %>
6
+ <%= csp_meta_tag %>
7
+
8
+ <%= stylesheet_link_tag "awesome_model_translations/application", media: "all" %>
9
+ </head>
10
+ <body>
11
+
12
+ <%= yield %>
13
+
14
+ </body>
15
+ </html>
data/config/routes.rb ADDED
@@ -0,0 +1,2 @@
1
+ AwesomeModelTranslations::Engine.routes.draw do # rubocop:disable Lint/EmptyBlock
2
+ end
@@ -0,0 +1,16 @@
1
+ class CreateSlugs < ActiveRecord::Migration[7.0]
2
+ def change
3
+ create_table :slugs do |t|
4
+ t.string "slug", null: false
5
+ t.string "scope"
6
+ t.datetime "created_at"
7
+ t.string "locale", null: false
8
+ t.references :sluggable, null: false, polymorphic: true
9
+ t.index ["locale"], name: "index_slugs_on_locale"
10
+ t.index ["slug", "sluggable_type", "locale"], name: "index_slugs_on_slug_and_sluggable_type_and_locale"
11
+ t.index ["slug", "sluggable_type", "scope", "locale"], name: "index_slugs_uniqueness", unique: true
12
+ t.index ["sluggable_id"], name: "index_slugs_on_sluggable_id"
13
+ t.index ["sluggable_type"], name: "index_slugs_on_sluggable_type"
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,27 @@
1
+ module AwesomeModelTranslations::CurrentTranslationScope
2
+ def self.included(base)
3
+ translation_class_name = "#{base.name}::Translation"
4
+ translation_class = translation_class_name.constantize
5
+ table_name = translation_class.table_name
6
+ foreign_key_name = base.reflections["translations"].foreign_key
7
+
8
+ scope_proc = proc do
9
+ locales_list = I18n.available_locales.join("', '")
10
+ sub_query_sql = "#{table_name}.#{translation_class.primary_key} = (" \
11
+ "SELECT #{table_name}.#{translation_class.primary_key} " \
12
+ "FROM #{table_name} " \
13
+ "WHERE #{table_name}.#{foreign_key_name} = #{base.table_name}.#{base.primary_key} AND " \
14
+ "#{table_name}.locale IN ('#{locales_list}') " \
15
+ "ORDER BY " \
16
+ "CASE WHEN #{table_name}.locale = '#{I18n.locale}' THEN 1 " \
17
+ "ELSE 2 " \
18
+ "END " \
19
+ "LIMIT 1" \
20
+ ")"
21
+
22
+ where(sub_query_sql)
23
+ end
24
+
25
+ base.has_one :current_translation, scope_proc, class_name: translation_class_name
26
+ end
27
+ end
@@ -0,0 +1,3 @@
1
+ class AwesomeModelTranslations::Engine < Rails::Engine
2
+ isolate_namespace AwesomeModelTranslations
3
+ end
@@ -0,0 +1,131 @@
1
+ module AwesomeModelTranslations::ModelExtensions
2
+ def self.included(base)
3
+ base.extend ClassMethods
4
+ end
5
+
6
+ module ClassMethods
7
+ def translates(*attributes) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
8
+ translations_class_name = "#{name}::Translation"
9
+ translations_table_name = "#{table_name.singularize}_translations"
10
+
11
+ translation_model_class = Class.new(AwesomeModelTranslations::Translation) do
12
+ self.table_name = translations_table_name
13
+ end
14
+
15
+ translation_model_class.define_singleton_method(:name) do
16
+ translations_class_name
17
+ end
18
+
19
+ define_singleton_method(:translated_attribute_names) do
20
+ attributes
21
+ end
22
+
23
+ translation_model_class.belongs_to :globalized_model, class_name: model_name.name, foreign_key: "#{model_name.element}_id", inverse_of: :translations,
24
+ optional: true
25
+
26
+ const_set(:Translation, translation_model_class)
27
+
28
+ has_many :translations, autosave: true, class_name: translations_class_name, dependent: :destroy, inverse_of: :globalized_model
29
+
30
+ define_method(:attributes) do |*args, &blk|
31
+ original_attributes = super(*args, &blk).clone
32
+ translated_attributes = {}
33
+
34
+ self.class.translated_attribute_names.each do |translated_attribute_name|
35
+ original_attributes.delete(translated_attribute_name.to_s)
36
+ end
37
+
38
+ association(:translations).target.each do |translation|
39
+ self.class.translated_attribute_names.each do |translated_attribute_name|
40
+ if translation.attributes.key?(translated_attribute_name.to_s)
41
+ translated_attributes["#{translated_attribute_name}_#{translation.locale}"] = translation.attributes.fetch(translated_attribute_name.to_s)
42
+ end
43
+ end
44
+ end
45
+
46
+ original_attributes.merge(translated_attributes)
47
+ end
48
+
49
+ define_method(:changed?) do |*args, &blk|
50
+ super(*args, &blk) || translations.target.any?(&:changed?)
51
+ end
52
+
53
+ define_method(:changes) do |*args, &blk|
54
+ original_changes = super(*args, &blk).clone
55
+ translated_changes = {}
56
+
57
+ self.class.translated_attribute_names.each do |translated_attribute_name|
58
+ original_changes.delete(translated_attribute_name.to_s)
59
+ end
60
+
61
+ association(:translations).target.each do |translation|
62
+ self.class.translated_attribute_names.each do |translated_attribute_name|
63
+ if translation.changes.key?(translated_attribute_name.to_s)
64
+ translated_changes["#{translated_attribute_name}_#{translation.locale}"] = translation.changes.fetch(translated_attribute_name.to_s)
65
+ end
66
+ end
67
+ end
68
+
69
+ original_changes.merge(translated_changes)
70
+ end
71
+
72
+ define_method(:saved_changes) do |*args, &blk|
73
+ original_saved_changes = super(*args, &blk).clone
74
+ translated_saved_changes = {}
75
+
76
+ self.class.translated_attribute_names.each do |translated_attribute_name|
77
+ original_saved_changes.delete(translated_attribute_name.to_s)
78
+ end
79
+
80
+ association(:translations).target.each do |translation|
81
+ self.class.translated_attribute_names.each do |translated_attribute_name|
82
+ if translation.saved_changes.key?(translated_attribute_name.to_s)
83
+ translated_saved_changes["#{translated_attribute_name}_#{translation.locale}"] = translation.saved_changes.fetch(translated_attribute_name.to_s)
84
+ end
85
+ end
86
+ end
87
+
88
+ original_saved_changes.merge(translated_saved_changes)
89
+ end
90
+
91
+ attributes.each do |attribute_name|
92
+ attribute attribute_name.to_sym
93
+
94
+ define_method(attribute_name) do
95
+ fallbacks = I18n.fallbacks[I18n.locale]
96
+ value = nil
97
+
98
+ fallbacks&.each do |locale|
99
+ value = __send__(:"#{attribute_name}_#{locale}")
100
+
101
+ break if value.present?
102
+ end
103
+
104
+ value
105
+ end
106
+
107
+ define_method(:"#{attribute_name}=") do |new_value|
108
+ __send__(:"#{attribute_name}_#{I18n.locale}=", new_value)
109
+ end
110
+
111
+ I18n.available_locales.each do |locale|
112
+ current_locale = locale.to_s
113
+
114
+ define_method(:"#{attribute_name}_#{locale}") do
115
+ translations.detect { |translation| translation.locale == current_locale }&.__send__(attribute_name)
116
+ end
117
+
118
+ define_method(:"#{attribute_name}_#{locale}=") do |new_value|
119
+ translation = translations.detect { |translation_i| translation_i.locale == current_locale }
120
+ translation ||= translations.build(locale: current_locale)
121
+ old_value = translation.__send__(attribute_name)
122
+ translation.assign_attributes(attribute_name => new_value)
123
+ __send__(:attribute_will_change!, attribute_name) if old_value != new_value
124
+ end
125
+ end
126
+ end
127
+
128
+ include AwesomeModelTranslations::CurrentTranslationScope
129
+ end
130
+ end
131
+ end
@@ -0,0 +1,80 @@
1
+ module AwesomeModelTranslations::Sluggable
2
+ def self.included(base)
3
+ base.extend ClassMethods
4
+ base.has_many :slugs, as: :sluggable, class_name: "AwesomeModelTranslations::Slug", dependent: :destroy
5
+ base.after_save :__set_slug
6
+
7
+ base.scope :where_current_slug, lambda { |slug|
8
+ joins(:slugs)
9
+ .where(slugs: {locale: I18n.locale}).where("slugs.slug = :slug OR #{table_name}.id = :slug", slug:)
10
+ }
11
+ end
12
+
13
+ module ClassMethods
14
+ def find_by_sluggable!(param)
15
+ return find(param) if UuidTester.uuid?(param)
16
+
17
+ locales = I18n.fallbacks[I18n.locale]&.map(&:to_s) || [I18n.locale.to_]
18
+ slugs = AwesomeModelTranslations::Slug
19
+ .select(:locale, :sluggable_id, :sluggable_type)
20
+ .where(
21
+ slug: param,
22
+ sluggable_type: name
23
+ )
24
+ .to_a
25
+
26
+ locales.each do |locale|
27
+ slug_with_locale = slugs.find { |slug| slug.locale == locale }
28
+
29
+ return slug_with_locale.sluggable if slug_with_locale
30
+ end
31
+
32
+ raise ActiveRecord::RecordNotFound, "No #{name} found with that slug: #{param}"
33
+ end
34
+ end
35
+
36
+ def __current_slug
37
+ locales = I18n.fallbacks[I18n.locale].map(&:to_s) || [I18n.locale.to_s]
38
+ slugs_to_check = slugs.to_a.sort_by(&:created_at).reverse
39
+
40
+ locales.each do |locale|
41
+ slug_with_locale = slugs_to_check.find { |slug| slug.locale == locale }
42
+
43
+ return slug_with_locale.slug if slug_with_locale
44
+ end
45
+
46
+ id
47
+ end
48
+
49
+ def __generate_slug
50
+ name_for_slug = if respond_to?(:sluggable_slug, true) && sluggable_slug.present?
51
+ sluggable_slug
52
+ elsif name.present?
53
+ name
54
+ end
55
+
56
+ return nil if name_for_slug.blank?
57
+
58
+ name_for_slug.downcase.gsub(/(\s+|\/)/, "-")
59
+ end
60
+
61
+ def __set_slug
62
+ I18n.available_locales.each do |locale|
63
+ I18n.with_locale(locale) do
64
+ slug = __generate_slug
65
+
66
+ next if slug.blank?
67
+
68
+ slugs.find_or_create_by!(locale:, slug:)
69
+ end
70
+ end
71
+ end
72
+
73
+ def slug
74
+ __current_slug
75
+ end
76
+
77
+ def to_param
78
+ __current_slug
79
+ end
80
+ end
@@ -0,0 +1,3 @@
1
+ class AwesomeModelTranslations::Translation < AwesomeModelTranslations::ApplicationRecord
2
+ self.abstract_class = true
3
+ end
@@ -0,0 +1,3 @@
1
+ module AwesomeModelTranslations
2
+ VERSION = "0.1.0".freeze
3
+ end
@@ -0,0 +1,9 @@
1
+ require "awesome_model_translations/version"
2
+ require "awesome_model_translations/engine"
3
+
4
+ module AwesomeModelTranslations
5
+ autoload :CurrentTranslationScope, "#{__dir__}/awesome_model_translations/current_translation_scope"
6
+ autoload :ModelExtensions, "#{__dir__}/awesome_model_translations/model_extensions"
7
+ autoload :Sluggable, "#{__dir__}/awesome_model_translations/sluggable"
8
+ autoload :Translation, "#{__dir__}/awesome_model_translations/translation"
9
+ end
@@ -0,0 +1,4 @@
1
+ # desc "Explaining what the task does"
2
+ # task :awesome_model_translations do
3
+ # # Task goes here
4
+ # end
metadata ADDED
@@ -0,0 +1,82 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: awesome_model_translations
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - kaspernj
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2025-04-15 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rails
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: 7.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: 7.0.0
27
+ description: Model translations for ActiveRecord.
28
+ email:
29
+ - kasper@diestoeckels.de
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - MIT-LICENSE
35
+ - README.md
36
+ - Rakefile
37
+ - app/assets/config/awesome_model_translations_manifest.js
38
+ - app/assets/stylesheets/awesome_model_translations/application.css
39
+ - app/controllers/awesome_model_translations/application_controller.rb
40
+ - app/helpers/awesome_model_translations/application_helper.rb
41
+ - app/jobs/awesome_model_translations/application_job.rb
42
+ - app/mailers/awesome_model_translations/application_mailer.rb
43
+ - app/models/awesome_model_translations/application_record.rb
44
+ - app/models/awesome_model_translations/slug.rb
45
+ - app/views/layouts/awesome_model_translations/application.html.erb
46
+ - config/routes.rb
47
+ - db/migrate/20231216092051_create_slugs.rb
48
+ - lib/awesome_model_translations.rb
49
+ - lib/awesome_model_translations/current_translation_scope.rb
50
+ - lib/awesome_model_translations/engine.rb
51
+ - lib/awesome_model_translations/model_extensions.rb
52
+ - lib/awesome_model_translations/sluggable.rb
53
+ - lib/awesome_model_translations/translation.rb
54
+ - lib/awesome_model_translations/version.rb
55
+ - lib/tasks/awesome_model_translations_tasks.rake
56
+ homepage: https://github.com/kaspernj/awesome_model_translations
57
+ licenses:
58
+ - MIT
59
+ metadata:
60
+ homepage_uri: https://github.com/kaspernj/awesome_model_translations
61
+ source_code_uri: https://github.com/kaspernj/awesome_model_translations
62
+ rubygems_mfa_required: 'true'
63
+ post_install_message:
64
+ rdoc_options: []
65
+ require_paths:
66
+ - lib
67
+ required_ruby_version: !ruby/object:Gem::Requirement
68
+ requirements:
69
+ - - ">="
70
+ - !ruby/object:Gem::Version
71
+ version: 3.3.5
72
+ required_rubygems_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '0'
77
+ requirements: []
78
+ rubygems_version: 3.5.16
79
+ signing_key:
80
+ specification_version: 4
81
+ summary: Model translations for ActiveRecord.
82
+ test_files: []