rails-hotwire

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Community Rails Hotwire Best Practices

社区版Rails Hotwire最佳实践

Comprehensive guide for building interactive Rails applications with Hotwire (Turbo + Stimulus), maintained by Community. Contains 53 rules across 9 categories, prioritized by impact to guide automated refactoring and code generation. Follows the DHH "One Person Framework" philosophy: the server renders HTML, Turbo makes it feel like an SPA, Stimulus adds the sprinkle of JS where needed.
这是由社区维护的、使用Hotwire(Turbo + Stimulus)构建交互式Rails应用的综合指南。包含9个类别共53条规则,按影响优先级排序,可指导自动化重构和代码生成。遵循DHH提出的"单人框架"理念:由服务器渲染HTML,Turbo让应用拥有类SPA的体验,Stimulus在需要的地方添加少量JS代码。

When to Apply

适用场景

Reference these guidelines when:
  • Configuring Turbo Drive navigation, prefetching, and caching behavior
  • Adding Turbo Frames for partial page updates and lazy loading
  • Delivering Turbo Streams for surgical DOM mutations
  • Broadcasting real-time updates over ActionCable
  • Enabling Turbo 8 morphing for page refreshes
  • Writing Stimulus controllers for client-side behavior
  • Handling errors in Turbo navigation, frames, and WebSocket connections
  • Choosing between Drive, Frames, Streams, Morphing, and Stimulus
  • Testing Hotwire interactions in system and integration tests
在以下场景中参考这些指南:
  • 配置Turbo Drive导航、预加载和缓存行为
  • 添加Turbo Frames实现页面局部更新和懒加载
  • 通过Turbo Streams实现精准的DOM变更
  • 基于ActionCable推送实时更新
  • 启用Turbo 8 morphing实现页面刷新
  • 编写Stimulus控制器处理客户端行为
  • 处理Turbo导航、Frames和WebSocket连接中的错误
  • 在Drive、Frames、Streams、Morphing和Stimulus之间做技术选型
  • 在系统测试和集成测试中验证Hotwire交互逻辑

Rule Categories by Priority

按优先级划分的规则类别

PriorityCategoryImpactPrefix
1Navigation & DriveCRITICAL
drive-
2Turbo FramesCRITICAL
frame-
3Turbo StreamsHIGH
stream-
4Broadcasting & Real-TimeHIGH
bcast-
5Morphing & Page RefreshHIGH
morph-
6Performance OptimizationMEDIUM-HIGH
perf-
7Stimulus PatternsMEDIUM-HIGH
stim-
8Architecture DecisionsMEDIUM
arch-
9Testing HotwireMEDIUM
test-
优先级类别影响程度前缀
1导航与Turbo Drive关键
drive-
2Turbo Frames关键
frame-
3Turbo Streams
stream-
4广播与实时功能
bcast-
5Morphing与页面刷新
morph-
6性能优化中高
perf-
7Stimulus模式中高
stim-
8架构决策
arch-
9Hotwire测试
test-

Quick Reference

快速参考

1. Navigation & Drive (CRITICAL)

1. 导航与Turbo Drive(关键)

  • drive-prefetch-links
    - Enable link prefetching for instant navigation
  • drive-form-submissions
    - Use Turbo Drive for form submissions
  • drive-visit-actions
    - Control history with visit actions
  • drive-cache-control
    - Configure Turbo cache for preview pages
  • drive-selective-disable
    - Disable Turbo Drive on incompatible pages
  • drive-progress-bar
    - Customize the Turbo progress bar
  • drive-confirm-dialog
    - Use data-turbo-confirm for destructive actions
  • drive-error-recovery
    - Handle Turbo navigation and fetch errors gracefully
  • drive-prefetch-links
    - 启用链接预加载以实现即时导航
  • drive-form-submissions
    - 使用Turbo Drive处理表单提交
  • drive-visit-actions
    - 通过visit操作控制历史记录
  • drive-cache-control
    - 为预览页面配置Turbo缓存
  • drive-selective-disable
    - 在不兼容的页面禁用Turbo Drive
  • drive-progress-bar
    - 自定义Turbo进度条
  • drive-confirm-dialog
    - 使用data-turbo-confirm处理破坏性操作
  • drive-error-recovery
    - 优雅处理Turbo导航和请求错误

2. Turbo Frames (CRITICAL)

2. Turbo Frames(关键)

  • frame-lazy-loading
    - Defer frame loading until viewport entry
  • frame-scope-navigation
    - Scope navigation within frames
  • frame-src-navigation
    - Use src for dynamic frame content
  • frame-break-out
    - Handle frame breakout for redirects
  • frame-promote-visits
    - Promote frame navigation to page visits
  • frame-dom-id
    - Use dom_id for frame identification
  • frame-empty-state
    - Provide meaningful frame loading states
  • frame-lazy-loading
    - 延迟加载Frame直到进入视口
  • frame-scope-navigation
    - 限定Frame内的导航范围
  • frame-src-navigation
    - 使用src加载动态Frame内容
  • frame-break-out
    - 处理Frame跳转时的突破逻辑
  • frame-promote-visits
    - 将Frame导航升级为页面级导航
  • frame-dom-id
    - 使用dom_id标识Frame
  • frame-empty-state
    - 提供有意义的Frame加载状态

3. Turbo Streams (HIGH)

3. Turbo Streams(高)

  • stream-progressive-enhance
    - Always provide HTML fallback for streams
  • stream-action-selection
    - Choose the right stream action for DOM mutations
  • stream-multi-target
    - Use targets for multi-element updates
  • stream-http-delivery
    - Deliver streams via HTTP for form responses
  • stream-websocket-source
    - Connect WebSocket sources in the body
  • stream-custom-actions
    - Register custom stream actions for complex DOM updates
  • stream-progressive-enhance
    - 始终为Streams提供HTML降级方案
  • stream-action-selection
    - 为DOM变更选择合适的Stream操作
  • stream-multi-target
    - 使用targets实现多元素更新
  • stream-http-delivery
    - 通过HTTP交付Streams作为表单响应
  • stream-websocket-source
    - 在页面body中连接WebSocket源
  • stream-custom-actions
    - 注册自定义Stream操作处理复杂DOM更新

4. Broadcasting & Real-Time (HIGH)

4. 广播与实时功能(高)

  • bcast-model-broadcasts
    - Use broadcasts_refreshes for simple model updates
  • bcast-debounce-n1
    - Debounce broadcasts to prevent N+1 broadcast storms
  • bcast-scope-streams
    - Scope broadcast streams to accounts or users
  • bcast-refresh-over-replace
    - Prefer broadcast refresh over granular stream updates
  • bcast-avoid-view-logic-in-models
    - Keep broadcasting logic out of models
  • bcast-signed-stream-names
    - Use signed stream names for security
  • bcast-reconnect-handling
    - Handle WebSocket disconnection and reconnection
  • bcast-model-broadcasts
    - 使用broadcasts_refreshes处理简单模型更新
  • bcast-debounce-n1
    - 防抖广播以避免N+1广播风暴
  • bcast-scope-streams
    - 按账户或用户范围隔离广播流
  • bcast-refresh-over-replace
    - 优先使用广播刷新而非细粒度Stream更新
  • bcast-avoid-view-logic-in-models
    - 避免在模型中编写广播逻辑
  • bcast-signed-stream-names
    - 使用签名流名称保障安全
  • bcast-reconnect-handling
    - 处理WebSocket断开与重连

5. Morphing & Page Refresh (HIGH)

5. Morphing与页面刷新(高)

  • morph-enable-page-refresh
    - Enable morphing for page refreshes
  • morph-permanent-elements
    - Mark stateful elements as permanent
  • morph-scroll-preservation
    - Preserve scroll position during morphing
  • morph-stimulus-reconnect
    - Handle Stimulus controller reconnection after morph
  • morph-frame-refresh
    - Use refresh='morph' on frames for additive content
  • morph-vs-streams
    - Choose morphing over complex stream orchestration
  • morph-enable-page-refresh
    - 启用morphing实现页面刷新
  • morph-permanent-elements
    - 将有状态元素标记为永久保留
  • morph-scroll-preservation
    - 在morphing期间保留滚动位置
  • morph-stimulus-reconnect
    - 处理morph后Stimulus控制器的重连
  • morph-frame-refresh
    - 在Frames上使用refresh='morph'加载增量内容
  • morph-vs-streams
    - 优先选择morphing而非复杂Stream编排

6. Performance Optimization (MEDIUM-HIGH)

6. 性能优化(中高)

  • perf-optimistic-ui
    - Implement optimistic UI updates before server confirmation
  • perf-batch-streams
    - Batch multiple stream updates into single responses
  • perf-frame-caching
    - Cache Turbo Frame responses with fragment caching
  • perf-prefetch-strategic
    - Disable prefetch on expensive endpoints
  • perf-memory-leak-prevention
    - Clean up subscriptions and event listeners
  • perf-optimistic-ui
    - 在服务器确认前实现乐观UI更新
  • perf-batch-streams
    - 将多个Stream更新批量为单个响应
  • perf-frame-caching
    - 使用片段缓存缓存Turbo Frame响应
  • perf-prefetch-strategic
    - 在高开销端点禁用预加载
  • perf-memory-leak-prevention
    - 清理订阅和事件监听器以避免内存泄漏

7. Stimulus Patterns (MEDIUM-HIGH)

7. Stimulus模式(中高)

  • stim-outlets-communication
    - Use outlets for cross-controller communication
  • stim-values-reactive-state
    - Use Values API for reactive controller state
  • stim-action-descriptors
    - Use declarative action descriptors over addEventListener
  • stim-small-reusable-controllers
    - Keep Stimulus controllers small and reusable
  • stim-outlets-communication
    - 使用outlets实现控制器间通信
  • stim-values-reactive-state
    - 使用Values API实现响应式控制器状态
  • stim-action-descriptors
    - 使用声明式action描述符替代addEventListener
  • stim-small-reusable-controllers
    - 保持Stimulus控制器小巧且可复用

8. Architecture Decisions (MEDIUM)

8. 架构决策(中)

  • arch-progressive-enhancement
    - Follow the progressive enhancement hierarchy
  • arch-frame-vs-stream-decision
    - Use frames for scoped navigation, streams for multi-target updates
  • arch-importmap-management
    - Pin JavaScript dependencies with import maps
  • arch-avoid-client-state
    - Keep state on the server, not the client
  • arch-stimulus-boundaries
    - Use Stimulus only for client-side behavior
  • arch-progressive-enhancement
    - 遵循渐进式增强原则
  • arch-frame-vs-stream-decision
    - 使用Frames处理范围导航,使用Streams处理多目标更新
  • arch-importmap-management
    - 使用import maps管理JavaScript依赖
  • arch-avoid-client-state
    - 将状态保存在服务器而非客户端
  • arch-stimulus-boundaries
    - 仅使用Stimulus处理客户端行为

9. Testing Hotwire (MEDIUM)

9. Hotwire测试(中)

  • test-system-test-async
    - Wait for Turbo updates in system tests
  • test-stream-assertions
    - Use Turbo Stream test helpers in integration tests
  • test-broadcast-assertions
    - Assert broadcasts with Turbo test helpers
  • test-frame-navigation
    - Test frame navigation with scoped assertions
  • test-websocket-timing
    - Handle WebSocket connection timing in system tests
  • test-system-test-async
    - 在系统测试中等待Turbo更新
  • test-stream-assertions
    - 在集成测试中使用Turbo Stream测试助手
  • test-broadcast-assertions
    - 使用Turbo测试助手断言广播逻辑
  • test-frame-navigation
    - 使用范围断言测试Frame导航
  • test-websocket-timing
    - 在系统测试中处理WebSocket连接时序

How to Use

使用方法

Read individual reference files for detailed explanations and code examples:
  • Section definitions - Category structure and impact levels
  • Rule template - Template for adding new rules
阅读单个参考文件获取详细说明和代码示例:
  • 章节定义 - 类别结构和影响级别说明
  • 规则模板 - 添加新规则的模板

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions and ordering
assets/templates/_template.mdTemplate for new rules
metadata.jsonVersion and reference information
文件描述
references/_sections.md类别定义和排序规则
assets/templates/_template.md新规则模板
metadata.json版本和参考信息