rack_livereload.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. if Rails.env.development? && ENV['RAKE_LIVE_RELOAD'].present?
  2. require 'rack-livereload'
  3. # strongly inspired by https://github.com/johnbintz/rack-livereload/issues/71#issuecomment-674899405
  4. module BodyProcessorExtension
  5. def process!(env)
  6. @content_security_policy_nonce = if ActionDispatch::Request.new(env).respond_to?(:content_security_policy_nonce)
  7. ActionDispatch::Request.new(env).content_security_policy_nonce
  8. end
  9. super
  10. end
  11. def template
  12. orignal_template = ::File.read(::File.expand_path('../../../../skel/livereload.html.erb', method(:template).super_method.source_location[0]))
  13. nonced_template = orignal_template.gsub(%r{(<script type="text/javascript")}, '\1 nonce="<%= @content_security_policy_nonce %>"')
  14. ERB.new(nonced_template)
  15. end
  16. end
  17. Rack::LiveReload::BodyProcessor.prepend(BodyProcessorExtension)
  18. # Automatically inject JavaScript needed for LiveReload
  19. Rails.application.middleware.insert_after(
  20. ActionDispatch::Static,
  21. Rack::LiveReload,
  22. no_swf: true,
  23. min_delay: 500, # default 1000
  24. max_delay: 10_000, # default 60_000
  25. live_reload_port: 35_738
  26. )
  27. end