Module: Nyara::Reload

Extended by:
Reload
Included in:
Reload
Defined in:
lib/nyara/reload.rb

Overview

listen to fs events and reload code / views todo: read http://urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell/ and improve it

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#last_errorObject (readonly)

Returns the value of attribute last_error


29
30
31
# File 'lib/nyara/reload.rb', line 29

def last_error
  @last_error
end

Instance Method Details

#hook_app_reload(app_path) ⇒ Object


private +++


70
71
72
73
74
75
76
# File 'lib/nyara/reload.rb', line 70

def hook_app_reload app_path
  l = Listen.to(app_path).relative_paths(false).filter(/\.rb$/).change do |modified, added, removed|
    notify 'app-modified', (added + modified).uniq
  end
  l.start
  l
end

#hook_views_reload(views_path) ⇒ Object


78
79
80
81
82
83
84
85
# File 'lib/nyara/reload.rb', line 78

def hook_views_reload views_path
  l = Listen.to(views_path).relative_paths(true).change do |modified, added, removed|
    notify 'views-modified', (added + modified).uniq
    notify 'views-removed', removed
  end
  l.start
  l
end

#listenObject

start listening


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/nyara/reload.rb', line 32

def listen
  @port = Config['port']
  if Config['watch'] == true
    app_path = Config['root']
  else
    app_path = Config.project_path Config['watch']
  end
  views_path = Config.views_path('/', false)

  if l = Nyara.logger
    if app_path.nil?
      l.info "can't find watch path"
      return
    end

    l.info "watching app and view changes under #{app_path}"
    unless views_path.start_with?(app_path)
      l.warn "views not under project dir, changes not watched"
    end
  end
  @app_listener = hook_app_reload app_path
  @views_listener = hook_views_reload views_path
end

#load_file(file) ⇒ Object

NOTE file should end with '.rb'
returns last error


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/nyara/reload.rb', line 12

def load_file file
  verbose = $VERBOSE
  $VERBOSE = nil
  begin
    load file
    @last_error = nil
  rescue Exception
    @last_error = $!
  ensure
    $VERBOSE = verbose
  end
  if l = Nyara.logger
    if @last_error
      l.error @last_error
    end
  end
end

#notify(leader, files) ⇒ Object


87
88
89
90
91
92
93
# File 'lib/nyara/reload.rb', line 87

def notify leader, files
  return if files.empty?
  data = files.to_query('files')
  s = TCPSocket.new 'localhost', @port
  s << "POST /reload:#{leader}\r\nContent-Length: #{data.bytesize}\r\n\r\n" << data
  s.close
end

#stopObject

cleanup workers


57
58
59
60
61
62
63
64
# File 'lib/nyara/reload.rb', line 57

def stop
  if @app_listener and @app_listener.adapter.worker
    @app_listener.adapter.worker.stop
  end
  if @views_listener and @views_listener.adapter.worker
    @views_listener.adapter.worker.stop
  end
end