I have a gem installed but require 'gemname' does not work. Why?

前端 未结 11 1790
傲寒
傲寒 2020-12-14 00:02

The question I\'m really asking is why require does not take the name of the gem. Also, In the case that it doesn\'t, what\'s the easiest way to find the secret incantation

相关标签:
11条回答
  • 2020-12-14 00:24

    My system also doesn't seem to know about RubyGems' existence - unless I tell it to. The 'require' command gets overwritten by RubyGems so it can load gems, but unless you have RubyGems already required it has no idea how to do that. So if you're writing your own, you can do:

    require 'rubygems'
    require 'gem-name-here'
    

    If you're running someone else's code, you can do it on the command line with:

    ruby -r rubygems script.rb
    

    Also, there's an environment variable Ruby uses to determine what it should load up on startup:

    export RUBYOPT=rubygems
    

    (from http://www.rubygems.org/read/chapter/3. The environment variable thing was pointed out to me by Orion Edwards)

    (If "require 'rubygems' doesn't work for you, however, this advice is of limited help :)

    0 讨论(0)
  • 2020-12-14 00:24

    The question I'm really asking is why require does not take the name of the gem.

    Installing a gem gets the files onto your system. It doesn't make any claims as to what those files will be called.
    As laurie points out there are several conventions for how they are named, but there's nothing to enforce that, and many gem authors unfortunately don't stick to them.

    Also, In the case that it doesn't, what's the easiest way to find the secret incantation to require the damn thing!?

    Read the docs for your gem?
    I find googling for rdoc gemname will usually find the official rdocs for your gem, which usually show you how to use it.

    Memcache is perhaps not the best example, as they assume you'll be using it from rails, and the 'require' will have already been done for you, but most other ones I've seen have examples which show the correct 'require' incantations

    0 讨论(0)
  • 2020-12-14 00:24

    Watch source of gem and check lib directory. If there is no rb file then you must point to gem main rb file in subdirectory:

    require 'dir/subdir/file'
    

    for /lib/dir/subdir/file.rb.

    0 讨论(0)
  • 2020-12-14 00:25

    An issue I just ran into was that the actual built gem was not including all the files that it should have.

    The issue with files was that there was a syntax mistake in the in the gemspec, but no errors were thrown during the build.

    Just adding this here in case anybody else runs into the same issue.

    0 讨论(0)
  • 2020-12-14 00:36

    I had this problem because I use rvm and was trying to use the wrong version of ruby. The gem in question needed 1.9.2 and I had set 2.0.0 as my default! Maybe a dumb error but one that someone else arriving on this page will probably have made.

    0 讨论(0)
提交回复
热议问题