[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

usage of Module.new

Daniel Schüle

6/18/2006 11:10:00 PM

Hello,

one can generate modules with

m = Module.new

m.module_eval do
def self.a;"a";end
def b;"b";end
end

but how can I 'include' them in a class

class A
include m # this doesn't work
end

is it possible?

Regards, Daniel
3 Answers

Tim Hunter

6/18/2006 11:33:00 PM

0

Schüle Daniel wrote:
> Hello,
>
> one can generate modules with
>
> m = Module.new
>
> m.module_eval do
> def self.a;"a";end
> def b;"b";end
> end
>
> but how can I 'include' them in a class
>
> class A
> include m # this doesn't work
> end
>
> is it possible?
>
> Regards, Daniel

Assign the module to a constant:

M = Module.new

and so on.

Daniel Schierbeck

6/19/2006 9:24:00 AM

0

Schüle Daniel wrote:
> one can generate modules with
>
> m = Module.new
>
> m.module_eval do
> def self.a;"a";end
> def b;"b";end
> end
>
> but how can I 'include' them in a class
>
> class A
> include m # this doesn't work
> end

As Tim said, you can assign the module to a constant. This isn't because
#include only accepts modules (that wouldn't even be possible, I think),
but rather it's a scoping issue.

class A
m = Module.new{define_method(:foo){"bar"}}
include m
end

Cheers,
Daniel

Daniel Schüle

6/19/2006 9:06:00 PM

0

[...]

>> class A
>> include m # this doesn't work
>> end
>
> As Tim said, you can assign the module to a constant. This isn't because
> #include only accepts modules (that wouldn't even be possible, I think),
> but rather it's a scoping issue.
>
> class A
> m = Module.new{define_method(:foo){"bar"}}
> include m
> end
>

I tried this third version :)

irb(main):004:0* $m = Module.new
=> #<Module:0x40233040>
irb(main):005:0> $m.module_eval do
irb(main):006:1* def self.a()""end
irb(main):007:1> def b()1;end
irb(main):008:1> end
=> nil
irb(main):009:0> $m.a
=> ""
irb(main):010:0> class A
irb(main):011:1> include $m
irb(main):012:1> end
=> A
irb(main):013:0> a = A.new
=> #<A:0x4020ec54>
irb(main):014:0> a.b
=> 1

it seems indeed that plain *m* is not seen
are constants handled special? (because M is seen)
and are globals seen anyway
or is this irb issue?

Thx, Daniel