Sha256: 0908bafa235b8b30a07c162d9e5b62500fb3de8145b69e369e09ab6026792932

Contents?: true

Size: 1.29 KB

Versions: 5

Compression:

Stored size: 1.29 KB

Contents

module FakeFS
  # Kernel Module
  module Kernel
    @captives = { original: {}, hijacked: {} }

    class << self
      attr_accessor :captives
    end

    def self.hijack!
      captives[:hijacked].each do |name, prc|
        ::Kernel.send(:remove_method, name.to_sym)
        ::Kernel.send(:define_method, name.to_sym, &prc)
        ::Kernel.send(:private, name.to_sym)
      end
    end

    def self.unhijack!
      captives[:original].each do |name, _prc|
        ::Kernel.send(:remove_method, name.to_sym)
        ::Kernel.send(:define_method, name.to_sym, proc do |*args, **kwargs, &block|
          ::FakeFS::Kernel.captives[:original][name].call(*args, **kwargs, &block)
        end)
        ::Kernel.send(:private, name.to_sym)
      end
    end

    # NOTE: maybe private
    def self.hijack(name, &block)
      captives[:original][name] = ::Kernel.method(name.to_sym)
      captives[:hijacked][name] = block || proc { |_args| }
    end

    hijack :open do |*args, &block|
      # This is a system command     or   we're inside IRB internals
      if args.first.start_with?('|') || self.class.to_s.start_with?("IRB::")
        ::FakeFS::Kernel.captives[:original][:open].call(*args, &block)
      else
        name = args.shift
        FakeFS::File.open(name, *args, &block)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
fakefs-2.8.0 lib/fakefs/kernel.rb
fakefs-2.7.1 lib/fakefs/kernel.rb
fakefs-2.7.0 lib/fakefs/kernel.rb
fakefs-2.6.0 lib/fakefs/kernel.rb
fakefs-2.5.0 lib/fakefs/kernel.rb