2

I've got a class that serializes data. I may want to serialize this data as JSON, or perhaps YAML. Can I cleanly swap YAML for JSON objects in this case? I was hoping I could do something like the following. Is it a pipe dream?

FORMATS = {
  :json => JSON,
  :yaml => YAML,
}

def serialize(data, format)
  FORMATS[format].serialize(data)
end
mmmmmm
  • 30,723
  • 26
  • 85
  • 109
Blaine Lafreniere
  • 2,584
  • 23
  • 41

2 Answers2

2

The code you have written should work just fine, provided that classes JSON and YAML both have class method called serialize. But I think the method that actually exists is #dump.

So, you would have:

require 'json'
require 'yaml'

FORMATS = {
  :json => JSON,
  :yaml => YAML,
}

def serialize(data, format)
  FORMATS[format].dump(data)
end

hash = {:a => 2}
puts serialize hash, :json
#=> {"a":2}

puts serialize hash, :yaml
#=> --- 
#=> :a: 2
Mladen Jablanović
  • 41,202
  • 10
  • 87
  • 110
0

If JSON and YAML are classes or modules that already exist, you can write:

FORMATS = { :json => "JSON", :yaml => "YAML" }

def serialize(data, format)
    Kernel.const_get(FORMATS[format]).serialize(data) # 'serialize' is a class method in this case
end
Daniel O'Hara
  • 12,777
  • 3
  • 43
  • 66