I wrote a small gem and I decided to use internally a different name than externally i.e. my gem's name is google-search, but the file structure is

google-search
  |-lib
    |-google
      |-search
      |-search.rb

to load my code using pry I simply do

bundle exec pry -r ./lib/google/search

from inside the google-search directory.

I have now included my new gem in my project and I'm attempting to require and use it, but for some reasons I'm not able to do it.

I've tried:

[1] pry(main)> require 'google/search'
=> false
[2] pry(main)> require 'google'
LoadError: cannot load such file -- google
from (pry):7:in `require'
[3] pry(main)> require 'google-search'
LoadError: cannot load such file -- google-search
from (pry):8:in `require'

Should I change the internal structure or I have to do something else? I really like the idea of require "google/search" but it's ok if I have to change it. How does this work? Thanks a lot.

有帮助吗?

解决方案

require 'google/search' is correct for your gem

The return value of false means that Ruby found your gem library file google/search.rb but has already parsed and loaded it. It would return true only if the library had not already been loaded.

Reference: http://www.ruby-doc.org/core-2.1.1/Kernel.html#method-i-require

It is possible that the require has found a conflicting file - anything in the gem search path matching google/search.rb could in theory be loaded, the gem name itself is not relevant other than .../gemname/lib gets added to the search path. It is this potential for gems to claim file names from each other which drives conventions such as naming your main library file identically to the gem, but as long as one derives reasonably directly and/or uniquely from the other, it should be fine to use different names.

For a gem called google-search, the advice on Rubygems says users should expect to use the require as you want it, so you are following normal Ruby convention here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top