Created
September 10, 2019 09:34
-
-
Save dmitriy-kiriyenko/747ef4d714d2ad2f5665e837363d127a to your computer and use it in GitHub Desktop.
Don't do that -- just don't use Globalize. But if you have to...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module FuckGlobalize | |
extend ActiveSupport::Concern | |
included do | |
scope :with_globalize_join, -> { | |
fk = "#{table_name.singularize}_id" | |
select(columns.map(&:name)) | |
.select(*translated_attribute_names.map { |n| "t.#{n} as #{n}" }) | |
.joins("JOIN #{translations_table_name} t ON t.#{fk} = #{table_name}.id AND t.locale = '#{I18n.locale}'") | |
} | |
end | |
module AssociationExtension | |
def load_with_globalize_associations(*associations) | |
to_a.tap do |collection| | |
associations.each do |association_name| | |
rel = klass.reflect_on_association(association_name) | |
ids = collection.index_by(&rel.foreign_key.to_sym) | |
objects = rel.klass.where(id: ids.keys) | |
objects.each do |object| | |
ids[object.id].send("_store_#{association_name}", object) | |
end | |
end | |
end | |
end | |
end | |
module ClassMethods | |
def define_globalize_association(name, class_name: name.classify, foreign_key: "#{name}_id", **opts) | |
klass = class_name.constantize | |
iv = "@_#{name}" | |
belongs_to name, class_name: class_name, foreign_key: foreign_key, **opts | |
define_method name do |reload = false| | |
instance_variable_set(iv, nil) if reload || instance_variable_get(iv)&.id != send(foreign_key) | |
return instance_variable_get(iv) if instance_variable_get(iv) || !send(foreign_key) | |
instance_variable_set(iv, klass.find(send(foreign_key))) | |
end | |
define_method "_store_#{name}" do |obj| | |
raise ArgumentError unless obj.id.to_s == send(foreign_key).to_s | |
instance_variable_set(iv, obj) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment