Creating Ruby gems for Front End libraries

August 5, 2016 | Uncategorized

While working on my Rails Project Management application, I had an idea. If I can use Bootstrap’s gem to import CSS styles and JS libraries, can I make one?

During the course of any project there are often CSS styles, JS scripts, and other elements that I like to reuse. After some Googling, I found an excellent video on how to create a gem for front end libraries – and it’s super easy (like, less than 10 minutes of work if you’re already familiar with how to make Ruby Gems). In this post I’ll show you how to create your own.

1. Create a new gem using your terminal

Screen Shot 2016-08-03 at 4.35.14 PM

2. In the /lib folder, edit your-gem-name.rb :

This snippet of code basically tells Rails to treat this gem as if it’s a Rails app inside another Rails app. Subsequently, it’s going to treat the folder structure of this gem a little different. Which leads to…

3. Add the Vendor folder and subfolders (assets/javascripts and assets/stylesheets to the root of your gem. Then add your .js and .css files to their respective folders.

Screen Shot 2016-08-03 at 5.30.19 PM

4. In your Rails app, delete the files (not folders) you’re including in the gem from the vendor/assets/javascripts and vendor/assets/stylesheets folders. However, make sure you’re still requiring the files in your asset pipeline (eg application.js and application.css).

5. Test your gem by including it in your gem file using the local path. Note: you may receive some errors when you run ‘bundle’ if you haven’t filled out the necessary information in the gemspec.

If all goes well, you should have access to all the files included in your gem. When you’re ready, run gem build to build it, followed, by rake release to push it up to Ruby gems.

I created my own gem to use in future project I work on. In the simple_front_end gem, I’ve included:

ThisIsDallas’ SimpleGrid – a fantastic, lightweight CSS grid system that’s very easy to implement.
Normalize.css by Necolas – it preserves useful defaults, normalizes styles for a wide range of elements, and corrects bugs and common browser inconsistencies.
Modernizr.js – JavaScript library that detects HTML5 and CSS3 features in the user’s browser.

This will likely change over time as I find better files to use or start incorporating ones I have created myself.

Check out the instructional video on GoRails on how to create this gem or watch it below. If you’re thinking about making a gem like this I highly recommend watching it!

Leave a Reply

Your email address will not be published. Required fields are marked *