In Ruby programming, a gem is a great way to package and reuse source code. Have you ever wondered why we shouldn't just code directly into a project but instead use gems? The simple reason is that gems help separate functionality, making the project cleaner, easier to maintain, and simple to share. In this article, we will create a simple gem - the BMI Calculator - and push it to GitHub instead of RubyGems for easier demo use.
Easy to reuse: When writing code for common features like calculating the BMI index, packaging it into a gem helps you reuse the code across different projects without the need for copy-pasting.
Version management and updates: With a gem, you can easily update and manage versions. When there are changes in the BMI calculation logic, simply update the gem and use the new version.
Separation of source code: The source code in a gem helps keep the main code of the project cleaner, easier to maintain, and adheres to the DRY (Don’t Repeat Yourself) principle.
Easy to share: If you are working in a team or want to share your code, gems make it easy to share and distribute for everyone to use.
Below are the basic steps to create a simple Ruby gem. You can watch a detailed step-by-step tutorial video on YouTube here: Guide to Creating a BMI Calculator Gem.
Main Steps:
bundle gem
to create the basic gem structure.README.md
file.In the video, I will guide you step-by-step so you can create and manage your own gem.
In another project, simply add this line to the Gemfile to use the gem from GitHub:
bundle add bmi_calculator --source=https://github.com/vulehuan/bmi_calculator.git
With the above command, bundle will automatically install the gem, and you can use it in your project like any other regular gem.
Note: In practice, many projects use gems from other sources like gemfury or other custom sources that fit the project requirements.
Creating a Ruby gem helps you reuse code, manage versions, and easily share within the community or work group. I hope this guide allows you to confidently create and use gems for your projects. Experiment and start building your first Ruby gem!