aboutsummaryrefslogblamecommitdiffstats
path: root/activerecord/lib/arel/visitors/visitor.rb
blob: 1c17184e869a636b70514a36b35bf0a98f4b2ee0 (plain) (tree)
1
2
3
4
5
6
7
8
9
                             
 
                         

                 
                    


                                      
                               
                           



             
                             
 



                                                                       
           
 


                                   
 











                                                                            


       
# frozen_string_literal: true

module Arel # :nodoc: all
  module Visitors
    class Visitor
      def initialize
        @dispatch = get_dispatch_cache
      end

      def accept(object, *args)
        visit object, *args
      end

      private

        attr_reader :dispatch

        def self.dispatch_cache
          Hash.new do |hash, klass|
            hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}"
          end
        end

        def get_dispatch_cache
          self.class.dispatch_cache
        end

        def visit(object, *args)
          dispatch_method = dispatch[object.class]
          send dispatch_method, object, *args
        rescue NoMethodError => e
          raise e if respond_to?(dispatch_method, true)
          superklass = object.class.ancestors.find { |klass|
            respond_to?(dispatch[klass], true)
          }
          raise(TypeError, "Cannot visit #{object.class}") unless superklass
          dispatch[object.class] = dispatch[superklass]
          retry
        end
    end
  end
end