This tutorial aims to guide you through the process of managing static files and compiled assets in a Rails project. We will take a deep dive into the 'public' directory and the asset pipeline, fully understanding their roles and how they function.
By the end of this tutorial, you will:
- Understand the structure and purpose of the 'public' directory in a Rails project.
- Learn how to work with compiled assets within the asset pipeline.
- Have a clear understanding of how static files are served to users.
Prerequisites: Basic knowledge of Ruby on Rails, HTML, CSS, and JavaScript. Familiarity with command line interface.
The 'public' directory in a Rails project is where static files that don't change often are stored. This includes error pages, favicon, and other assets.
The asset pipeline is a feature in Rails that concatenates and minifies or compresses JavaScript and CSS assets. It also allows coding assets via a higher-level language such as CoffeeScript, Sass, and ERB.
404.html
, 422.html
, 500.html
, and possibly favicon.ico
.404.html
error page.app/assets
directory. This is where your JavaScript, CSS, and image assets are stored.//= require
directive to include assets in your application. For example, to include a JavaScript file, you would write //= require example.js
in your application.js
file.Let's take a look at some examples.
In your public/404.html
file, you could have something like this:
<!DOCTYPE html>
<html>
<head>
<title>Page Not Found</title>
</head>
<body>
<h1>Oops!</h1>
<p>We couldn't find the page you were looking for.</p>
</body>
</html>
In your app/assets/javascripts
directory, create a file called example.js
and add some JavaScript code:
// This is an example JavaScript file
console.log("Hello, world!");
Then, in your application.js
file, require the example.js
file:
//= require example
The expected output when you load your application in the browser and open the console is: Hello, world!
.
We've covered how to work with the 'public' directory and the asset pipeline in a Rails project. You've learned how to manage static files and compiled assets, and how these assets are served to the user.
To continue learning, you could explore more about the asset pipeline, such as how to precompile assets for production. You could also learn more about managing static files in Rails.
500.html
error page in your Rails project.Solution: Open the public/500.html
file and add your custom HTML code.
Exercise 2: Add a CSS asset to your Rails project and include it in your application.
Solution: In the app/assets/stylesheets
directory, create a styles.css
file. Add some CSS rules. Then, in your application.css
file, use the *= require styles
directive to include the styles.css
file.
Exercise 3: Precompile your assets for production.
rake assets:precompile
in your terminal to precompile your assets. This generates files in the public/assets
directory.Remember, practice makes perfect! Happy coding!