What does it mean to "pollute the global namespace"?


In ruby, some gems choose to "pollute the global namespace".

What does this mean?
How can I see where it's happening?
Why would a gem need to do this?

When faced with two gems that are polluting the global namespace and conflicting, what tradeoffs am I making when I choose to "isolate" one?

For example:

I'm using two gems that are both polluting the global namespace: pry and gli so I'm not able to place my binding.prys where I want anymore.

One solution is to wrap the entire cli in a module:

module Wrapper
  include GLI::App

  extend self
  program_desc "..."

  exit run ARGV

Now I'm able to use my binding.prys wherever I want.

Why did this work?
What tradeoffs am I making when I choose to do "isolate gli"? Or is it "isolate the GLI::App module"?

Show source
| ruby   | rubygems   | pry   | global-namespace   2016-12-31 09:12 1 Answers

Answers ( 1 )

  1. 2016-12-31 09:12

    Ruby has a singular root namespace shared by all code and any constants and globals you define there are universal through the whole application. This makes conflict inevitable if you're not careful about namespacing things.

    The module construct is there as a namespace primitive, all constants will be local to that, all classes defined within it. You can also use a class as a namespace if you prefer, it's up to you.

    Forcing the include of something into the root namespace is a big problem. That's usually only done in quick scripts that are fairly tiny and self-contained. That's a bad habit to get into when you're doing anything non-trivial as it mashes together all the constants and methods in those two contexts, potentially over-writing them.

◀ Go back