Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby, how to reference Root namespace?

Tags:

main

ruby

When I have a module like this:

module MyModule
  class MyClass
  end
end

I can access/modify MyModule referencing it:

MyModule.const_set("MY_CONSTANT", "value")

But what about the Root namespace, the :: one?, I'm looking for something like:

::.const_set("MY_CONSTANT", "value")

The const_set thing is just an example, please don't try to solve this concrete situation but the way of actually making reference to the Root namespace

like image 973
fguillen Avatar asked Jan 21 '14 15:01

fguillen


People also ask

What is Namespacing in Ruby?

Namespace in Ruby allows multiple structures to be written using hierarchical manner. Thus, one can reuse the names within the single main namespace. The namespace in Ruby is defined by prefixing the keyword module in front of the namespace name. The name of namespaces and classes always start from a capital letter.

Can you instantiate a module in Ruby?

You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module.

What is Scope Resolution operator Ruby?

The :: (scope resolution) operator is used to qualify hidden names so that you can still use them. You can use the unary scope operator if a namespace scope or global scope name is hidden by an explicit declaration of the same name in a block or class.

How modules work in Ruby?

In Ruby, modules are somewhat similar to classes: they are things that hold methods, just like classes do. However, modules can not be instantiated. I.e., it is not possible to create objects from a module. And modules, unlike classes, therefore do not have a method new .


1 Answers

What is the root object? If you mean main object, you can't set constant at this level:

TOPLEVEL_BINDING.eval('self').const_set("MY_CONSTANT", "value")
# NoMethodError: undefined method `const_set' for main:Object
#   from (irb):71
#   from /home/malo/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'

If you mean Object object, do as follows:

Object.const_set("MY_CONSTANT", "value")
# => "value"

then you can use at the main, or at any other level:

::MY_CONSTANT
# => "value"

Adding another confirmation

We can set a constant using Kernel or using Object and in both cases the constant will be accessible from the root namespace:

Kernel.const_set("KERNEL_CONSTANT", "value")
Object.const_set("OBJECT_CONSTANT", "value")

puts !!(defined? ::KERNEL_CONSTANT) # => true
puts !!(defined? ::OBJECT_CONSTANT) # => true

But if we set a constant in the root namespace this constant is actually set in Object and not in Kernel:

::ROOT_CONSTANT = "value"

puts !!(defined? Object::ROOT_CONSTANT) # => true
puts !!(defined? Kernel::ROOT_CONSTANT) # => false
like image 187
Малъ Скрылевъ Avatar answered Oct 05 '22 12:10

Малъ Скрылевъ