Forum: Ruby Nesting Includes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
listrecv (Guest)
on 2005-11-15 03:08
(Received via mailing list)
Hi.  I'd like to include one module, which would include other modules
into my namespace.  Is this doable?

Doing this:
----file1.rb
module AAA
  include bbb
end

----file2.rb
include AAA

does not seem to include bbb.  Is there anyway to do this, or do I need
to add the include explicilty to file2 as well?

(Note - I understand the need for this, to avoid namespace collisions).
Sean O. (Guest)
on 2005-11-15 04:42
(Received via mailing list)
On 11/15/05, removed_email_address@domain.invalid 
<removed_email_address@domain.invalid> wrote:
> include AAA
>
> does not seem to include bbb.  Is there anyway to do this, or do I need
> to add the include explicilty to file2 as well?
>
Hi, you need to require the files you want:

----bbb.rb
module BBB
  def bbb
    puts "bbb"
  end
end

----aaa.rb
require 'bbb'

module AAA
  include BBB
end

---- test-nested-includes.rb
require 'aaa'
include AAA
bbb

---- OUTPUT
bbb

Regards,

Sean
gwtmp01 (Guest)
on 2005-11-15 05:06
(Received via mailing list)
On Nov 14, 2005, at 8:07 PM, removed_email_address@domain.invalid wrote:
>
> does not seem to include bbb.  Is there anyway to do this, or do I
> need
> to add the include explicilty to file2 as well?

It seems like you are thinking (in the way that I did while learning
Ruby)
that Ruby's 'include' facility is analogous to the C/C++ include
mechanism.
Same keyword but totally unrelated semantics.

As Sean indicated, use 'require' to have ruby parse a file and use
'include'
to mixin modules (i.e. to dynamically construct the hierarchy of
modules/classes).
You have to make sure that Ruby has parsed a module definition via
'require' before
it will be available for use via 'include'.  If your modules were all
defined
in a single file, it would look like:

module B
   # definition of module B
end

module A
   include B
   # more parts of A
end

include A

So if B is defined in 'file1.rb' and A is defined in 'file2.rb' you
could
access those definitions in a third file as:

	require 'file1'    # now B is defined, for use by A
	require 'file2'    # now A is defined, using B

	include A	   # module A is included into the current scope (top level)






Gary W.
This topic is locked and can not be replied to.