Creating modules

def initialize(a_constant_to_go_in_module)
self.module_eval do
K = a_constant_to_go_in_module
def a_method; ‘wibble’; end
end
end

Ah! I think that’s exactly what I want :slight_smile: Thanks, I’ll give it a try :slight_smile:

So, I’ve been having an experiment, and here’s what I’ve found so far…

irb(main):001:0> class MyModule < Module
irb(main):002:1> def initialize(k)
irb(main):003:2> module_eval {K=k}
irb(main):004:2> end
irb(main):005:1> end
SyntaxError: compile error
(irb):3: dynamic constant assignment
module_eval {K=k}
^
from (irb):5

But I can do…

irb(main):001:0> x=10
=> 10
irb(main):002:0> m=Module.new
=> #Module:0xb73ee938
irb(main):003:0> m.module_eval {K=x}
=> 10

However, if I then try…

irb(main):004:0> m::K
NameError: uninitialized constant #Module:0xb73ee938::K
from (irb):4
irb(main):005:0> m.constants
=> []

But I can do…

irb(main):006:0> m.const_get(:X)
NameError: uninitialized constant #Module:0xb73ee938::X
from (irb):6:in `const_get’
from (irb):6
irb(main):007:0> m.const_get(:K)
=> 10

!? Huh? I guess this is something to do with constants being looked up
in a global symbol pool?

Going back to trying to define a sub class of modules…

irb(main):009:0> vishnu in new_try# irb
irb(main):001:0> class MyModule < Module
irb(main):002:1> def initialize(x)
irb(main):003:2> super()
irb(main):004:2> module_eval do
irb(main):005:3* def f; x; end
irb(main):006:3> def self.g; x*x; end
irb(main):007:3> end
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0> m=MyModule.new(10)
=> #MyModule:0xb73ded44
irb(main):011:0> m.g
NameError: undefined local variable or method x' for #<MyModule:0xb73ded44> from (irb):6:ing’
from (irb):11
irb(main):012:0> Object.new.extend(m).f
NameError: undefined local variable or method x' for #<Object:0xb73d6270> from (irb):5:inf’
from (irb):12
irb(main):013:0>

…Which is a bit of a pitty.

I also briefly dabled with…

irb(main):018:0> class ParameterClass < Class
irb(main):019:1> end
TypeError: can’t make subclass of Class
from (irb):18
irb(main):020:0>

And turned away from that avenue.

I think I need a better idea of what is and isn’t possible here. I think
my understanding of the dark secrets is very little; I was hoping I’d
get away with that though, as I generally have with Ruby until now :slight_smile:

Cheers,
Benjohn