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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With