React와 Rails 환경에서 강력한 스트리밍 기능은 부족했으며, Turbo와 같은 즉시 사용 가능한 솔루션이 없어 직접 구현하는 것은 번거롭고 오류 발생 가능성이 높았습니다. Super Turbo Streams는 이러한 문제를 해결하기 위해 Turbo Streams의 핵심 개념을 React에 적용했습니다.
Super Turbo Streams의 핵심 원리
Super Turbo Streams의 핵심은 기존 서버 측 템플릿을 재사용하여 실시간 부분 페이지 변경을 수행하는 것입니다. Turbo Streams가 HTML을 전달하는 반면, Super Turbo Streams는 JSON을 전달한다는 차이가 있습니다. 즉, _post.html.erb 대신 _post.json.props와 같은 JSON 파셜을 사용합니다.
구현 예시
Super Turbo Streams를 활용한 구현 과정은 다음과 같습니다.
1. 채널 프롭스 생성
stream_from_props를 사용하여 스트리밍 채널을 생성합니다. 이는 Turbo Streams의 turbo_stream_from에 해당하는 Superglue의 기능입니다.
ruby
# index.json.props
json.streamFromPosts stream_from_props('my_posts')
json.favPost(partial: ["post", fragment: "post-#{@post.id}"]) do
# ... 기존 내용 ...
end
json.numOfPosts Post.count
2. 파셜 및 프래그먼트 정의
부분 템플릿을 추출하고 fragment 이름을 부여합니다. 프래그먼트는 JSON을 위한 DOM ID와 유사하게, 프론트엔드에서 식별 가능한 렌더링된 파셜을 의미합니다.
ruby
# app/views/posts/_post.json.props
json.title @post.title
json.body @post.body
3. React 컴포넌트 통합
React 컴포넌트에서 useStreamSource 훅을 임포트하고 채널 프롭스를 전달하여 스트림 소스를 연결합니다.
```javascript
// app/views/posts/index.jsx
import React from ‘react’
import { useStreamSource, useContent } from ‘@thoughtbot/superglue’
export default function PostIndex() {
const { streamFromPosts, favPost, numOfPosts } = useContent()
useStreamSource(streamFromPosts) // 스트림 소스 연결
return (
<div>
<h1>{There are ${numOfPosts}}</h1>
<Post {…favPost} />
</div>
)
}
```
4. 컨트롤러/잡에서 업데이트 브로드캐스트
컨트롤러나 잡에서 broadcast_save_later_to를 사용하여 업데이트를 브로드캐스트합니다. 이는 Turbo의 broadcast_replace_later_to와 broadcast_replace_later_to를 결합한 기능입니다.
ruby
# 컨트롤러, 잡 등에서
@post.broadcast_save_later_to('my_posts', target: "post-#{@post.id}")
5. 스트리밍 응답 처리
컨트롤러 액션에서 format.json 응답 시 render layout: "stream"을 사용하여 스트림 레이아웃을 렌더링하고, 뷰에서 broadcast_save_props를 통해 업데이트를 브로드캐스트할 수 있습니다.
```ruby
# 컨트롤러 액션 예시
def update
# …
if @post.save
respond_to do |format|
format.html { redirect_to posts_path, notice: “Successfully updated” }
format.json {
flash.now[:notice] = “Successfully submitted”
render layout: “stream” # 스트림 레이아웃 자동 생성
}
end
else
redirect_to posts_path, alert: “Could not update”
end
end
update.json.props 뷰
broadcast_save_props(model: @post, target: “post-#{@post.id}”) ```
현재 상태 및 향후 계획
Superglue 2.0 Alpha는 현재 개발 초기 단계이며 API 변경 가능성이 있습니다. 현재 Super Turbo Streams는 prepend, append, save, refresh의 4가지 액션만 지원하지만, 향후 확장될 예정입니다. 또한, 2.0 버전은 프래그먼트 개념을 재정의하여 1.0 버전과 하위 호환성이 없으므로, 주요 릴리스에서 마이그레이션 계획이 제공될 예정입니다.