Sha256: 613d2b1212ec4067eb4653475cbc7df89f4850a4147580f90d94e487aca79004

Contents?: true

Size: 1.56 KB

Versions: 4

Compression:

Stored size: 1.56 KB

Contents

module Simple::Httpd::Reloader
  def self.attach(target, paths:, reloading_instance: target)
    target.extend self
    target.load!(paths: paths, reloading_instance: reloading_instance)
    target
  end

  H = ::Simple::Httpd::Helpers

  attr_accessor :reloading_paths

  def load!(paths:, reloading_instance:)
    paths = Array(paths)
    paths = nil if paths.empty?

    @__reload_paths__ = paths
    @__reloading_instance__ = reloading_instance

    reload_all_changed_files
  end

  def reload!
    # if this is a class, and its superclass is also reloadable,
    # reload the superclass first.
    if respond_to?(:superclass) && superclass&.respond_to?(:reload!)
      superclass.reload!
    end

    reload_all_changed_files
  end

  private

  def reload_all_changed_files
    return unless @__reload_paths__

    @__reload_paths__.each do |path|
      reload_file_if_necessary(path)
    end
  end

  def reload_file_if_necessary(path)
    @__source_mtimes_by_path__ ||= {}

    mtime = File.mtime(path)
    return if @__source_mtimes_by_path__[path] == mtime

    Simple::Httpd.logger.debug do
      verb = @__source_mtimes_by_path__.key?(path) ? "reloading" : "loading"
      "#{verb} #{H.shorten_path path}"
    end

    silence_warnings do
      if @__reloading_instance__
        @__reloading_instance__.instance_eval File.read(path), path, 1
      else
        load path
      end
    end

    @__source_mtimes_by_path__[path] = mtime
  end

  def silence_warnings(&block)
    _ = block

    warn_level = $VERBOSE
    $VERBOSE = nil
    yield
  ensure
    $VERBOSE = warn_level
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
simple-httpd-0.4.3 lib/simple/httpd/reloader.rb
simple-httpd-0.4.2 lib/simple/httpd/reloader.rb
simple-httpd-0.4.1 lib/simple/httpd/reloader.rb
simple-httpd-0.4.0 lib/simple/httpd/reloader.rb