2

I have a table which should store an id, a name and a hash. How do I serialize the Hash? (I'm using Ruby and Sequel as ORM.)

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
t6d
  • 2,595
  • 3
  • 26
  • 42

4 Answers4

5

If you're using Sequel::Model, the Serialization plugin should do the trick.

davetron5000
  • 24,123
  • 11
  • 70
  • 98
Greg Campbell
  • 15,182
  • 3
  • 44
  • 45
  • It works! Thanks a lot. I probably should have spent a little bit more time reading the docs: http://sequel.rubyforge.org/rdoc-plugins/classes/Sequel/Plugins/Serialization.html – t6d Jan 25 '10 at 18:47
  • As for the actual column that will save the serialized data, a Blob seems like the way to go - http://stackoverflow.com/questions/5544749/what-column-type-should-be-used-to-store-serialized-data-in-a-mysql-db – Gokul Sep 30 '16 at 06:51
5

You seem to have found a sufficient answer but I thought I'd chip in with a general-purpose Ruby way.

# outside of rails you'll need this
require 'base64'

# encode
h = { :first => "John", :age => 23 }
encoded = Base64.encode64(Marshal.dump(h))

# decode
h = Marshal.load(Base64.decode64(encoded))

I use this to serialize Ruby objects (e.g. across JSON and to the DB), and you'll find that cookie sessions in Rails encode the session hash in the same way. It's often handy to debug the session contents from a browser cookie using this.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user253455
  • 465
  • 2
  • 5
  • The Sequel serialization plugin works the same way. You can decide if you want the use Marshal, Yaml or Json for serializing and deserializing your data. But thanks for the tip. ;) – t6d Jan 28 '10 at 13:46
1

If you're looking for JSON-API compliance, I've had good luck with JSONAPI::Serializers. You will need to pass in the :skip_collection_check option, and for performance you should 1) pass in resultsets, not datasets, and 2) eager-load relationships before serializing (if you're sideloading data).

mwp
  • 8,217
  • 20
  • 26
0

You may give YAML a try:

require 'yaml'

# encode
my_hash = { :first => "John", :age => 23 }
encoded = YAML.dump(my_hash)

# decode
my_hash = YAML.load(encoded)

You can store it in a Sequel String, it works with complex objects, and it is readable in the DB. I read about it here.

Gergely Máté
  • 107
  • 2
  • 11