Roman Trofimov
Roman Trofimov

Reputation: 109

Ruby: How to include namespaced classes into global namespace in IRB

For some reason I want to use namespaced Classes/Modules as they are in global namespace in IRB.

For example I have module MyCore and class MyUser inside it. Is there any mechanism or hook for IRB to include MyCore::MyUser in a way I can call just MyUser.new without prefixing it with MyCore?

Upvotes: 4

Views: 2903

Answers (4)

Spec
Spec

Reputation: 445

i research about this problem and i found this talking & scripts

but i thought this gem wrap_in_module does the best practise

wrap_in_module

hope it helps.

Upvotes: 0

BroiSatse
BroiSatse

Reputation: 44725

You can always do

MyUser = MyCore::MyUser

If you want to get all the included modules/classes:

MyCore.constants.each do |const|
  Object.const_set(const, MyCore.const_get(const))
end

Upvotes: 0

Uri Agassi
Uri Agassi

Reputation: 37419

You can simply do

include MyCore

myUser = MyUser.new

Using include adds all the constants in the module to you current class.

class WhereIWantToIncludeMyCore
  include MyCore

  def initialize
    user = MyUser.new
  end
end

If you want to be able to do that everywhere, you can add it outside the scope of a class, which will include it to Object.

Upvotes: 4

Kostas Rousis
Kostas Rousis

Reputation: 6098

You could do something like

MU = MyCore::MyUser

and use the alias you defined for subsequent calls.

Upvotes: 0

Related Questions