X_AJ_X

Formatted article

Oct 4th, 2024 (edited)
542
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.96 KB | None | 0 0
  1. Serialization is one of those things you can easily do without until all of a sudden you really need it one day. That’s pretty much how it went with me. I was happily using and learning Ruby for months before I ever ran into a situation where serializing a few objects really would have made my life easier. Even then I avoided looking into it, you can very easily convert the important data from an object into a string and write that out to a file. Then when you need to, you just read the file, parse the string and recreate the object, what could be simpler? Of course, it could be much simpler indeed, especially when you’re dealing with a deep hierarchy of objects. I think being weaned on languages like Java, **you come to expect operations like serialization to be non-trivial** . Don’t get me wrong, it is not really difficult in Java, but neither is it simple and if you want your serialized object to be human-readable, then you’re into 3rd party library land and things can get easier or harder depending on your needs. Suffice to say, bad experiences in the past don’t fill you with a lot of enthusiasm for the future.
  2.  
  3. When I started looking into serialization in Ruby, I fully expected to have to look into 3rd party solutions – surely the serialization mechanisms built into the language couldn’t possibly, easily fit my needs. As usual, I was pleasantly surprised. Now, like [that proverbial hammer](https://en.wikipedia.org/wiki/Law_of_the_instrument) , serialization seems to be useful all the time :). Anyway, I’ll let you judge for yourself, let’s take a look at the best and most common options you have, when it comes to serialization with Ruby.
  4. ## Human-Readable Objects
  5.  
  6. Ruby has two object serialization mechanisms built right into the language. One is used to serialize into a human readable format, the other into a binary format. I will look into the binary one shortly, but for now let’s focus on human readable. Any object you create in Ruby can be serialized into <em>YAML</em> format, with pretty much no effort needed on your part. Let’s make some objects:
  7.  
  8.  
  9. ```ruby
  10. require "yaml"
  11.  
  12. class A
  13. def initialize(string, number)
  14. @string = string
  15. @number = number
  16. end
  17.  
  18. def to_s
  19. "In A:\n #{@string}, #{@number}\n"
  20. end
  21. end
  22.  
  23. class B
  24. def initialize(number, a_object)
  25. @number = number
  26. @a_object = a_object
  27. end
  28.  
  29. def to_s
  30. "In B: #{@number} \n #{@a_object.to_s}\n"
  31. end
  32. end
  33.  
  34. class C
  35. def initialize(b_object, a_object)
  36. @b_object = b_object
  37. @a_object = a_object
  38. end
  39.  
  40. def to_s
  41. "In C:\n #{@a_object} #{@b_object}\n"
  42. end
  43. end
  44.  
  45. a = A.new("hello world", 5)
  46. b = B.new(7, a)
  47. c = C.new(b, a)
  48.  
  49. puts c
  50. ```
  51. Since we created a to_s, method, we can see the string representation of our object tree:
  52. ```yaml
  53. In C:
  54. In A:
  55. hello world, 5
  56. In B: 7
  57. In A:
  58. hello world, 5
  59. ```
  60. To serialize our object tree we simply do the following:
  61.  
  62. ```ruby
  63. serialized_object = YAML::dump(c)
  64. puts serialized_object
  65. ```
  66.  
  67. Our serialized object looks like this:
  68. ```yaml
  69. --- !ruby/object:C
  70. a_object: &id001 !ruby/object:A
  71. number: 5
  72. string: hello world
  73. b_object: !ruby/object:B
  74. a_object: *id001
  75. number: 7
  76. ```
  77. If we now want to get it back:
  78.  
  79. ```ruby
  80. puts YAML::load(serialized_object)
  81. ```
  82.  
  83. This produces output which is exactly the same as what we had above, which means our object tree was reproduced correctly:
  84. ```yaml
  85. In C:
  86. In A:
  87. hello world, 5
  88. In B: 7
  89. In A:
  90. hello world, 5
  91. ```
  92. Of course **you almost never want to serialize just one object**, it is usually an array or a hash. In this case you have two options, either you serialize the whole array/hash in one go, or you serialize each value separately. The rule here is simple, if you always need to work with the whole set of data and never parts of it, just write out the whole array/hash, otherwise, iterate over it and write out each object. The reason you do this is almost always to share the data with someone else.
  93.  
  94. If you just write out the whole array/hash in one fell swoop then it is as simple as what we did above. When you do it one object at a time, it is a little more complicated, since we don't want to write it out to a whole bunch of files, but rather all of them to one file. It is a little more complicated since you want to be able to easily read your objects back in again which can be tricky as <span style="font-style: italic;"></span>_YAML_ serialization creates multiple lines per object. Here is a trick you can use, when you write the objects out, separate them with two newlines e.g.:
  95.  
  96. ```ruby
  97. File.open("/home/alan/tmp/blah.yaml", "w") do |file|
  98. (1..10).each do |index|
  99. file.puts YAML::dump(A.new("hello world", index))
  100. file.puts ""
  101. end
  102. end
  103. ```
  104.  
  105. The file will look like this:
  106. ```yaml
  107. --- !ruby/object:A
  108. number: 1
  109. string: hello world
  110.  
  111. --- !ruby/object:A
  112. number: 2
  113. string: hello world
  114.  
  115. ...
  116. ```
  117.  
  118. Then when you want to read all the objects back, simply set the input record separator to be two newlines e.g.:
  119.  
  120. ```ruby
  121. array = []
  122. $/="\n\n"
  123. File.open("/home/alan/tmp/blah.yaml", "r").each do |object|
  124. array &lt;&lt; YAML::load(object)
  125. end
  126.  
  127. puts array
  128. ```
  129.  
  130. The output is:
  131. ```yaml
  132. In A:
  133. hello world, 1
  134. In A:
  135. hello world, 2
  136. In A:
  137. hello world, 3
  138. ...
  139. ```
  140.  
  141. Which is exactly what we expect &#8211; handy. By the way, I will be covering things like the input record separator in an upcoming series of posts I am planning to do about Ruby one-liners, so don't forget to subscribe if you don't want to miss it.
  142.  
  143. ## A 3rd Party Alternative
  144.  
  145. Of course, if we don't want to resort to tricks like that, but still keep our serialized objects human-readable, we have another alternative which is basically as common as the Ruby built in serialization methods &#8211; <a href="http://www.json.org/" target="_blank">JSON</a>. The JSON support in Ruby is provided by a 3rd party library, all you need to do is:
  146. ```sh
  147. gem install json
  148. ```
  149. or
  150. ```sh
  151. gem install json-pure
  152. ```
  153. The second one is if you want a pure Ruby implementation (_no native extensions_).
  154.  
  155. **The good thing about JSON, is the fact that it is even more human readable than YAML**. It is also a "_low-fat_" alternative to XML and can be used to transport data over the wire by AJAX calls that require data from the server (_that's the simple one sentence explanation :)_). The other good news when it comes to serializing objects to JSON using Ruby is that if you save the object to a file, it saves it on one line, so we don't have to resort to tricks when saving multiple objects and reading them back again.&nbsp;
  156.  
  157. There is bad news of course, in that your objects won't automagically be converted to JSON, unless all you're using is hashes, arrays and primitives. You need to do a little bit of work to make sure your custom object is serializable. Let&rsquo;s make one of the classes we introduced previously serializable using JSON.
  158.  
  159. ```ruby
  160. require "json"
  161.  
  162. class A
  163. def initialize(string, number)
  164. @string = string
  165. @number = number
  166. end
  167.  
  168. def to_s
  169. "In A:\n #{@string}, #{@number}\n"
  170. end
  171.  
  172. def to_json(*a)
  173. {
  174. "json_class" =&gt; self.class.name,
  175. "data" =&gt; {"string" =&gt; @string, "number" =&gt; @number }
  176. }.to_json(*a)
  177. end
  178.  
  179. def self.json_create(o)
  180. new(o["data"]["string"], o["data"]["number"])
  181. end
  182. end
  183. ```
  184.  
  185. Make sure to not forget to '_require_' json, otherwise you'll get funny behaviour. Now you can simply do the following:
  186.  
  187. ```ruby
  188. a = A.new("hello world", 5)
  189. json_string = a.to_json
  190. puts json_string
  191. puts JSON.parse(json_string)
  192. ```
  193.  
  194. Which produces output like this:
  195. ```json
  196. {"json_class":"A","data":{"string":"hello world","number":5}}
  197. ```
  198. ```yaml
  199. In A:
  200. hello world, 5
  201. ```
  202. The first string is our serialized JSON string, and the second is the result of outputting our deserialized object, which gives the output that we expect.
  203.  
  204. As you can see, we implement two methods:
  205.  
  206. * _**to_json**_ &#8211; called on the object instance and allows us to convert an object into a JSON string.
  207. * _**json_create**_ &#8211; allows us to call _JSON.parse_ passing in a JSON string which will convert the string into an instance of our object
  208.  
  209. You can also see that, when converting our object into a JSON string we need to make sure, that we end up with a hash and that contains the '_json_class_' key. We also need to make sure that we only use hashes, arrays, primitives (_i.e. integers, floats etc., not really primitives in Ruby but you get the picture_) and strings.
  210.  
  211. So, JSON has some advantages and some disadvantages. I like it because it is widely supported so you can send data around and have it be recognised by other apps. I don't like it because you need to do work to make sure your objects are easily serializable, so if you don't need to send your data anywhere but simply want to share it locally, it is a bit of a pain.
  212.  
  213. ## Binary Serialization
  214.  
  215. The other serialization mechanism built into Ruby is binary serialization using <a href="http://ruby-doc.org/core/classes/Marshal.html" target="_blank"><em>Marshal</em></a>. **It is very similar to _YAML_ and just as easy to use, the only difference is it's not human readable as it stores your objects in a binary format**. You use Marshal exactly the same way you use YAML, but replace the word YAML with Marshal :)
  216.  
  217. ```ruby
  218. a = A.new("hello world", 5)
  219. puts a
  220. serialized_object = Marshal::dump(a)
  221. puts Marshal::load(serialized_object)
  222. ```
  223. ```yaml
  224. In A:
  225. hello world, 5
  226. In A:
  227. hello world, 5
  228. ```
  229. As you can see, according to the output the objects before and after serialization are the same. You don’t even need to <em>require</em> anything :). The thing to watch out for when outputting multiple <em>Marshalled</em> objects to the same file, is the record separator. Since you’re writing binary data, it is not inconceivable that you may end up with a newline somewhere in a record accidentally, which will stuff everything up when you try to read the objects back in. So two rules of thumb to remember are:
  230.  
  231. - don’t use puts when outputting Marshalled objects to a file (use print instead), this way you avoid the extraneous newline from the
  232. - use a record separator other than newline, you can make anything unlikely up (if you scroll down a bit you will see that I used ‘——’ as a separator_)
  233.  
  234. The disadvantage of Marshal is the fact the its output it not human-readable. The advantage is its speed.
  235.  
  236. ## Which One To Choose?
  237. It’s simple, if you need to be able to read your serializable data then you have to go with one of the human-readable formats (<em>YAML or JSON</em>). I’d go with YAML purely because you don’t need to do any work to get your custom objects to serialize properly, and the fact that it serializes each object as a multiline string is not such a big deal (<em>as I showed above</em>). The only times I would go with JSON (<em>aside the whole wide support and sending it over the wire deal</em>), is if you need to be able to easily edit your data by hand, or when you need human-readable data and you have a lot of data to deal with (_see benchmarks below_).
  238.  
  239. If you don’t really need to be able to read your data, then always go with Marshal, especially if you have a lot of data.
  240.  
  241. Here is a situation I commonly have to deal with. I have a CSV file, or some other kind of data file, I want to read it, parse it and create an object per row or at least a hash per row, to make the data easier to deal with. What I like to do is read this CSV file, create my object and serialize them to a file at the same time using Marshal. This way I can operate on the whole data set or parts of the data set, by simply reading the serialized objects in, and it is orders of magnitude faster than reading the CSV file again. Let’s do some benchmarks. I will create 500000 objects (<em>a relatively small set of data</em> ) and serialize them all to a file using all three methods.
  242.  
  243. ```ruby
  244. require "benchmark"
  245.  
  246. def benchmark_serialize(output_file)
  247. Benchmark.realtime do
  248. File.open(output_file, "w") do |file|
  249. (1..500000).each do |index|
  250. yield(file, A.new("hello world", index))
  251. end
  252. end
  253. end
  254. end
  255.  
  256. puts "YAML:"
  257. time = benchmark_serialize("/home/alan/tmp/yaml.dat") do |file, object|
  258. file.puts YAML::dump(object)
  259. file.puts ""
  260. end
  261. puts "Time: #{time} sec"
  262.  
  263. puts "JSON:"
  264. time = benchmark_serialize("/home/alan/tmp/json.dat") do |file, object|
  265. file.puts object.to_json
  266. end
  267. puts "Time: #{time} sec"
  268.  
  269. puts "Marshal:"
  270. time = benchmark_serialize("/home/alan/tmp/marshal.dat") do |file, object|
  271. file.print Marshal::dump(object)
  272. file.print "---_---"
  273. end
  274. puts "Time: #{time} sec"
  275. ```
  276. ```yaml
  277. YAML:
  278. Time: 45.9780583381653 sec
  279. JSON:
  280. Time: 5.44697618484497 sec
  281. Marshal:
  282. Time: 2.77714705467224 sec
  283. ```
  284. What about deserializing all the objects:
  285.  
  286. ```ruby
  287. def benchmark_deserialize(input_file, array, input_separator)
  288. $/=input_separator
  289. Benchmark.realtime do
  290. File.open(input_file, "r").each do |object|
  291. array &lt;&lt; yield(object)
  292. end
  293. end
  294. end
  295.  
  296. array1 = []
  297. puts "YAML:"
  298. time = benchmark_deserialize("/home/alan/tmp/yaml.dat", array1, "\n\n") do |object|
  299. YAML::load(object)
  300. end
  301. puts "Array size: #{array1.length}"
  302. puts "Time: #{time} sec"
  303.  
  304. array2 = []
  305. puts "JSON:"
  306. time = benchmark_deserialize("/home/alan/tmp/json.dat", array2, "\n") do |object|
  307. JSON.parse(object)
  308. end
  309. puts "Array size: #{array2.length}"
  310. puts "Time: #{time} sec"
  311.  
  312. array3 = []
  313. puts "Marshal:"
  314. time = benchmark_deserialize("/home/alan/tmp/marshal.dat", array3, "---_---") do |object|
  315. Marshal::load(object.chomp)
  316. end
  317. puts "Array size: #{array3.length}"
  318. puts "Time: #{time} sec"
  319. ```
  320. ```yaml
  321. YAML:
  322. Array size: 500000
  323. Time: 19.4334170818329 sec
  324. JSON:
  325. Array size: 500000
  326. Time: 18.5326402187347 sec
  327. Marshal:
  328. Array size: 500000
  329. Time: 14.6655268669128 sec
  330. ```
  331. As you can see, **it is significantly faster to serialize objects when you’re using Marshal** , although JSON is only about 2 times slower. YAML gets left in the dust. When deserializing, the differences are not as apparent, although Marshal is still the clear winner. The more data you have to deal with the more telling these results will be. So, for pure speed – choose Marshal. For speed and human readability – choose JSON (<em>at the expense of having to add methods to custom objects</em>). For human readability with relatively small sets of data – go with YAML.
  332.  
  333. That’s pretty much all you need to know, but it is not all I have to say on serialization. One of the more interesting (<em>and cool</em>) features of Ruby is how useful [blocks](http://www.skorks.com/2009/09/using-ruby-blocks-and-rolling-your-own-iterators/) can be in many situations, so **you will inevitably, eventually run into a situation where you may want to serialize a block and this is where you will find trouble** ! We will deal with block serialization issues and what (<em>if anything</em> ) you can do about it in a subsequent post. More Ruby soon :).
Advertisement
Add Comment
Please, Sign In to add comment