Logo

dev-resources.site

for different kinds of informations.

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

Published at
10/21/2021
Categories
ruby
rails
serialization
Author
leon0824
Categories
3 categories in total
ruby
open
rails
open
serialization
open
Author
8 person written this
leon0824
open
使用序列化在兩個 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 操作的物件或資料庫關聯的物件就會遇到一些問題了。

serialization Article's
30 articles in total
Favicon
Java interacting with Apache Avro
Favicon
Apache Avro
Favicon
Protocol Buffers as a Serialization Format
Favicon
WSON (Web Simple Object Notation)
Favicon
Serializing Python Object Using the pickle Module
Favicon
Converting a Unicorn project to Sitecore Content Serialization (SCS)
Favicon
Converting a TDS project to Sitecore Content Serialization (SCS) 
Favicon
Deserializing Polymorphic Lists with Kotlin, Jackson, and Spring Boot
Favicon
Mapify-ts
Favicon
ProtoBuf message serialization in Akka.NET using protobuf-net
Favicon
Pandas Dataframe to AVRO
Favicon
Mapping > Json Converters // true
Favicon
Nested Encoding Efficency
Favicon
Java serialization with Avro
Favicon
Java Serialization with Flatbuffers
Favicon
Java Serialization with Protocol Buffers
Favicon
Serialização de Objectos
Favicon
Effective Java: Consider Serialization Proxies Instead of Serialized Instances
Favicon
Effective Java: For Instance Control, Prefer Enum types to readResolve
Favicon
Effective Java: Write readObject Methods Defensively
Favicon
Effective Java: Consider Using a Custom Serialized Form
Favicon
Effective Java: Prefer Alternatives To Java Serialization
Favicon
ASP.NET XML serialisation issues: Observations on DataContractSerializer
Favicon
ReScript JSON Typed Strongly
Favicon
使用序列化在兩個 Rails 站台間傳遞物件
Favicon
Serialização no Kotlin
Favicon
Working with Firebase Cloud Firestore made easier with "withConverter()"
Favicon
Meet Model Object Mapper, a Database Serialization Utility for Django!
Favicon
How to Speak Binary in TypeScript
Favicon
Practical Java 16 - Using Jackson to serialize Records

Featured ones: