Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Placing Ruby `require` outside of a module definition?

Tags:

ruby

In Ruby, is it OK to place a require statement outside of a module definition? Will the require'd module still be available inside classes nested in the module?

For example, is this:

require 'baz'
module Foo
  class Bar
    # some code using Baz
  end
end 

the same as this?

module Foo
  require 'baz'
  class Bar
    # some code using Baz
  end
end 

and the same as this?

module Foo
  class Bar
    require 'baz'
    # some code using Baz
  end
end 
like image 681
professormeowingtons Avatar asked Feb 15 '23 00:02

professormeowingtons


1 Answers

You can put require anywhere. As you can see in the documentation here, constants and globals from the required file are always added the the global namespace. Best practice is generally to use require outside of any nesting, but some gems take advantage of the fact that it available anywhere to conditionally require files based on ruby logic, i.e

if some_boolean
  require 'file'
end
like image 135
Alex.Bullard Avatar answered May 10 '23 15:05

Alex.Bullard