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)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay