tags:

views:

85

answers:

1

If I have the following project structure

project/   
  lib/
    subproject/
      a.rb
      b.rb
      lib.rb

where lib.rb looks like this :-

module Subproject
  def foo
    do_some_stuff
  end
end

and a.rb and b.rb both need to mixin some methods within lib.rb and are both namespaced within a module like so :-

require 'subproject/lib'

module Subproject
  class A
    include Subproject

    def initialize()
      foo()
    end
  end
end

What does ruby do when it encounters the include statement? How does it know that I want to only include the mixin from lib.rb rather than the whole module which includes both class A and class B, is this based purely on the require of subproject/lib or am I getting it wrong and it is including the whole of the module, including the definitions of Class A and B within themselves?

+1  A: 

It is including the whole of the module. There is only one Subproject module, you've just reopened it in a.rb and b.rb and added classes A and B to it. I don't think require is related anyhow there.

BTW, you can always try it out in irb:

>> Subproject::A
=> Subproject::A
>> Subproject::A::A
=> Subproject::A
Mladen Jablanović
So if I just want to include lib.rb functions then I have to define it in a module called SubprojectLib or similar and just include that?
Steve Weet
That's correct.
Mladen Jablanović