As a sample for building a ruby gem I have chosen a simple example, an gem that extend the string class with a method that generate the SHA1 hash for the string. I will call it StringHasher. The ruby code for the that gem is really simple (The following code shown on the awesome features in ruby programming language that allow the developer to open an existing class and add new methods to it)
The next step is package this code into a gem and make it ready for distribution. To do this you need to create a specific file structure required by gem builder.
The first file “string_hasher.gemspec” is a manifest of the gem that holds all sort of metadata about the gem, such as: name, version, author name, files… (here is an example of gemspec file)
1. Gem::Specification.new do |s|
2. s.name = 'string_hasher'
3. s.version = '0.0.1'
4. s.date = '2013-09-03'
5. s.summary = "Hash string using SHA!"
6. s.description = "Extension method to string class ..."
7. s.authors = ["Joseph Wahba"]
8. s.email = '???@????.??'
9. s.files = ["lib/string_hasher.rb"]
10. s.license = 'MIT'
the “string_hasher.rb” file contains the actual ruby code that performs the desired functionality. (note that this file should be referenced in the gemspec file as in line 10)
After you finish editing these files, open your trusty terminal and execute the following command.
gem build string_hasher.gemspec
The following result should show up in the terminal
Successfully built RubyGem
Then you will be able to find a new file created in the folder with the name string_hasher-0.0.1.gem
Congratulation you have your first gem
Next article I will show how to deploy this gem using RubyGems.org and/or locally and how to reference it and use it in your project.