On Mon, Oct 02, 2006 at 05:45:52PM +0900, benjohn / fysh.org wrote:
> 
> I am dynamically creating modules [1]. I would like to be able to add
> methods and constants to the module using the "normal" notation:
> 
> module MyModule
>   def a_method; 'wibble'; end
> end
> 
> But the module doesn't have an constant associated with it, so I'm
> getting an error from...
> 
> class MyModuleClass < Module
>   def initialize(a_constant_to_go_in_module)
>     module self
>       K = a_constant_to_go_in_module
>       def a_method; end
>       ...
>     end
>   end
> end
> 
> Is there a way to do this, or do I have to start using the define_method
> and const_set methods?
> 
No, well at least not if you know the method name before hand.

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

> Cheers,
>   Benjohn
> 
> [1] These modules encapulate the behaviour of different types of
> message. There are quite a few types of message; while all different,
> they're sufficiently similar that the differences can be described in a
> table. It's easy to think of a class of types of message: a given
> message is an instance of a type of message.
>