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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With