Class: Camping::Reloader::Script

Inherits:
Object
  • Object
show all
Defined in:
lib/camping/reloader.rb

Overview

This class is doing all the hard work; however, it only works on single files. Reloader just wraps up support for multiple scripts and hides away some methods you normally won’t need.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, callback = nil) ⇒ Script

Returns a new instance of Script.



43
44
45
46
47
48
49
50
51
# File 'lib/camping/reloader.rb', line 43

def initialize(file, callback = nil)
  @file = File.expand_path(file)
  @dir = File.dirname(@file)
  @extras = File.join(@dir, File.basename(@file, ".rb"))
  @mtime = Time.at(0)
  @requires = []
  @apps = {}
  @callback = callback
end

Instance Attribute Details

#appsObject (readonly)

:nodoc:



41
42
43
# File 'lib/camping/reloader.rb', line 41

def apps
  @apps
end

#dirObject (readonly)

:nodoc:



41
42
43
# File 'lib/camping/reloader.rb', line 41

def dir
  @dir
end

#extrasObject (readonly)

:nodoc:



41
42
43
# File 'lib/camping/reloader.rb', line 41

def extras
  @extras
end

#fileObject (readonly)

:nodoc:



41
42
43
# File 'lib/camping/reloader.rb', line 41

def file
  @file
end

Instance Method Details

#==(other) ⇒ Object

Checks if both scripts watches the same file.



109
110
111
# File 'lib/camping/reloader.rb', line 109

def ==(other)
  @file == other.file
end

#load_appsObject

Loads the apps availble in this script. Use apps to get the loaded apps.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/camping/reloader.rb', line 55

def load_apps
  all_requires = $LOADED_FEATURES.dup
  all_apps = Camping::Apps.dup
  
  begin
    load(@file)
  rescue Exception => e
    puts "!! Error loading #{@file}:"
    puts "#{e.class}: #{e.message}"
    puts e.backtrace
    puts "!! Error loading #{@file}, see backtrace above"
  end
  
  @requires = ($LOADED_FEATURES - all_requires).map do |req|
    full = full_path(req)
    full if full == @file or full.index(@extras) == 0
  end
  
  @mtime = mtime
  
  new_apps = (Camping::Apps - all_apps)
  old_apps = @apps.dup
  
  @apps = new_apps.inject({}) do |hash, app|
    key = app.name.to_sym
    hash[key] = app
    
    if !old_apps.include?(key)
      @callback.call(app) if @callback
      app.create if app.respond_to?(:create)
    end
    hash
  end
  
  self
end

#reload!Object

Reloads the file if needed. No harm is done by calling this multiple times, so feel free call just to be sure.



102
103
104
105
106
# File 'lib/camping/reloader.rb', line 102

def reload!
  return if @mtime >= mtime
  remove_apps
  load_apps
end

#remove_appsObject

Removes all the apps defined in this script.



93
94
95
96
97
98
# File 'lib/camping/reloader.rb', line 93

def remove_apps
  @apps.each do |name, app|
    Camping::Apps.delete(app)
    Object.send :remove_const, name
  end
end