Question

I'm attempting to make JSON that looks something like this:

elements: {
    nodes: [
      { data: { id: 'j', title: 'Jerry' } },
      { data: { id: 'e', title: 'Elaine' } },
      { data: { id: 'k', title: 'Kramer' } },
      { data: { id: 'g', title: 'George' } }
    ],
    edges: [
      { data: { source: 'j', target: 'e' } },
      { data: { source: 'j', target: 'k' } },
      { data: { source: 'k', target: 'j' } },
   ]
} 

With RABL. My code looks like this:

object @work => :elements

child :nodes, :root => :nodes, :object_root => "data".pluralize do
    attributes :id, :title
end

child :links, :root => :edges, :object_root => :data do
    attribute :parent_id => :source
    attribute :child_id => :target
end

But my JSON still reads

{"elements":
    {"nodes":[
        {"datum":{"id":j,"title":"Jerry"}},
        {"datum":{"id":k,"title":"Kramer"}},

etc...

As you can see, I've tried the .pluralize function, even .pluralize(2) to try to force it to recognize it as multiple, but to no avail. It seems like RABL is probably calling .singularize somewhere down the line, but I'm not sure how to get around it.

I need it to read "data" instead of "datum" because of a library I'm using (cytoscape.js), which requires the JSON to be formatted a specific way. Thanks for any help!

Was it helpful?

Solution

I found a solution. Basically, appending an s to the plural version of the word will singularize it to back to the plural version, not the singular version.

It's a bit cheesy, but this code in show.json.rabl:

object @work => :elements

child :nodes, :root => :nodes, :object_root => :datas do
    attributes :id, :title
end

child :links, :root => :edges, :object_root => :datas do
    attribute :parent_id => :source
    attribute :child_id => :target
end

yields

"elements":{
    "nodes":[
         {"data":{"id":820,"title":"Jerry"}},
         {"data":{"id":821,"title":"Elaine"}}

etc.

I believe it's because the singularize function doesn't recognize "datas" since it's not a word, so it drops the s by default. Someone who knows ruby a bit better than I might be able to corroborate/shoot that down.

This is probably pretty obvious to people, but perhaps it will help someone like myself who hadn't thought of it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top