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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Alexey P. (Guest)
on 2008-12-29 19:32
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 K. (Guest)
on 2008-12-29 20:17
(Received via mailing list)
2008/12/29 Alexey P. <removed_email_address@domain.invalid>:
>
>    class E
>        # include A::*
>        B; C; D;
>    end

robert@fussel ~
$ ruby <<EOF
> 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
Luis L. (Guest)
on 2008-12-29 20:25
(Received via mailing list)
On Dec 29, 3:32 pm, Alexey P. <removed_email_address@domain.invalid> wrote:
>
>     class E
>         # include A::*
>         B; C; D;
>     end
> --
> Posted viahttp://www.ruby-forum.com/.

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

module Bar
  include Foo
end

Bar::A.new

HTH,
Alexey P. (Guest)
on 2008-12-29 21:16
Thanks! :)
This topic is locked and can not be replied to.