DEV Community

Cover image for 使用序列化在兩個 Rails 站台間傳遞物件
Leon
Leon

Posted on • Originally published at editor.leonh.space

3 1

使用序列化在兩個 Rails 站台間傳遞物件

一般 REST API 傳遞大多是用 HTTP post 發送 JSON、YAML、XML,不過這裡講的不是 client - server 的傳遞,而是 server - server 的傳遞,情境是 production 站與 staging 站間的物件傳遞,雖然說 Rails 有 seed 可以用來建資料,不過有時候開發上還是需要拿一些比較真實的資料來驗證,或者單純因為懶惰。

簡單解釋做法,就是把 production 上的物件序列化成檔案,再從 staging 站台抓下來還原城物件。在 Ruby 的世界,已經內建有 Marshal 模組來做序列化的工作,並且使用簡易。

練習隨機挑一個 book 物件,使用 Marshal 把它序列化後存到 Rails 的 public 位置:

b = Book.find(Book.ids.sample(1)[0])
File.open(Rails.public_path.join(Book.id, 'wb+') do |f|
  f.write(Marshal.dump(b))
end
Enter fullscreen mode Exit fullscreen mode

然後切換到 staging 站台,去 production 站抓檔案,反序列化後存入資料庫:

f = open('http://10.100.99.72/619204')
f = Marshal.load(f)

b = Book.new
b.attributes = f.attributes
b.save
Enter fullscreen mode Exit fullscreen mode

注意,直接跑 f.save 是沒用的,一定要建新的物件再指定 attributes。

可以再驗證一下:

b.reload
b
Enter fullscreen mode Exit fullscreen mode

應該就可以看到有正確存入了。

不過 Marshal 也不是萬能的,牽扯到一些 IO 操作的物件或資料庫關聯的物件就會遇到一些問題了。

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

AWS GenAI Live!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️