aboutsummaryrefslogtreecommitdiffstats
path: root/lib/arel/visitors/visitor.rb
blob: 2152da9f0538f75a63bc68e1666b877c1bc28932 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
module Arel
  module Visitors
    class Visitor
      def initialize
        @dispatch = get_dispatch_cache
      end

      def accept object
        visit object
      end

      private

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

        # pre-populate cache. FIXME: this should be passed in to each
        # instance, but we can do that later.
        self.class.private_instance_methods.sort.each do |name|
          next unless name =~ /^visit_(.*)$/
          dispatch[$1.gsub('_', '::')] = name
        end
        dispatch
      end

      def get_dispatch_cache
        self.class.dispatch_cache
      end

      def dispatch
        @dispatch
      end

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