Forum: Ruby Reshuffling namespaces freely?

4828d528e2e46f7c8160c336eb332836?d=identicon&s=25 Robert Heiler (shevegen)
on 2014-07-26 15:22
Are there simple ways to reshuffle namespaces?

Consider file foo.rb with this code:

  class Foo
  end

Let's assume someone else wrote this code, so I can not
easily modify it.

Can I put it into a namespace upon load-time, or lateron?

Consider the same code, but put in a module or a class.

Is there a way for me to reshuffle this into another namespace?

For instance, if I don't like a top namespace as class, I'd like to have
the option to put it into a module forcibly.

Example:

class Bar
  class Foo
  end
end

Otherwise, same code as above.

And of course the last example:

module Bar
  class Foo
  end
end
54404bcac0f45bf1c8e8b827cd9bb709?d=identicon&s=25 7stud -- (7stud)
on 2014-07-26 22:56
Robert Heiler wrote in post #1153580:
> Are there simple ways to reshuffle namespaces?
>
> Consider file foo.rb with this code:
>
>   class Foo
>   end
>
> Let's assume someone else wrote this code, so I can not
> easily modify it.
>
> 1) Can I put it into a namespace upon load-time, or lateron?
>

> And of course the last example:
>
> module Bar
>   class Foo
>   end
> end

Because a module is a namespace, question #1 and #3 are the same:

#foo.rb ------

class Foo
  def greet
    puts 'hello'
  end
end

#-----------


A = Module.new
code = File.read('foo.rb')
A.module_eval(code)

A::Foo.new.greet
Foo.new.greet


--output:--
hello
1.rb:5:in `<main>': uninitialized constant Foo (NameError)


> Example:
>
> class Bar
>   class Foo
>   end
> end
>

A = Class.new
code = File.read('foo.rb')
A.class_eval(code)

class A
  Foo.new.greet
end

Foo.new.greet

--output:--
hello
1.rb:9:in `<main>': uninitialized constant Foo (NameError)
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.