Ruby: if condition in attributes to handle missing key-value

52 views Asked by At

I have a resource class that I use as intermediate DTO for mapping from my model to my API response. I would like to prevent any situation in which any part of the response payload might be delivered as nil. This is what I have

attr_reader :json_block, :element  

def initialize(attributes = {})
 @json_block = attributes['some_json']
 @element = attributes['some_json']['element']
 ....

I thought I could have an something along these lines:

if attributes['json_block'].exists?
  @json_block = attributes['json_block']
  @element = attributes['element']
end

Is this the correct approach? I would like a solution whereby if it comes in nil, we can ignore it and unmarshall the payload.

Thank you

0

There are 0 answers