Ben Poon
Ben Poon

Reputation: 125

Nested Module namespacing? Ruby

Given the following code structure...

module Foo
  module Bar
    class A
    end
  end
  class B
    def initialize(stuff)
    ...
    end
  end
end

How could I call B's .new method from within class A ?

And, is there a way to do it dynamically, if perhaps I had a string that was the class name I wanted to access?

Upvotes: 0

Views: 63

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

module Foo
  module Bar
    class A
    end
  end
  class B
    def initialize(stuff)
      puts "I like #{stuff}"
    end
  end
end

From anywhere you could invoke:

include Foo
klass = "B"
Module.const_get(klass).send(:new, "cats")
  #=> "I like cats"

Upvotes: 1

fotanus
fotanus

Reputation: 20116

This is how you call it statically:

module Foo
  class B
    def initialize(stuff)
    end
  end
  module Bar
    class A
      puts Foo::B.new(1)
    end
  end
end

To call it dinamically, check @CarySwoveland answer. You will need to use the methods const_get and send.

Upvotes: 0

Related Questions