API אחזור פוסט כתובות URL יחסיות

סיכום מבוסס בינה מלאכותית

The user bobpies discusses an issue with API-retrieved post content from a Discourse forum hosted at forums.xxx.com, where relative URLs in the cooked content break when displayed on www.xxx.com. Links to users, images, and emojis fail because they resolve to the wrong domain. bobpies shares a Ruby solution using a helper method to replace relative URLs with absolute ones by prepending the original domain, providing a working fix for the issue.

Hi all

I’m using the discourse API to retrieve a Topic / all its posts and then each post and and its content

My forums are hosted on forums.xxx.com
I use the API to retrieve the posts and place them on my www.xxx.com domain and link back and forth between the two,

This all works except that the content i pull through uses relative URLs - so a link to a user (when on the forums domain) would be forums.xxx.com/u/the-user

As i pull that post through to my www.x domain, it links to www.xxx.com/u/the-user - which obviously does not exist.
The same problem extends to any emojis or images included in the post - the links are broken.

Is there anyway to have the links coming through (i use content: data['cooked']) to link back to the original domain?

i actually asked chat GPT the same question and got a working answer straight away

using a helper method to replace the urls inside the cooked data

def update_urls(content)
    forum_domain = 'https://forums.xxx.com'

    # Update href attributes
    content.gsub!(/href="(\/[^"]*)"/i) { |match| "href=\"#{forum_domain}#{$1}\"" }

    # Update src attributes
    content.gsub!(/src="(\/[^"]*)"/i) { |match| "src=\"#{forum_domain}#{$1}\"" }

    content
  end

So i’ll leave this here for anyone else - if anyone has a more elegant out of the box solution i would be interested