Jian Weihang Jian Weihang - 2 months ago 25
Ruby Question

require file inside module?

I saw the following source code in someone's repository:

module Twitter
module Bootstrap
module Rails
require 'twitter/bootstrap/rails/engine' if defined?(Rails)
end
end
end

require 'less-rails'
require 'twitter/bootstrap/rails/bootstrap' if defined?(Rails)


Source

I want to know what's difference when we put
require
in a module?

Answer

There is no difference as far as the require is concerned, i.e., require always loads the file into the global namespace.

It should be noted that, in this case, the inner require will always run, since Rails at that point refers to the module it is within, so the if statement there will always evaluate to true.

This means the code is equivalent to the possibly less confusing:

module Twitter
  module Bootstrap
    module Rails
    end
  end
end

require 'twitter/bootstrap/rails/engine'
require 'less-rails'
require 'twitter/bootstrap/rails/bootstrap' if defined?(Rails)