Sha256: 02eeab95aab3076352d1e0f12499a8f27e5c7f03d2430eca7bbb679f41a22ed5

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

# frozen_string_literal: true

module ActiveRecord
  module Reflection
    class AssociationReflection < MacroReflection
      private

      def convert_options_to_dynamic_reflection_options!
        @options = DynamicReflectionOptionsHash.new.merge!(
          @options,
          {
            association_model_name: class_name,
            association_type: collection? ? :collection : :singular
          }
        )
      end

      class DynamicReflectionOptionsHash < Hash
        def [](key)
          return super unless key == :dependent && super(:dependent) == :auto
          return fallback_method if defining_dependent_callbacks?

          # TODO: This path can be memoized
          model = super(:association_model_name).constantize
          return :destroy unless model._destroy_callbacks.empty?

          case super(:association_type)
          when :singular then :delete
          when :collection then :delete_all
          else fallback_method
          end
        end

        private

        def fallback_method
          :destroy
        end

        def defining_dependent_callbacks?
          caller.any? { |line| line.include?("active_record/associations/builder/association.rb") }
        end
      end
    end

    class BelongsToReflection < AssociationReflection
      def initialize(...)
        super(...)
        convert_options_to_dynamic_reflection_options!
      end
    end

    class HasOneReflection < AssociationReflection
      def initialize(...)
        super(...)
        convert_options_to_dynamic_reflection_options!
      end
    end

    class HasManyReflection < AssociationReflection
      def initialize(...)
        super(...)
        convert_options_to_dynamic_reflection_options!
      end
    end

    class HasAndBelongsToManyReflection < AssociationReflection
      def initialize(...)
        super(...)
        convert_options_to_dynamic_reflection_options!
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
dependent-auto-rails-0.1.7 lib/dependent-auto-rails/activerecord/reflection.rb