Ruby on Rails provides a powerful and flexible asset pipeline that makes managing and referencing assets like images, stylesheets, and JavaScripts a breeze. Within this system, the AssetUrlHelper
module offers several handy methods to generate paths and URLs for your assets. While some of these methods are commonly used, others are less well-known but equally useful.
In this blog post, we’ll explore five helpful methods provided by the AssetUrlHelper
module, complete with examples to demonstrate their usage.
1. asset_url
The asset_url
method generates an absolute URL to an asset. This is useful when you need a complete URL for linking assets in emails, API responses, or other contexts where a full URL is required.
Example Usage:
1
2
<%= asset_url 'logo.png' %>
<!-- Outputs: http://yourdomain.com/assets/logo.png -->
2. asset_path
The asset_path
method generates a relative path to an asset. Unlike asset_url
, this method returns a path relative to the root of the application, making it useful for in-app references.
Example Usage:
1
2
<%= asset_path 'image.png' %>
<!-- Outputs: /assets/image.png -->
3. image_url
The image_url
method generates an absolute URL specifically for image assets. It is a specialized version of asset_url
tailored for images.
Example Usage:
1
2
<%= image_url 'avatar.jpg' %>
<!-- Outputs: http://yourdomain.com/assets/avatar.jpg -->
4. font_path
The font_path
method generates the relative path to a font asset. This method is particularly useful for referencing custom fonts in your stylesheets.
Example Usage:
1
2
3
4
@font-face {
font-family: "MyFont";
src: url("<%= font_path 'myfont.woff2' %>") format("woff2");
}
5. video_url
The video_url
method generates an absolute URL for a video asset. It is designed to simplify the handling of video files within your application.
Example Usage:
1
2
<%= video_url 'sample.mp4' %>
<!-- Outputs: http://yourdomain.com/assets/sample.mp4 -->
Putting It All Together
Let’s see how these methods can be used in a typical Rails view:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html>
<head>
<title>AssetUrl Helper Examples</title>
<link rel="stylesheet" href="<%= asset_path 'styles.css' %>">
<style>
@font-face {
font-family: "MyFont";
src: url("<%= font_path 'myfont.woff2' %>") format("woff2");
}
</style>
</head>
<body>
<h1>Welcome to Our Website</h1>
<img src="<%= image_url 'logo.png' %>" alt="Logo">
<video controls>
<source src="<%= video_url 'intro.mp4' %>" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>
The AssetUrlHelper
module in Rails provides a variety of methods to help you manage and reference your assets effectively. Whether you need a full URL for an API response, a relative path for in-app use, or specific references for images, fonts, and videos, these helper methods can streamline your development process.