简体   繁体   中英

Creating a Ruby gem // 'require' error: cannot load such file (LoadError)

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM