DEV Community

Cover image for Reuse Javascript code in Rails 6
Masroor Hussain
Masroor Hussain

Posted on

Reuse Javascript code in Rails 6

DRY(Don't Repeat Yourself) is a basic principle in programming. This article provides a very trivial but useful way for rails developers to reuse their javascript code in multiple files.
The usual folder structure in a rails 6 app looks like

-app/
 |-assets/
 |-channels/
 |-controllers/
 |-helpers/
 |-javascript/
   |-packs/
     |-application.js
 |-...(and other folders)
Enter fullscreen mode Exit fullscreen mode

If you have multiple javascript files in the app/javascript/ folder and you want to reuse the code between these files

-app/
 |-javascript/
   |-packs/
     |-application.js
     |-first.js
     |-second.js
Enter fullscreen mode Exit fullscreen mode

Consider

// app/javascript/packs/first.js

const calculateArea = (params_here) => {
  // calculate and return area
}

const calculateVolume = (params_here) => {
  // calculate and return volume
}
Enter fullscreen mode Exit fullscreen mode

now if you want to use the function calculateArea and calculateVolume in your second.js you can export these functions from first.js and then import them in second.js.

// app/javascript/packs/first.js

const calculateArea = (params_here) => {
  // calculate and return area
}

const calculateVolume = (params_here) => {
  // calculate and return volume
}

export { calculateArea, calculateVolume };
Enter fullscreen mode Exit fullscreen mode

and import them for re-use

// app/javascript/packs/second.js

import { calculateArea, calculateVolume } from './first';
// now you can use the imported consts/variables/functions in this file
Enter fullscreen mode Exit fullscreen mode

Bonus

To include your custom javascript code into application.js pack, considering you've app/javascript/packs/first.js and app/javascript/packs/second.js, do this

// app/javascript/packs/application.js

import 'packs/first'
import 'packs/second'
Enter fullscreen mode Exit fullscreen mode

Cover Image credits Clem Onojeghuo on Unsplash

Top comments (1)

Collapse
 
masroorhussainv profile image
Masroor Hussain

yes, definitely. That example was only to demonstrate the import method/syntax.