How can I produce some simple json with this Ruby class? -


Here is a simple ActiveResource class, there are some examples variables and maybe even some methods, but it does not support any data .

  Ruby-1.8.7-p299 & gt; Class box & lt; ActiveResource :: Base; Attr_accessor: a ,: b ,: c ,: d; End = & gt; Zero  

populate it:

  Ruby-1.8.7- p299> Bx = box. new; Bx.a = 100; Bxb = 200; Bx.c = 300; Bxad = 400; Bx = & gt; # & Lt; Box: 0xb5841c54 @ attributes = {}, @ b = 200, @ a = 100, @ prefix_options = {}, @ c = 300, @ d = 400 & gt;  

So far, how good do we cherish those example variables for some of our Jason models? Say we do not pay attention to b and c , but a , d , or something else .

Ruby-1.8.7- p299 & gt; Bx.to_json ({: only => gt; ['B', 'C']}) => "{}"

This does not work, however, because we do not have any properties 'b' or 'c', only values ​​are.

<">" "" Even better, can we obtain it without an inheritance from ActiveResource?

In an AR object, you can use two-jays from the 'methods' param on this page. , like:.

In a non-AR object, simply define a custom to_json method, where you assemble a hash of the variable that you want to json-ize, then do it, and return it to do. As such, here's an (untested) example:

  def to_json (options = {}) {"box" => {"B" = & gt; B, "c" = & gt; C}}. To_json (option) End  

Comments

Popular posts from this blog

c# - sqlDecimal to decimal clr stored procedure Unable to cast object of type 'System.Data.SqlTypes.SqlDecimal' to type 'System.IConvertible' -

Calling GetGUIThreadInfo from Outlook VBA -

Obfuscating Python code? -