shioyama/mobility

table fallbacks

Opened this issue · 1 comments

We migrated from Globalize today and were heavily dependent on fallbacks support for query, so wrote a simple initializer that brought the functionality back for the table backend.

# config/initializers/mobility_extensions.rb

module MobilityQueryFallbacks
  extend ActiveSupport::Concern

  class FallbackAttribute < ::Arel::Nodes::NamedFunction
    include Mobility::Plugins::Arel::MobilityExpressions

    attr_reader :backend_class
    attr_reader :locale
    attr_reader :attribute_name

    def initialize(fallback_attributes, locale, backend_class, attribute_name)
      @backend_class = backend_class
      @locale = locale
      @attribute_name = attribute_name
      super('COALESCE', fallback_attributes)
    end
  end

  class_methods do

    def build_node(attr, locale)
      fallback_locales = I18n.fallbacks[locale]
      return super if fallback_locales.length == 1
      fallback_attributes = fallback_locales.map { |locale| super(attr, locale) }
      FallbackAttribute.new(fallback_attributes, locale, self, attr)
    end

    def join_translations(relation, locale, join_type)
      fallback_locales = I18n.fallbacks[locale]
      return super if fallback_locales.length == 1
      fallback_locales.reduce(relation) do |relation, locale|
        super(relation, locale, Mobility::Plugins::Arel::Visitor::OUTER_JOIN)
      end
    end
  end
end

ActiveSupport.on_load(:active_record) do
  require 'mobility/backends/active_record/table'

  Mobility::Backends::ActiveRecord::Table.prepend(MobilityQueryFallbacks)
end

Wanted to open a ticket as this doesn't feel far off a good solution, and would love to see this functionality added. What are your thoughts @shioyama on this as a general direction?

I'm running in the same issue here, could this be implemented?