Here's a simple ActiveResource class. It has some instance variables and maybe even some methods, but it's not backed by any data.
ruby-1.8.7-p299 > class Box < ActiveResource::Base;
attr_accessor :a, :b, :c, :d;
end
=> nil
Let's populate it:
ruby-1.8.7-p299 > bx = Box.new; bx.a = 100; bx.b = 200;
bx.c = 300; bx.d = 400;
bx
=> #<Box:0xb5841c54 @attributes={}, @b=200, @a=100,
@prefix_options={}, @c=300, @d=400>
So far so good. How about we cherry-pick some of those instance variables for its JSON model? Say that we only care about b
and c
but not a
, d
, or anything else.
ruby-1.8.7-p299 > bx.to_json({:only => ['b', 'c']})
=> "{}"
That doesn't work, however, since we have no attributes called 'b' or 'c', only values. How can we wind up with something like this?
{ "box": { "b": 200, "c": 300 } }
Even better, can we get this without having to inherit from ActiveResource?