Do Ruby 'require' statements go inside or outside the class definition?
Technically, it doesn't really matter. require
is just a normal method call, and the scope it's called in doesn't affect how it works. The only difference placement makes is that it will be executed when whatever code it's placed in is evaluated.
Practically speaking, you should put them at top so people can see the file's dependencies at a glance. That's the traditional place for it.
I can see a possible reason for not putting a require
at the top of the file: where it's expensive to load and not always executed. One case that occurs to me is where, for example, code and its tests are in the same file, which is something I like to do from time to time for small library code in particular. Then I can run the file from my editor and the tests run. In this case when the file is require
d in from elsewhere, I don't want test/unit
to be loaded.
Something a little like this:
def some_useful_library_function() return 1endif __FILE__ == $0 require 'test/unit' class TestUsefulThing < Test::Unit::TestCase def test_it_returns_1 assert_equal 1, some_useful_library_function() end endend