Module: Staticky::ServerPlugins::LiveReloading
- Defined in:
- lib/staticky/server_plugins/live_reloading.rb
Class Method Summary collapse
-
.setup_live_reload(app) ⇒ Object
rubocop:disable Metrics.
Class Method Details
.setup_live_reload(app) ⇒ Object
rubocop:disable Metrics
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 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 |
# File 'lib/staticky/server_plugins/live_reloading.rb', line 6 def self.setup_live_reload(app) # rubocop:disable Metrics sleep_interval = 0.5 file_to_check = Staticky.build_path.join("index.html") errors_file = Staticky.build_path.join("errors.json") app.request.get "_staticky/live_reload" do # rubocop:disable Metrics/BlockLength @_mod = if Staticky.files.exist?(file_to_check) file_to_check.mtime.to_i else 0 end event_stream = proc do |stream| Thread.new do loop do new_mod = if Staticky.files.exist?(file_to_check) file_to_check.mtime.to_i else 0 end if @_mod < new_mod stream.write "data: reloaded!\n\n" break elsif Staticky.files.exist?(errors_file) stream.write "event: builderror\n" \ "data: #{errors_file.read.to_json}\n\n" else stream.write "data: #{new_mod}\n\n" end sleep sleep_interval rescue Errno::EPIPE # User refreshed the page break end ensure stream.close end end app.request.halt [ 200, { "Content-Type" => "text/event-stream", "cache-control" => "no-cache" }, event_stream ] end end |