Sha256: e1ff56c6de18850e4887ab94db9ec069bfe0311241b7d060fde5ac26b882b8b0

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

module Switchman
  module ActiveRecord
    module Reflection
      module AbstractReflection
        def shard(owner)
          if polymorphic? || klass.shard_category == owner.class.shard_category
            # polymorphic associations assume the same shard as the owning item
            owner.shard
          else
            Shard.default
          end
        end
      end

      if ::Rails.version >= '4.2'
        module AssociationScopeCache
          def initialize(*args)
            super
            # on ThroughReflection, these won't be initialized (cause it doesn't
            # inherit from AssociationReflection), so make sure they're
            # initialized here
            @association_scope_cache ||= {}
            @scope_lock ||= Mutex.new
          end

          # cache association scopes by shard.
          # this technically belongs on AssociationReflection, but we put it on
          # ThroughReflection as well, instead of delegating to its internal
          # HasManyAssociation, losing its proper `klass`
          def association_scope_cache(conn, owner)
            key = conn.prepared_statements
            if polymorphic?
              key = [key, owner._read_attribute(@foreign_type)]
            end
            key = [key, shard(owner).id].flatten
            @association_scope_cache[key] ||= @scope_lock.synchronize {
              @association_scope_cache[key] ||= yield
            }
          end
        end
      end

      module AssociationReflection
        # removes memoization - ActiveRecord::ModelSchema does that anyway;
        # and in fact this is the exact change AR makes in 4.2+
        if ::Rails.version < '4.2'
          def quoted_table_name
            klass.quoted_table_name
          end
        else
          def join_id_for(owner)
            owner.send(active_record_primary_key) # use sharded id values in association binds
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
switchman-1.7.4 lib/switchman/active_record/reflection.rb