I’m learning ruby and I wanted to test how to create gem file. I have followings installed in my machine.
ruby 1.9.3p362 (2012-12-25 revision 38607) [x86_64-linux]
Bundler version 1.2.3
rake, version 10.0.3
I created a gem using bundle gem hello_gem. I added following sample code to hello_gem.rb
module HelloGem
class Base
def self.hello
puts "Hello Ruby Gem #{HelloGem::VERSION}"
end
end
end
My folder structure is like follows.
├── Gemfile
├── Gemfile.lock
├── hello_gem.gemspec
├── lib
│ ├── hello_gem
│ │ └── version.rb
│ └── hello_gem.rb
├── LICENSE.txt
├── Rakefile
├── README.md
Then I created the gem using rake install. Then I started irb and I can execute following.
1.9.3-p362 :001 > require 'hello_gem'
=> true
1.9.3-p362 :002 > HelloGem::Base.hello
Hello Ruby Gem 0.0.1
=> nil
1.9.3-p362 :003 >
Problem comes when I wanted to move code to lib folder. I created lib/hello_gem/base.rb and added the above code there. And in the hello_gem.rb I just used require "hello_gem/base". Now my project look like follows.
├── Gemfile
├── Gemfile.lock
├── hello_gem.gemspec
├── lib
│ ├── hello_gem
│ │ ├── base.rb
│ │ └── version.rb
│ └── hello_gem.rb
├── LICENSE.txt
├── Rakefile
├── README.md
When I build the gem using rake install and use irb to test following error happened.
1.9.3-p362 :001 > require 'hello_gem'
LoadError: cannot load such file -- hello_gem/base
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from /home/sandarenu/.rvm/gems/ruby-1.9.3-p362/gems/hello_gem-0.0.1/lib/hello_gem.rb:2:in `<top (required)>'
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `require'
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:60:in `rescue in require'
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:35:in `require'
from (irb):1
from /home/sandarenu/.rvm/rubies/ruby-1.9.3-p362/bin/irb:16:in `<main>'
1.9.3-p362 :002 >
I can’t find a way to fix this issue. It would be a great help if somebody can tell me what I’m doing wrong here.
Thanks in advance.
The
.gemspeccreated bybundle gemuses Git to determine which files to include in the gem; it contains the line:In order for it to add your
hello_gem/base.rbyou need to add it to the Git repository. Since the original setup works for you I assume you have Git installed, so you just need to run:You don’t actually need to commit the file for
git ls-filesto pick it up and add it to the gem, so this should be enough to get it to work.