Include constants from one scope into another ( A::* )

A

Alexey Petrushin

Hello! Is there a way to include constants from one class into another?
Something like "include A::*"?

SAMPLE:

class A
class B; end
class C; end
class D; end
end

class E
# include A::*
B; C; D;
end
 
R

Robert Klemme

2008/12/29 Alexey Petrushin said:
Hello! Is there a way to include constants from one class into another?
Something like "include A::*"?

SAMPLE:

class A
class B; end
class C; end
class D; end
end

class E
# include A::*
B; C; D;
end

robert@fussel ~
$ ruby <<EOF
class A
class B; end
class C; end
class D; end
end

class E
B=::A::B
C=::A::C
D=::A::D
end
p E::C.new
EOF
#<A::C:0x1002ebc0>

robert@fussel ~
$

You can as well do something like this

class Module
def import_all(mod)
mod.constants.each do |c|
const_set(c, mod.const_get(c))
end
end
end

irb(main):016:0> class E
irb(main):017:1> import_all A
irb(main):018:1> end
=> ["C", "B", "D"]
irb(main):019:0> E::B.new
=> #<A::B:0x7ff60548>

Kind regards

robert
 
L

Luis Lavena

Hello! Is there a way to include constants from one class into another?
Something like "include A::*"?

SAMPLE:

    class A
        class B; end
        class C; end
        class D; end
    end

    class E
        # include A::*
        B; C; D;
    end

module Foo
class A; end
class B; end
class C; end
end

module Bar
include Foo
end

Bar::A.new

HTH,
 

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

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,278
Latest member
BuzzDefenderpro

Latest Threads

Top