Logo de Rails Hotwire Realtime

Rails Hotwire Realtime

Comunidade
marckohlbrugge
rails-hotwire-realtime

Apply Hotwire, Turbo, Stimulus, and ActionCable best practices for real-time Rails interfaces. Use when building Turbo Streams/Frames, Stimulus interactions, or websocket-driven updates.

Add to TypingMind

Visão geral

Publicado pormarckohlbrugge
Repositório37signals-skills
Nome da habilidaderails-hotwire-realtime
Estrelas
724
Forks
56
Arquivos incluídos
Somente instruções
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Sem arquivos extras

    Tudo de que o modelo precisa está nas instruções — sem arquivos extras para sincronizar.

  • Código aberto

    Publicada por marckohlbrugge no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Rails Hotwire Realtime no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/marckohlbrugge/37signals-skills/tree/main/skills/rails-hotwire-realtime
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/marckohlbrugge/37signals-skills.git /tmp/37signals-skills
mkdir -p .claude/skills
cp -r /tmp/37signals-skills/skills/rails-hotwire-realtime .claude/skills/rails-hotwire-realtime
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Rails Hotwire Realtime em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Rails Hotwire Realtime automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Rails Hotwire Realtime não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Rails Hotwire + Realtime

Use for Turbo/Stimulus/ActionCable architecture and reviews. Patterns from Campfire (cable-heavy chat) and Fizzy (streams-only kanban).

Choose the Right Realtime Architecture

Two proven 37signals topologies:

  • Streams-only (Fizzy): no custom ActionCable channels at all. turbo_stream_from, broadcasts_refreshes + morph, lazy frames with ETags. Default to this for CRUD-ish apps.
  • Cable-augmented (Campfire): custom channels only for lightweight JSON signals (presence, typing, unread pings) where rendering HTML server-side would be wasteful. Durable DOM state still goes through Turbo Streams.

Rule of thumb: Turbo Streams for anything that changes the DOM; bare ActionCable only for tiny ephemeral signals.

Turbo Defaults

  • Prefer server-rendered partial updates over heavy client-side state systems.
  • Set global morph refresh in the layout: turbo_refreshes_with method: :morph, scroll: :preserve.
  • Use Turbo Streams for targeted updates; one action can render a multi-target stream template that updates every affected region atomically (source column + destination + detail pane).
  • Lazy-load expensive sections with turbo_frame_tag ..., src:, loading: :lazy and give the frame endpoint its own fresh_when ETag. Extract frequently-changing fragments into their own frames so they don't bust the parent cache.
  • Use data-turbo-permanent for elements that must survive navigation/morph (footer trays, in-progress editors).
  • Block morph from clobbering client-owned state (e.g. localStorage-driven collapsed columns) via turbo:before-morph-attribute + preventDefault().
  • Exempt realtime-heavy pages from Turbo's page cache (turbo_exempts_page_from_cache); rely on frame-level ETags instead.
  • Optimistic UI without a JS framework: server-render a <template> partial with $placeholder$ tokens; client clones it with a generated ID before submit; the stream response replaces it.

Broadcast Patterns

  • Keep broadcast logic on models (Message::Broadcasts concern with broadcast_create), not in controllers.
  • Scope every stream name by tenant/user: [board.account, :all_boards], [user, :notifications] — stream names are isolation boundaries.
  • Dual streams when needed: broadcasts_refreshes for direct subscribers plus broadcasts_refreshes_to ->(r) { [r.account, :aggregate_view] } for account-wide views.
  • Gate noisy secondary broadcasts on meaningful change: set a flag in before_update when preview-relevant fields change; broadcast if: :preview_changed?.
  • Suppress broadcasts in background jobs that incidentally touch records (Model.suppressing_turbo_broadcasts), e.g. around ActiveStorage analysis.
  • Fan-out efficiently: render_to_string once, then broadcast_replace_to user, ..., html: per recipient.
  • Use broadcast_*_later async variants when synchronous broadcasting hurts request latency.
  • Broadcast-rendered partials lack request context: wrap attachment/url helpers (broadcast_image_tag pattern) so URLs resolve.

Reconnect & Catch-Up

  • Catch-up over reload: on reconnect/tab-return, fetch a turbo-stream diff (?since=<epoch_ms>); server appends new records and replaces updated ones.
  • An empty HeartbeatChannel gives reliable connected/disconnected callbacks for triggering catch-up and a debounced offline UI.
  • Guard Stimulus connect() with a turbo-preview check so back/forward cache previews don't open sockets or request permissions.

Stimulus Defaults

  • Keep controllers single-purpose; compose multiple small controllers on one element.
  • Prefer targets/values over ad-hoc selectors and attribute parsing.
  • Always clean up timers/listeners/subscriptions in disconnect. For cable subscriptions, defer unsubscribe one animation frame and skip if the element reconnected (morph churn).
  • Use event dispatch between controllers (or outlets) instead of tight coupling.
  • For complex surfaces, compose data-controller/data-action/target wiring in Ruby helpers (message_area_tag) so views stay declarative and the contract lives in one place.
  • Read page context from <meta> tags into a tiny window.Current object rather than inlining JSON.
  • Will elements added later via broadcast get the behavior? Design controllers to handle dynamically-inserted children (e.g. targetConnected callbacks).

Scroll & Interaction Contracts

  • Preserve scroll declaratively: pass a custom attribute (maintain_scroll: true) on broadcasts and handle it once in a turbo:before-stream-render listener.
  • Serialize competing scroll mutations through a promise queue when streams and optimistic inserts race.
  • Strip a stream target's id on turbo:submit-start so background broadcasts can't race the form's own stream response.
  • Infinite feeds: IntersectionObserver sentinels in turbo-stream pagination (remove trigger, append batch, append new sentinel); cap DOM size; only autoscroll when the user is at the latest page.

ActionCable / Connection Safety

  • Authenticate in Connection#connect with the same identity resolution as HTTP; scope channel subscriptions through ownership (current_user.rooms.find_by(id: params[:room_id])).
  • Disconnect deactivated/banned users remotely: ActionCable.server.remote_connections.where(current_user: user).disconnect.
  • Presence: reference-count connections with a TTL (connections counter + connected_at, 60s freshness scope) to survive multi-tab and reconnects; debounce visibility changes (~5s) to avoid flicker.
  • Under path-based tenancy, emit the cable URL from request.script_name via a custom meta tag helper.

Caching + Realtime

  • Keep cache keys aligned with what affects output (record, user, timezone, filter state); use touch: true chains so child edits invalidate parents.
  • Personalize cached fragments client-side: render data-creator-id, let a Stimulus controller compare against Current.user and toggle visibility — don't break fragment caching for per-user toggles.
  • Avoid HTTP-caching form pages where token freshness is critical.

Web Push (when applicable)

  • Push only to disconnected users, excluding the actor; respect per-user involvement levels (everything vs mentions-only).
  • Deliver via a thread pool with persistent HTTP connections, resolving all AR data before posting to threads; invalidate expired subscriptions async.
  • Clean up the push subscription client-side on logout.

Testing

  • Model broadcasts: assert_turbo_stream_broadcasts([user, :notifications], count: 1) { ... } and assert_no_turbo_stream_broadcasts for negatives.
  • Controller responses: as: :turbo_stream + assert_turbo_stream action: :replace, target: dom_id(...).
  • For DOM-level assertions on broadcasts, a small helper reading ActionCable.server.pubsub.broadcasts + assert_select covers it.
  • System tests: using_session("OtherUser") for multi-user realtime, and wait for turbo-cable-stream-source[connected] before asserting.

Red Flags

  • Duplicate stream IDs/targets causing unstable updates.
  • Broadcast channels or stream names that are not tenant/user-scoped.
  • HTML rendering inside bare ActionCable channels (use Turbo Streams).
  • Stimulus controllers leaking timers/listeners after navigation.
  • Replacing full pages for small interactions that should be streamed.
  • Custom ActionCable channels for things turbo_stream_from already does.
  • Morph refreshes destroying in-progress user input (missing data-turbo-permanent).

Perguntas frequentes

O que a habilidade de IA Rails Hotwire Realtime faz?

Apply Hotwire, Turbo, Stimulus, and ActionCable best practices for real-time Rails interfaces. Use when building Turbo Streams/Frames, Stimulus interactions, or websocket-driven updates.

Por que usar Rails Hotwire Realtime no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Rails Hotwire Realtime é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Rails Hotwire Realtime no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/marckohlbrugge/37signals-skills/tree/main/skills/rails-hotwire-realtime. O TypingMind lê o arquivo SKILL.md e instala a habilidade para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Rails Hotwire Realtime?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Rails Hotwire Realtime?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Rails Hotwire Realtime com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Rails Hotwire Realtime é gratuita?

A habilidade é publicada no GitHub por marckohlbrugge. Consulte os termos de licenciamento no repositório. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇