require 'set'

module Docile
  class FallbackContextProxy
    NON_PROXIED_METHODS = Set[:object_id, :__send__, :__id__, :==, :equal?, :"!", :"!=", :instance_exec,
                              :instance_variables, :instance_variable_get, :instance_variable_set,
                              :remove_instance_variable]

    NON_PROXIED_INSTANCE_VARIABLES = Set[:@__receiver__, :@__fallback__]

    instance_methods.each do |method|
      unless NON_PROXIED_METHODS.include?(method.to_sym)
        undef_method(method)
      end
    end

    def initialize(receiver, fallback)
      @__receiver__ = receiver
      @__fallback__ = fallback
    end

    # Special case to allow proxy instance variables
    def instance_variables
      # Ruby 1.8.x returns string names, convert to symbols
      super.map(&:to_sym) - NON_PROXIED_INSTANCE_VARIABLES.to_a
    end

    def method_missing(method, *args, &block)
      __proxy_method__(method, *args, &block)
    end

    def __proxy_method__(method, *args, &block)
      begin
        @__receiver__.__send__(method.to_sym, *args, &block)
      rescue ::NoMethodError => e
        @__fallback__.__send__(method.to_sym, *args, &block)
      end
    end
  end
end

require 'set'

module Docile
  class FallbackContextProxy
    NON_PROXIED_METHODS = Set[:object_id, :__send__, :__id__, :==, :equal?, :"!", :"!=", :instance_exec,
                              :instance_variables, :instance_variable_get, :instance_variable_set,
                              :remove_instance_variable]

    NON_PROXIED_INSTANCE_VARIABLES = Set[:@__receiver__, :@__fallback__]

    instance_methods.each do |method|
      unless NON_PROXIED_METHODS.include?(method.to_sym)
        undef_method(method)
      end
    end

    def initialize(receiver, fallback)
      @__receiver__ = receiver
      @__fallback__ = fallback
    end

    # Special case to allow proxy instance variables
    def instance_variables
      # Ruby 1.8.x returns string names, convert to symbols for compatibility
      super.select { |v| !NON_PROXIED_INSTANCE_VARIABLES.include?(v.to_sym) }
    end

    def method_missing(method, *args, &block)
      __proxy_method__(method, *args, &block)
    end

    def __proxy_method__(method, *args, &block)
      begin
        @__receiver__.__send__(method.to_sym, *args, &block)
      rescue ::NoMethodError => e
        @__fallback__.__send__(method.to_sym, *args, &block)
      end
    end
  end
end

Modify 1.8.x compatibility fix to preserve original return type
Modify 1.8.x compatibility fix to preserve original return type

On 1.8.x, Object#instance_variables returns an array of strings,
whereas it is an array of symbols on later versions. This minor
change preserves that it is strings on 1.8.x
