Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby module inside module

Tags:

module

ruby

I have a ruby module which includes many other modules. Here's a quick example:

module Foo

  module Bar
  end

  module Baz
  end

end

except, I have like 6-7 modules inside Foo module. Is there a way I can put Bar/Baz in separate file but still get the same behavior? Right now all my code is inside 1 file, very unorganized.

like image 391
0xSina Avatar asked Dec 12 '22 05:12

0xSina


1 Answers

You can define them like this, each in a separate file:

# foo.rb
module Foo
end

# foo_bar.rb
module Foo::Bar
end

# foo_baz.rb
module Foo::Baz
end

NB. You will need to define the Foo module before being able to define modules such as Foo::Bar with this notation.

Or you could just put them in differently named files in the format they're currently in and it should still work:

# foo_bar.rb
module Foo
  module Bar
  end
end

# foo_baz.rb
module Foo
  module Baz
  end
end
like image 185
Russell Avatar answered Dec 15 '22 00:12

Russell