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


usually, put of require statements @ top of file. while reading source code poltergeist, noticed following

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

actual source

what advantages of using require way?

the advantage in case capybara::poltergeist module exists before modules required. since modules extend capybara::poltergeist module, way ensure aren't loaded before module available. placing require statements after module definition have same effect.

consider 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 fail because non-nested foo::bar syntax expect foo exist time module called. changing first file to:

module foo   module bar     require './bar_module'   end end 

the require work, since foo::bar exist time bar_module starts doing thing.

in particular instance, doesn't have practical effect, since poltergeist uses nested module syntax (module foo; module bar) rather collapsed syntax (module foo::bar), it's practice delineates "these requires expect module exist".


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -