3

I am trying to create my first Ruby gem and I get a LoadError on the first 'require' line.

Inside my gem folder I have 3 classes including 'version.rb' (where the LoadError is occurring)

version.rb

module OptimalBankroll
 VERSION = "0.0.1"
end

numeric.rb ( i modify the numeric class so that any integer/float used will be changed to a percentage:

module OptimalBankroll
 class Numeric
  def to_percentage
    self.to_f / 100
  end
 end
end

bet_size.rb ( Ex: BetSize.new.amount(1000,1), returns ==> 10

module OptimalBankroll
 class BetSize
  def amount(bankroll, unit)
   bankroll.round(2) * unit.round(2).to_percentage
  end
 end
end

optimal_bankroll.rb ( here is where I get the LoadError )

require "optimal_bankroll/version"
require "optimal_bankroll/numeric"
require "optimal_bankroll/bet_size"

module OptimalBankroll

end

p OptimalBankroll::BetSize.new.amount(1000, 0.5)

rubygems/core_ext/kernel_require.rb:53:in `require': cannotload such file --
optimal_bankroll/version (LoadError)

I am completely green with creating Ruby gems so any advice would be helpful, thanks!

1 Answer 1

3

If the string you pass into require is not an absolute path, it will only check for the file in directories specified in $LOAD_PATH. Normally, these files are placed in lib/, which is added to $LOAD_PATH in your gemspec. Make sure you have these lines in your gemspec:

lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

So then for your require to work you would need to use this folder structure:

/
└── lib/
   └── optimal_bankroll.rb
   └── optimal_bankroll/
      └── version.rb
      └── numeric.rb
      └── bet_size.rb

It is standard practice to use the directory scheme described above, and changing $LOAD_PATH to match where you've placed your files rather than vice versa should be avoided.

Here is a guide on how to create a gem with bundler. You may find it helpful if you're just getting started with gem development. http://bundler.io/v1.6/rubygems.html

Sign up to request clarification or add additional context in comments.

2 Comments

You should never mess with $LOAD_PATH in a gem. The whole point of using a package management system like RubyGems is that it handles setting up the environment for you!
@JörgWMittag what would you suggest? I'm having a similar problem as the OP but I don't want to use $LOAD_PATH

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.