Adding a directory to $LOAD_PATH (Ruby)

前端 未结 7 1119
广开言路
广开言路 2020-11-28 01:48

I have seen two commonly used techniques for adding the directory of the file currently being executed to the $LOAD_PATH (or $:). I see the advantages of doing this in case

7条回答
  •  被撕碎了的回忆
    2020-11-28 02:12

    I'm not too fond on the 'quick-and-dirty' way. Anyone new to Ruby will be pondering what $:. is.

    I find this more obvious.

    libdir = File.dirname(__FILE__)
    $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
    

    Or if I care about having the full path...

    libdir = File.expand_path(File.dirname(__FILE__))
    $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
    

    UPDATE 2009/09/10

    As of late I've been doing the following:

    $:.unshift(File.expand_path(File.dirname(__FILE__))) unless
        $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__)))
    

    I've seen it in a whole bunch of different ruby projects while browsing GitHub.

    Seems to be the convention?

提交回复
热议问题