One of my favorite things about using the Markdown Rails, Sitepress Rails, and URI Builder gems is how easy it is to integrate referral codes into markdown content so I don’t have to think about it when I’m writing the article.
All I have to do is modify the ApplicationMarkdown
class to intercept links the Markdown parses.
# ./app/markdown/application_markdown.rb
class ApplicationMarkdown < MarkdownRails::Renderer::Rails
# Code
AMAZON_STORE_ID = "rocketship083-20"
# This is called when a link is encountered in the markdown content
def link(link, title, content)
# The URI is wrapped in a builder, which makes modifications easier.
url = URI.build(link)
case url.uri.host
when "www.amazon.com"
url.query tag: AMAZON_STORE_ID
end
# HTML is rendered and emitted back into the HTML buffer.
content_tag :a, href: url.to_s, title: do
content
end
end
end
Then, when I’m writing an article, I can copy and paste whatever links I want into the markdown and never have to remember to include the referral code.
When I paste a link into my markdown like:
[SmallRig aluminum tripod stand](https://www.amazon.com/SmallRig-Selection-Lightweight-Aluminum-Adjustable/dp/B09C8F36LC)
It automatically renders the HTML with the referral code:
<a href="https://www.amazon.com/SmallRig-Selection-Lightweight-Aluminum-Adjustable/dp/B09C8F36LC?tag=rocketship083-20">
SmallRig aluminum tripod stand
</a>
In the future if I need to add more referral codes, I can add them to the case statement and manipulate the URL with URI Builder.