Reputation: 1530
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
Reputation: 4382
You just write it:
# In some part of your codebase:
module Foo
end
# Extension:
module Foo
module Bar
end
end
Upvotes: -2
Reputation: 21740
Without (ugly) string eval:
module Foo
end
bar = Module.new
Foo.const_set(:Bar, bar)
Upvotes: 4
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