Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Last active April 5, 2024 08:32
Show Gist options
  • Save Burgestrand/216d78b525fa9f49fb04f53fd21fd3cf to your computer and use it in GitHub Desktop.
Save Burgestrand/216d78b525fa9f49fb04f53fd21fd3cf to your computer and use it in GitHub Desktop.
A custom livereload using Turbo 8 morph, Turbo Stream, and Listen.
<!DOCTYPE html>
<html>
<head>
<%= action_cable_meta_tag %>
<%= turbo_refreshes_with method: :morph, scroll: :preserve if Rails.env.development? %>
<%= yield :head # turbo_refreshes_with provides :head %>
<!-- JS include tag for Turbo 8 -->
</head>
<body>
<%= turbo_stream_from :livereload, channel: LivereloadChannel if Rails.env.development? %>
</body>
</html>
require_relative "../config/environment"
# This is key, to keep the websocket connection stable in development. Without it, the server restarts on change.
Rails.application.config.enable_reloading = false
Rails.application.eager_load!
run ActionCable.server
Rails.application.configure do
config.action_cable.mount_path = nil
config.action_cable.url = "ws://localhost:28080" # use wss:// in production
end
# frozen_string_literal: true
class LivereloadChannel < ApplicationCable::Channel
extend Turbo::Streams::Broadcasts
extend Turbo::Streams::StreamName
include Turbo::Streams::ActionHelper
include Turbo::Streams::StreamName::ClassMethods
PATHS = %w[
app/models
app/views
app/helpers
app/assets/builds
config/locales
].freeze
def subscribed
@listener = Listen.to(*PATHS.map { Rails.root.join(_1) }) do
logger.info "LivereloadChannel: refreshing"
transmit turbo_stream_refresh_tag
end
@listener.start
logger.info "LivereloadChannel: subscribed"
end
def unsubscribed
logger.info "LivereloadChannel: unsubscribed"
@listener.stop
end
end
cable: WEB_CONCURRENCY=0 PORT=28080 bundle exec puma config/cable.ru
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment