How can I use Ruby's to_json in a subclass and include super's json? -
#!/usr/bin/env ruby require 'json' class def to_json(*a) { :a => 'a' }.to_json(*a) end end class b < def to_json(*a) super({ :b => 'b' }) end end puts b.new.to_json
produces
{"a":"a"}
how produce
{"a":"a", "b":"b"}
in reasonable way?
i'm using ruby 1.9.3 , latest json gem.
a related question is: arguments *a to_json? i've scoured docs no avail.
you have 2 hashes {:a=>'a'}
, {:b=>'b'}
in 2 classes, they're encapsulated i.e. hidden outside world. way can see parse json string hash , merge them, convert result json.
class b < def to_json(*a) json.parse(super).merge({:b=>'b'}).to_json end end
but here small difference: you're merging {:a=>'a',:b=>'b'}
, got {"a":"a","b":"b"}
*a
parameter set options json format
Comments
Post a Comment