This post refers to exercise 46 in the book Learn Ruby the Hard Way. Here is the work flow for building a simple Ruby gem:
- Build a project skeleton.
Example of a simple project skeleton:
Rakefile data ext hello.gemspec tests
bin doc hello-1.0.gem lib
./bin:
hello
./data:
./doc:
./ext:
./lib:
hello.rb
./tests:
test_hello.rb
-
Write some code to the /lib directory.
I just wrote a simple Ruby function.
-
Put a script in the /bin directory.
I wrote one line of Ruby code.
-
Get the script running.
This part required adding execute permissions to the file. I went one step further and moved the script file to /usr/local/bin/ directory and created an alias for the $PATH. This mean’t I could I could just type the filename (in this case hello) to invoke the Ruby script.
-
Make sure the details in the gemspec file are correct.
-
Build the gem.
wickinot:ex46-scriptexercise wickinot$ gem build hello.gemspec
Successfully built RubyGem
Name: hello
Version: 1.0
File: hello-1.0.gem
wickinot:ex46-scriptexercise wickinot$ gem install ./hello-1.0.gem
Successfully installed hello-1.0
Parsing documentation for hello-1.0
Installing ri documentation for hello-1.0
Done installing documentation for hello after 0 seconds
1 gem installed
- Check if everything works by ‘requiring’ the newly created gem and using it in the Ruby console.
wickinot:ex46-scriptexercise wickinot$ irb
2.5.1 :001 > require 'hello'
=> true
2.5.1 :002 > Hello.hi
Hello, World!
=> nil
2.5.1 :003 >
References I found helpful for this exercise are:
https://commandercoriander.net/blog/2013/02/16/making-a-ruby-script-executable/
https://guides.rubygems.org/make-your-own-gem/
What are the .gemspec and gemfiles?
Gemfile
When developing an app it is important to declare which version of a gem to use and to declare the dependency of the app on that particular gem - This is specified in the gemfile (for example in a Rails app) so the bundler tool knows exactly where to look for the gem.
.gemspec file
The .gemspec file contains all the necessary information for a Gem. It contains a list of dependencies including information about where to find them.
A break down of what each of these .gemspec attributes is as follows:
- spec.name: This is the gem’s name.
- spec.version: The gem’s version.
- spec.authors: The developer(s) name.
- spec.email: The developer(s) email.
- spec.summary: A short description of the gem.
- spec.description: A longer description of the gem.
- spec.homepage: The domain name of the gem.
- spec.license: The license for the gem.
There are further gemspec attributes you can use which can be found RubyGems.org. Another resource I found helpful in getting my head around this was Yehuda Katz’s blog post on this topic found here.