dev-resources.site
for different kinds of informations.
使用序列化在兩個 Rails 站台間傳遞物件
Published at
10/21/2021
Categories
ruby
rails
serialization
Author
leon0824
Author
8 person written this
leon0824
open
一般 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
然後切換到 staging 站台,去 production 站抓檔案,反序列化後存入資料庫:
f = open('http://10.100.99.72/619204')
f = Marshal.load(f)
b = Book.new
b.attributes = f.attributes
b.save
注意,直接跑 f.save
是沒用的,一定要建新的物件再指定 attributes。
可以再驗證一下:
b.reload
b
應該就可以看到有正確存入了。
不過 Marshal 也不是萬能的,牽扯到一些 IO 操作的物件或資料庫關聯的物件就會遇到一些問題了。
serialization Article's
30 articles in total
Java interacting with Apache Avro
read article
Apache Avro
read article
Protocol Buffers as a Serialization Format
read article
WSON (Web Simple Object Notation)
read article
Serializing Python Object Using the pickle Module
read article
Converting a Unicorn project to Sitecore Content Serialization (SCS)
read article
Converting a TDS project to Sitecore Content Serialization (SCS)
read article
Deserializing Polymorphic Lists with Kotlin, Jackson, and Spring Boot
read article
Mapify-ts
read article
ProtoBuf message serialization in Akka.NET using protobuf-net
read article
Pandas Dataframe to AVRO
read article
Mapping > Json Converters // true
read article
Nested Encoding Efficency
read article
Java serialization with Avro
read article
Java Serialization with Flatbuffers
read article
Java Serialization with Protocol Buffers
read article
Serialização de Objectos
read article
Effective Java: Consider Serialization Proxies Instead of Serialized Instances
read article
Effective Java: For Instance Control, Prefer Enum types to readResolve
read article
Effective Java: Write readObject Methods Defensively
read article
Effective Java: Consider Using a Custom Serialized Form
read article
Effective Java: Prefer Alternatives To Java Serialization
read article
ASP.NET XML serialisation issues: Observations on DataContractSerializer
read article
ReScript JSON Typed Strongly
read article
使用序列化在兩個 Rails 站台間傳遞物件
currently reading
Serialização no Kotlin
read article
Working with Firebase Cloud Firestore made easier with "withConverter()"
read article
Meet Model Object Mapper, a Database Serialization Utility for Django!
read article
How to Speak Binary in TypeScript
read article
Practical Java 16 - Using Jackson to serialize Records
read article
Featured ones: