Smarter linking to articles
Middleman doesn't give an indication when articles linked within your site are broken. Examples of the cause are mistyping the file path, deletion of article(s) linked, and renaming of the article file.
Using this link helper to link articles will raise an error for the following situations:
- When the specified relative path is missing a starting '/'.
- When the specified relative path is missing an ending '/'.
- When an article doesn't exist for the relative path.
def link_to_article(relative_path)
raise ArgumentError, "Argument #{relative_path} is missing beginning '/'" unless relative_path.start_with?('/')
raise ArgumentError, "Argument #{relative_path} is missing ending '/'" unless relative_path.end_with?('/')
article = blog.articles.detect { |a| a.url == relative_path }
raise ArgumentError, "Argument #{relative_path} doesn't exist" unless article.present?
link_to article.data.title.titleize, article.url, title: "Read article: #{article.data.title.titleize}"
end
Alternatively if you wish the helper to be not restrictive on the forward slashes:
def link_to_article(relative_path)
relative_path.insert(0, '/') unless relative_path.start_with?('/')
relative_path << '/' unless relative_path.end_with?('/')
article = blog.articles.detect { |a| a.url == relative_path }
raise ArgumentError, "Argument #{relative_path} doesn't exist" unless article.present?
link_to article.data.title.titleize, article.url, title: "Read article: #{article.data.title.titleize}"
end
Written by Viet Hoang
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Middleman
Authors
Related Tags
#middleman
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#