Using Module as Namespace

When I was reading the book Metaprogramming Ruby, I came across how to use Module as a namespace and thought it’s pretty useful. So I’m sharing it in this post:

Consider the following:

CHILI_MULTIPLIER = 0
module SuperSpicy
   CHILI_MULTIPLIER = 99
end

print "CHILI_MULTIPLIER : ", CHILI_MULTIPLIER,"\n"
print "SuperSpicy::CHILI_MULTIPLIER : ", SuperSpicy::CHILI_MULTIPLIER,"\n"

Result:

CHILI_MULTIPLIER : 0
SuperSpicy::CHILI_MULTIPLIER : 99

When we’re inside a module, we can still refer to the outer Constant by adding :: in front of the Constant.

CHILI_MULTIPLIER = 0

module SuperSpicy
   CHILI_MULTIPLIER = 99

   class Curry
      print "CHILI_MULTIPLIER : ", CHILI_MULTIPLIER.to_s ,"\n"
      print "::CHILI_MULTIPLIER : ", ::CHILI_MULTIPLIER.to_s, "\n"
   end
end

Result:

CHILI_MULTIPLIER : 99
::CHILI_MULTIPLIER : 0

If you want to find out about how deep you’ve gotten into, you can use Module.nesting(), try this:

print "[outter most] Module.nesting() : ", Module.nesting(), "\n"
   module SuperSpicy
   print "[inside SuperSpicy] Module.nesting() : ", Module.nesting(), "\n"
   class Curry
      print "[inside Curry] Module.nesting() : ", Module.nesting(), "\n"
   end
end

Result:

[outter most] Module.nesting() : []
[inside SuperSpicy] Module.nesting() : [SuperSpicy]
[inside Curry] Module.nesting() : [SuperSpicy::Curry, SuperSpicy]

That’s it 🙂

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s