开发者

Question about requiring files and the load path in Programming Ruby 1.9

开发者 https://www.devze.com 2023-03-15 01:50 出处:网络
I\'m reading through \"Programming Ruby 1.9\". On page 208 (in a \"Where to Put Tests\" section), the book has the code organized as

I'm reading through "Programming Ruby 1.9". On page 208 (in a "Where to Put Tests" section), the book has the code organized as

roman
    lib/
        roman.rb
        other files...
    test/
        test_roman.rb
        other_tests...
    other stuff

and asks how we get our test_roman.rb file to know about the roman.rb file.

It says that one option that doesn't work is to build the path into require statements in the test code:

# in test_roman.rb
require 'test/unit'
require '../lib/roman'

Instead, it says a better solution is for all other components of the application to assume that the top-level directory of the application is in Ruby's load path, so开发者_如何学JAVA that the test code would have

# in test_roman.rb
require 'test/unit'
require '/lib/roman'

and we'd run the tests by calling ruby -I path/to/app path/to/app/test/test_roman.rb.

My question is: is this realy the best way? It seems like

  1. If we simply replaced require '../lib/roman' in the first option with require_relative '../lib/roman', everything would work fine.
  2. The assumption in the second option (that all components have the top-level directory in Ruby's load path) only works because we pass the -I path/to/app argument, which seems a little messy.

Am I correct that replacing require with require_relative fixes all the problems? Is there any reason to prefer the second option anyways?


Further on, that same book makes use of require_relative (Chapter 16, Organizing your source code) in the context of testing, so yes, I would say that using it is a Good Thing, since it "always loads files from a path relative to the directory of the file that invokes it".

Of course, like @christiangeek noticed, require_relative is new in the 1.9 series, but there's a gem that provides you with the same functionality.

It might be worth pointing out that the Pickaxe too provides a little method you can stick in your code in the same chapter I mentioned before.


require_relative does make the code cleaner but is only available natively on Ruby > 1.9.2. Which means if you want want your code to be portable to versions of Ruby < 1.9.2 you need to use a extension or the regular require AFAIK. The book is most likely a) written before 1.9.2 became widespread or b) providing a example for lowest common denominator.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号