ruby on rails - What's the easiest way to make HTTParty return an object/class rather than a JSON response? -


right call:

def child(parent_id, child_id, params = {})   if @api_token     self.class.get("/parents/#{parent_id}/children/#{child_id}", query: params,                       :headers=>{"authorization"=>"token token=#{@api_token}"})   else     self.class.get("/parents/#{parent_id}/children/#{child_id}", query: params)   end end 

it returns json response directly api hash. there easy way me standardize response parses json , generates class?

example:

original response -------- {'child' : { 'name' : 'john doe', 'age' : 23 } }  desired response -------- res.name # john doe res.age  # 23 res.class # apiclient::child 

it can achieved via custom parser passed request call (however advise not , leave now)

an example of parser pass

class instanceparser < httparty::parser   def parse     #assuming have json in format { 'one_key_mapping_to_model' => data }             body_as_json = json.parse(body) #string parsed json              model_class_name = body_as_json.keys.first # == 'one_key_mapping'            model_class_data = body_as_json[model_class_name] # == data     class_instance = model_class_name.camelize.constantize.new(model_class_data) # create new instance of onekeymapping      class_instance   end end 

and in api call pass self.class.get("/parents/#{parent_id}/children/#{child_id}", query: params, parser: instanceparser)


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -