0

I was wondering how to add another key value pair to the end of the JSON generated by DataMappers .to_json method. When I try to call to_json(:methods => [:total_pages]), it ignores the methods bit all together.

I would like it to produce something like this:

{
  'data':        [rows go here],
  'total_pages': X
}

Is there a way to just do the method inline or something?

Thanks!

Tom Brunoli
  • 3,436
  • 9
  • 36
  • 54

2 Answers2

2

You could edit the JSON string, but as far as I know there's no easy way to inject arbitrary values into the JSON.

Calling your_dm_resource.to_json(:methods => [:total_pages]) is the correct way to do what you want, check your some_dm_resource.total_pages method is working that way you expect.

And if you're using a modern Ruby, you can drop the hash rockets:

your_dm_resource.to_json(methods: [:total_pages])
  • Thanks Daniel. I have been fiddling around with the total_pages method, and I can't get it to work when I have it as a class method (it has a bit of a fit probably because of the relations). Do you know if it's possible to reference a local function in the to_json arguments, or does it have to be a symbol? – Tom Brunoli Sep 25 '12 at 23:19
2

You can do it simpler.

{
    data:   YourModel.your_whatever,
    total_pages: YourModel.total_pages
}.to_json

DM serialization to_json tries to call methods provided in options on the same object it is called itself (in your case - probably collection of results, that does not have total_pages method defined)

UncleGene
  • 2,132
  • 16
  • 19