Building a Ruby gem
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
- Install the 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/