From: Josh Cheek Date: 2012-05-10T13:27:31+09:00 Subject: Re: How to make a given klass to include a module --e89a8fb20116ab63c604bfa7091e Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable On Wed, May 9, 2012 at 6:36 AM, I=F1aki Baz Castillo wrote: > Hi, simple code: > > ---------------------------- > module M > def hello > "HELLO" > end > end > > class A > end > > > klass =3D A > ---------------------------- > > Now I want to make an instance of klass (so an instance of A) but also > need that klass includes module M. > Note however that I cannot change class A definition since klass is > given in runtime by the user. > > NOTE: It must be efficient, I don't want to use eval and so. > > Thanks a lot. > > Since we don't want to change A, use a subclass. It will have all the behaviour of A, but you can include modules and so forth while leaving M in pristine condition. klass =3D Class.new(A) { include M } klass.new.hello # =3D> "HELLO" A.new.respond_to? :hello # =3D> false Alternatively, extend your instances: klass =3D A instance =3D klass.new instance.extend M instance.hello # =3D> "HELLO" A.new.respond_to? :hello # =3D> false Extending works by opening up the singleton class and including within it. This means the instance behaves as if A had M included, even though it doesn't. --e89a8fb20116ab63c604bfa7091e Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On Wed, May 9, 2012 at 6:36 AM, I=F1aki Baz Cast= illo <ibc@aliax.net> wrote:
Hi, simple code:

----------------------------
=A0module M
=A0 =A0def hello
=A0 =A0 =A0"HELLO"
=A0 =A0end
=A0end

=A0class A
=A0end


=A0klass =3D A
----------------------------

Now I want to make an instance of klass (so an instance of A) but also
need that klass includes module M.
Note however that I cannot change class A definition since klass is
given in runtime by the user.

NOTE: It must be efficient, I don't want to use eval and so.

Thanks a lot.


Since we don't wa= nt to change A, use a subclass. It will have all the behaviour of A, but yo= u can include modules and so forth while leaving M in pristine condition.

klass =3D Class.new(A) { include M }=A0
= klass.new.hello # =3D> "HELLO"
A.new.respond_to? :he= llo # =3D> false


Alternati= vely, extend your instances:

klass =3D A
instance =3D klass.new
=
instance.extend M
instance.hello # =3D> "HELLO"=
A.new.respond_to? :hello # =3D> false

Extending works by opening up the singleton class and including within it. = This means the instance behaves as if A had M included, even though it does= n't.
--e89a8fb20116ab63c604bfa7091e--