Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively modify values in a nested hash

Given the following hash structure I would like to walk the structure and make a modification to all of the values with a key of "link":

{"page_id":"12345", "link_data":{"message":"test message", "link":"https://www.example.com", "caption":"https://www.example.com", "child_attachments":[{"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xap1/t45.1600-4/10736595_6021553533580_1924611765_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xaf1/t45.1600-4/10736681_6021625991180_305087686_n.png"}, {"link":"http://www.example.com", "name":"test", "description":"test 2", "picture":"https://fbcdn-creative-a.akamaihd.net/hads-ak-xfp1/t45.1600-4/10736569_6020761399780_1700219102_n.png"}]}}

The approach that I've been playing with feels a bit wrong to me in that Im checking all of the values to see if they have a pattern matching what should be a URL and then modifying it at that point:

  def find_all_values_for(key)
    result = []
    result << self[key]
    self.values.each do |hash_value|
      if hash_value.to_s =~ URI::regexp # if the value looks like a URL then change it
        # update the url
     end
    end
  end

So the exact end result of the transformation should be the same hash with the URL's modified. What I actually want to do is to add tracking parameters to each of the URL's in the hash.

I've toyed with the idea of converting the hash to a string and performing some string replacement on it too but that doesnt seem like it would be the cleanest way of doing such a thing.

Cheers

like image 667
cgallagher Avatar asked Nov 05 '14 17:11

cgallagher


Video Answer


1 Answers

Something like this perhaps?

def update_links(hash)
  hash.each do |k, v|
    if k == "link" && v.is_a?(String)
      # update link here
      v.replace "a modification"
    elsif v.is_a?(Hash)
      update_links v
    elsif v.is_a?(Array)
      v.flatten.each { |x| update_links(x) if x.is_a?(Hash) }
    end
  end
  hash
end
like image 130
August Avatar answered Sep 21 '22 16:09

August