T5i
T5i

Reputation: 1530

Define a module inside a module

Having the following module:

module Foo
end

How can we add inside this Foo module another module from its name (with for example: name = 'Bar')?

I would like to dynamically get this:

module Foo
  module Bar
  end
end

Upvotes: 0

Views: 121

Answers (3)

TuteC
TuteC

Reputation: 4382

You just write it:

# In some part of your codebase:
module Foo
end

# Extension:
module Foo
  module Bar
  end
end

Upvotes: -2

Reactormonk
Reactormonk

Reputation: 21740

Without (ugly) string eval:

module Foo
end

bar = Module.new
Foo.const_set(:Bar, bar)

Upvotes: 4

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230551

That's pretty straightforward:

module Foo
end

name = 'Bar'

Foo.class_eval <<RUBY
  module #{name}
  end
RUBY

puts Foo::Bar
# >> Foo::Bar

Upvotes: 1

Related Questions