Class: Mack::Reloader

Inherits:
Object show all
Defined in:
lib/mack/utils/reloader.rb

Overview

Mack::Reloader checks on every request, but at most every secs seconds, if a file loaded changed, and reloads it, logging to Mack.logger.debug.

Instance Method Summary collapse

Constructor Details

#initialize(app, secs = configatron.mack.reload_classes) ⇒ Reloader

Returns a new instance of Reloader.



7
8
9
10
11
# File 'lib/mack/utils/reloader.rb', line 7

def initialize(app, secs = configatron.mack.reload_classes)
  @app = app
  @secs = secs              # reload every @secs seconds max
  @last = Time.now
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/mack/utils/reloader.rb', line 13

def call(env)
  if Time.now > @last + @secs
    Thread.exclusive {
      reload!
      @last = Time.now
    }
  end

  @app.call(env)
end

#reload!Object



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
50
51
52
53
54
55
56
57
# File 'lib/mack/utils/reloader.rb', line 24

def reload!
  need_reload = $LOADED_FEATURES.find_all { |loaded|
    begin
      if loaded =~ /\A[.\/]/  # absolute filename or 1.9
        abs = loaded
      else
        if configatron.mack.deep_class_reload
          abs = $LOAD_PATH.map { |path| ::File.join(path, loaded) }.find { |file| ::File.exist? file }
        end
      end

      if abs
        ::File.mtime(abs) > @last - @secs  rescue false
      else
        false
      end
    end
  }

  need_reload.each { |l|
    $LOADED_FEATURES.delete l
  }

  need_reload.each { |to_load|
    begin
      if require to_load
        Mack.logger.debug "#{self.class}: reloaded `#{to_load}'"
      end
    rescue LoadError, SyntaxError => e
      raise e                 # Possibly ShowExceptions
    end
  }
  need_reload
end