开发者

Is there an easy way to define a common interface for a group of unrelated objects?

开发者 https://www.devze.com 2023-01-09 21:40 出处:网络
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 lik开发者_如

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 lik开发者_如何学JAVAe the following. Is it a pipe dream?

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

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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号