Skip to content

Instantly share code, notes, and snippets.

@dmitriy-kiriyenko
Created September 10, 2019 09:34
Show Gist options
  • Save dmitriy-kiriyenko/747ef4d714d2ad2f5665e837363d127a to your computer and use it in GitHub Desktop.
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...
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