Using 'include' but not poluting my namespace

M

Mike Austin

I noticed that if you 'include' a module within a method, it will polute the
namesapce that defines that method. I found a simple solution is to declare a
throw-away class, and execute my code in that. Is there a more better way to
achieve this?

# Pollutes current namespace
def init()
include Inertia

do_stuff_with_inertia()
end

# Doesn't polute namespace, but ugly
class DontPolute
include Inertia

do_stuff_with_inertia()
end


Mike
 
A

ara.t.howard

I noticed that if you 'include' a module within a method, it will polute the
namesapce that defines that method. I found a simple solution is to declare
a throw-away class, and execute my code in that. Is there a more better way
to achieve this?

# Pollutes current namespace
def init()
include Inertia

do_stuff_with_inertia()
end

# Doesn't polute namespace, but ugly
class DontPolute
include Inertia

do_stuff_with_inertia()
end


Mike

both pollute your namespace equally. the first pollutes class Object, the
second class DontPolute. remember that you're code in ruby, if not inside a
class, is inside the Object class. this allows you to pretend your coding
something like perl. i always write main programs like so

class Main
...
end

Main::new if $0 == __FILE__

to avoid any such issues.

if you are looking for a workaround you can also use

Module::new{ include Inertia ... }

regards.

-a
 
B

Brian Mattern

I noticed that if you 'include' a module within a method, it will polute
the namesapce that defines that method. I found a simple solution is to
declare a throw-away class, and execute my code in that. Is there a more
better way to achieve this?

# Pollutes current namespace
def init()
include Inertia

do_stuff_with_inertia()
end

# Doesn't polute namespace, but ugly
class DontPolute
include Inertia

do_stuff_with_inertia()
end


Mike

Instead of include, you may want:
require 'intertia'

This will load up inertia.rb, which i'm assuming contains either a class or a
module name Intertia. Then you can use it via Interia.new() or
Intertia::do_stuff_with_intertia().

Correct me if I'm misunderstanding what you're trying to do here.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,667
Latest member
DaniloB294

Latest Threads

Top