Carlos
Carlos

Reputation: 1

Ruby Nested Hash Merge

Given something like this:

hey = {
  some_key: {
      type: :object,
      properties: {
        id: { type: :string, example: '123', description: 'Id' },
        created_at: { type: :string, example: '2019-02-14 14:13:55'},
        updated_at: { type: :string, example: '2019-02-14 14:13:55'},
        type: { type: :string, example: 'something', description: 'Resource type' },
        token: { type: :string, example: 'token', description: 'Some description of token' }
      }
    }
}

I would like to go through all keys until I find one named properties, then mutate its content such that the keys become the value of a description key if it doesn't exit in its nested hash.

So for the example above, the hash would end up like this:

hey = {
  some_key: {
      type: :object,
      properties: {
        id: { type: :string, example: '123', description: 'Id' },
        created_at: { type: :string, example: '2019-02-14 14:13:55', description: 'Created At'},
        updated_at: { type: :string, example: '2019-02-14 14:13:55', description: 'Updated At'},
        type: { type: :string, example: 'something', description: 'Resource type' },
        token: { type: :string, example: 'token', description: 'Some description of token' }
      }
    }
}

created_at and updated_at didn't have a description.

It should also handle if token, for instance, had a properties property.

I came up with a solution that works but I am really curious on how I can improve it?

My solution below:

def add_descriptions(hash)
  return unless hash.is_a?(Hash)
  hash.each_pair do |key, value|
    if key == :properties
      value.each do |attr, props|
        if props[:description].nil?
          props.merge!(description: attr.to_s)
        end
      end
    end
    add_descriptions(value)
  end
end

Upvotes: 0

Views: 170

Answers (1)

Cary Swoveland
Cary Swoveland

Reputation: 110675

As I understand all you know about the hash hey is that it is comprised of nested hashes.

def recurse(h)
  if h.key?(:properties)
    h[:properties].each do |k,g|
      g[:description] = k.to_s.split('_').map(&:capitalize).join(' ') unless
        g.key?(:description)
    end
  else
    h.find { |k,obj| recurse(obj) if obj.is_a?(Hash) }
  end
end

recurse hey
  #=> {:id=>{:type=>:string, :example=>"123", :description=>"Id"},
  #    :created_at=>{:type=>:string, :example=>"2019-02-14 14:13:55",
  #      :description=>"Created At"},
  #    :updated_at=>{:type=>:string, :example=>"2019-02-14 14:13:55",
  #    :description=>"Updated At"},
  #    :type=>{:type=>:string, :example=>"something",
  #      :description=>"Resource type"},
  #    :token=>{:type=>:string, :example=>"token",
  #      :description=>"Some description of token"}} 

The return value is the updated value of hey.

Upvotes: 1

Related Questions