Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is Yarn in Ruby on Rails?

If you're learning programming, you might have come across the term "Yarn" within the context of Ruby on Rails. You might be wondering what it is and how it's used. In this blog post, we will dive into Yarn, understand its purpose, and learn how it's used in Ruby on Rails applications.

What is Yarn?

Yarn is a package manager for your code. It allows you to manage and organize the libraries (also known as packages or modules) that your project depends on. These libraries are chunks of pre-written code that you can use in your project to save time and effort. Yarn ensures that the correct versions of these libraries are installed and that they work well together.

Yarn was developed by Facebook as an alternative to another popular package manager called npm (Node Package Manager). The main aim of Yarn was to address some of the shortcomings of npm, like slow installation speeds and issues with package security. Yarn has been widely adopted by the developer community due to its performance improvements and better dependency management.

How does Yarn work?

Imagine you're building a house. You have a rough idea of what you want, but you need to source the building blocks, or bricks, to put it all together. In this scenario, Yarn is like a brick supplier that helps you find and organize the bricks you need. It ensures that you have the right bricks, in the right quantity, and that they're all compatible with one another.

In programming terms, the bricks are the libraries (code written by others) that your project depends on. These libraries can be anything from utility functions, like formatting dates, to entire frameworks like Ruby on Rails itself.

To use Yarn, you need to provide it with a list of the libraries your project depends on. This list is usually stored in a file called package.json, which is located in the root directory of your project. The package.json file contains information about your project, like its name, version, and the dependencies it relies on.

Here's an example of what a simple package.json file might look like:

{
  "name": "my-awesome-project",
  "version": "1.0.0",
  "dependencies": {
    "lodash": "^4.17.15",
    "moment": "^2.24.0"
  }
}

In this example, our project depends on two libraries: lodash and moment. The version numbers (e.g., ^4.17.15) indicate which versions of the libraries are compatible with our project. The ^ symbol means that any version with the same major version number (the first number) is compatible.

When you run yarn install in your project directory, Yarn will read the package.json file and download the required libraries, along with their compatible versions, into a folder called node_modules. This folder is then used by your project to access the libraries' functionality.

Yarn in Ruby on Rails

Ruby on Rails is a popular web development framework that makes it easy to build web applications quickly. It relies on a package manager called RubyGems to manage its dependencies, which are called gems. However, Rails applications often require JavaScript libraries for front-end functionality, like animations, form validation, or data manipulation.

This is where Yarn comes into play. Starting with Rails version 5.1, Yarn has been integrated into the Rails framework as the default package manager for JavaScript libraries. This means that when you create a new Rails application, Yarn is automatically set up and ready to use.

Let's take a look at how Yarn is used in a Rails application.

Initializing Yarn in a Rails project

When you create a new Rails application, Yarn is automatically set up for you. You'll notice a package.json file in the root directory of your application, similar to this:

{
  "name": "my-rails-app",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/actiontext": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "^4.0.0",
    "turbolinks": "^5.2.0"
  },
  "version": "0.1.0"
}

As you can see, Rails has already added some JavaScript libraries that it depends on, like @rails/actioncable and turbolinks.

Adding a new library

Let's say we want to add jQuery, a popular JavaScript library, to our Rails application. We can do this by running the following command in our project directory:

yarn add jquery

This command tells Yarn to download the jQuery library and add it as a dependency in our package.json file. After running this command, you'll see that the package.json file has been updated to include jQuery:

{
  "name": "my-rails-app",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/actiontext": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "^4.0.0",
    "turbolinks": "^5.2.0",
    "jquery": "^3.6.0"
  },
  "version": "0.1.0"
}

The jQuery library has been downloaded into the node_modules folder, and we can now use it in our Rails application.

Using a library in your Rails application

To use the jQuery library (or any other library you've added using Yarn) in your Rails application, you'll need to import it into your JavaScript code. Rails uses a tool called Webpacker to bundle and manage JavaScript code. By default, Webpacker creates a file called app/javascript/packs/application.js, which serves as the entry point for your JavaScript code.

To use jQuery, open the application.js file and add the following line at the top:

import $ from 'jquery';

This line tells Webpacker to import the jQuery library and assign it to the variable $. You can now use jQuery in your Rails application like you would in any other JavaScript project.

Here's an example of how you might use jQuery in your Rails application:

  1. Create a file called app/javascript/my-script.js and add the following code:
$(document).ready(function() {
  $('button').click(function() {
    alert('Button clicked!');
  });
});

This code uses jQuery to listen for a button click and display an alert when a button is clicked.

  1. Import the my-script.js file in your application.js file by adding this line:
import './my-script';
  1. In your Rails view (e.g., app/views/layouts/application.html.erb), make sure you've added the following line to include the JavaScript pack:
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>

Now, when you run your Rails application and click a button, you should see an alert saying "Button clicked!".

Conclusion

In this blog post, we learned about Yarn, a package manager that helps you manage and organize the libraries your project depends on. We also saw how Yarn is integrated into Ruby on Rails applications and how you can use it to add and manage JavaScript libraries.

By using Yarn in your Rails projects, you can easily manage your JavaScript dependencies and ensure that your application uses the correct versions of the libraries it depends on. This can help you avoid potential issues and make your development process more efficient and enjoyable.