1

I have a JSON object that looks like the following:

{  
   "id":"10103",
   "key":"PROD",
   "name":"Product",
   "projectCategory":{  
      "id":"10000",
      "name":"design",
      "description":""
   }
}

and a Virtus model that looks like the following:

class Project
  include Virtus.model

  attribute  :id, Integer 
  attribute  :key, String
  attribute  :name, String

  attribute  :category, String  #should be the value of json["projectCategory"]["name"]

end

Everything lines up fine other than trying to map Project.category to json["projectCategory"]["name"].

So in total the end Virtus object I'm look for should look like:

"id"       => "10103",
"key"      => "PROD",
"name"     => "Product",
"category" => "design"

Right now I'm creating a model instance with Project.new(JSON.parse(response)) or basically a hash of the json response. How can I custom map Virtus some attributes to my json response?

beckah
  • 1,543
  • 6
  • 28
  • 61

1 Answers1

1

So I ended up figuring out you can override the self.new method allowing you to get to nested values in the hash you pass your Virtus model.

I ended up doing the following which worked fine:

class Project
  include Virtus.model

  attribute  :id,       Integer 
  attribute  :name,     String
  attribute  :key,      String
  attribute  :category, String

  def self.new(attributes)
    new_attributes = attributes.dup

    # Map nested obj "projectCategory.name" to Project.category
    if attributes.key?("projectCategory") and attributes["projectCategory"].key?("name")
      new_attributes[:'category'] = attributes["projectCategory"]["name"]
    end

    super(new_attributes)
  end

end
beckah
  • 1,543
  • 6
  • 28
  • 61