Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the advantages of using `require` inside a module instead of at the top?

Tags:

ruby

Usually, I put most of my require statements at the top of a file. While reading the source code for Poltergeist, I noticed the following

module Capybara
  module Poltergeist
    require 'capybara/poltergeist/utility'
    require 'capybara/poltergeist/driver'
    require 'capybara/poltergeist/browser'
    # more requires
  end
end

Actual source

What are the advantages of using require this way?

like image 957
James Lim Avatar asked Aug 15 '13 18:08

James Lim


2 Answers

The advantage in this case is that the Capybara::Poltergeist module exists before those modules are required. Since those modules all extend the Capybara::Poltergeist module, this is just a way to ensure that they aren't loaded before the module is actually available. Placing the require statements after the module definition would have the same effect.

Consider the following:

# foobar.rb
require './bar_module'

module Foo
  module Bar
  end
end

# bar_module.rb
module Foo::Bar
   def baz
     "hi!"
   end
end

This setup will fail because the non-nested Foo::Bar syntax will expect Foo to already exist by the time this module is called. By changing the first file to:

module Foo
  module Bar
    require './bar_module'
  end
end

The require will work, since Foo::Bar will exist by the time that bar_module starts doing its thing.

In this particular instance, it doesn't have much practical effect, since Poltergeist uses the nested module syntax (module Foo; module Bar) rather than the collapsed syntax (module Foo::Bar), but it's a good practice that basically delineates "these requires expect this module to exist".

like image 167
Chris Heald Avatar answered Sep 25 '22 07:09

Chris Heald


I don't know what's the advantage in your example.

I sometimes use require inside a method definition.

I do this for methods which are used rarely, but need large libraries. The advantage: The large library is only loaded, when it is really needed.

require checks, if the library is already loaded. So I have no problem with double loading a library.

like image 21
knut Avatar answered Sep 25 '22 07:09

knut