0

I'm a java and Js developer, so I'm completetly new to rails and ruby. In one of my project I'm using rails to consume an api and return in back to js. I'm converting the api response to a model in ruby.

Now, it's in format of {KEY1=>[{array of objects(my model)}], KEY2=>[{array of objects(my model)}]}

Also the keys to model is in snake_case. My requirement is to loop through this and convert this into JSON with camel case keys.

Api response after converting to model: { KEY1=>[{@person_name:"abc", @person_id="123"}],KEY2:[{@personName:"bca", @person_id="231"}] }

Desired output: { KEY1:[{personName:"abc", personId:"123"}],KEY2:[{personName:"bca",personId:"231"}] }

I tried using .map and .transform_values till now, but don't know where I'm doing wrong.

Any help is appreciated.

5
  • 2
    Minor note: your desired output is not a valid JSON Commented Oct 15, 2021 at 13:34
  • Just use JSON.generate to convert your hash to JSON. ruby-doc.org/stdlib-3.0.0/libdoc/json/rdoc/… Commented Oct 15, 2021 at 14:05
  • Does it take care of converting keys to camel case? @dbugger Commented Oct 15, 2021 at 14:28
  • @AbhishekP - To clarify, you want to convert a list of models into json, and transofrm all the keys using camelcase? Commented Oct 15, 2021 at 14:47
  • Yes, exactly @BroiSatse Commented Oct 15, 2021 at 14:48

2 Answers 2

1

You can add the following to your ApplicationRecord class:

class ApplicationRecord < ActiveRecord::Base
  def serializable_hash(options = {})
    hash = super
    return hash unless options[:camelize]

    hash.deep_transform_keys { |key| key.to_s.camelize(options[:camelize]) }
  end
end

This will allow you to call to_json(camelize: :lower) on pretty much any object:

{
  KEY1: Person.where(...),
  KEY2: Person.where(...),
}.to_json(camelize: :lower)

To automatically serialize the whole collection

Sign up to request clarification or add additional context in comments.

Comments

0

You can do something like this:

{ 
  KEY1: Person.where(...).select(:name, :id).map { |p| Hash[p.serializable_hash.map { |key, value| ["#{p.model_name.name.downcase}#{key.capitalize}", value] }] }, 
  KEY2: Person.where(...).select(:name, :id).map { |p| Hash[p.serializable_hash.map { |key, value| ["#{p.model_name.name.downcase}#{key.capitalize}", value] }] }
}.to_json

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.