Tyler
Tyler

Reputation: 2879

How do I build my own gem and use it in another project?

I'm trying to build my first ruby gem that contains some classes I want to use across projects - for the sake of this question it is called test_service_api.

I have written and built the gem using "gem build test_service_api.spec". I have then done a "gem install test_service_api-0.0.2.gem".

The spec file is:

# -*- encoding: utf-8 -*-
require File.expand_path('../lib/test_service_api/version', __FILE__)

Gem::Specification.new do |gem|
  gem.authors       = ["Tyler Power"]
  gem.email         = ["[email protected]"]
  gem.description   = %q{}
  gem.summary       = %q{}
  gem.homepage      = ""

  gem.files         = `git ls-files`.split($\)
  gem.executables   = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) }
  gem.test_files    = gem.files.grep(%r{^(test|spec|features)/})
  gem.name          = "test_service_api"
  gem.require_paths = ["lib"]
  gem.version       = TestServiceApi::VERSION
end

I'm now trying to use the gem in a little test project, in the test projects Gemfile I have specified a dependency on the gem I built:

source 'https://rubygems.org'

gem 'sinatra'
gem 'test_service_api'

I can then do a "bundle install" and the bundler correctly finds all my dependencies and puts them in vendor/cache:

Tylers-MacBook-Pro:Test tyler$ bundle install
Using rack (1.4.1) 
Using rack-protection (1.2.0) 
Using test_service_api (0.0.2) 
Using tilt (1.3.3) 
Using sinatra (1.3.2) 
Using bundler (1.1.3) 
Updating .gem files in vendor/cache
Your bundle is complete! It was installed into ./vendor/bundle

So that all looks good to me so far, the issue I have is that when I try to require the gem in a source file in the test project it can't find it:

require 'rubygems'
require 'sinatra'
require 'test_service_api'

get '/' do
  res = ''
  ENV.each do |k, v|
    res << "#{k}: #{v}<br/>"
  end
  res
end

My IDE complains of "No file to load" and if I try and run the app I get:

./app.rb:3:in `require': no such file to load -- test_service_api (LoadError)
    from ./app.rb:3

I'm close to pulling my hair out... Does anyone have any ideas on how to resolve this?

Upvotes: 1

Views: 663

Answers (1)

DeTeam
DeTeam

Reputation: 438

What about trying this:

require "rubygems"
require "bundler/setup"

instead of just rubygems?

Upvotes: 4

Related Questions