[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

extend an object using string as module name?

konsu

12/9/2005 2:38:00 AM

hello,

is this a proper way to do it:

name = 'MyModule'
o = Object.new
o.extend(Module.const_get(name))


are there better ways?

thanks
konstantin

5 Answers

Ara.T.Howard

12/9/2005 3:51:00 AM

0

Ross Bamford

12/9/2005 12:43:00 PM

0

On Thu, 08 Dec 2005 18:37:43 -0800, ako... wrote:

> hello,
>
> is this a proper way to do it:
>
> name = 'MyModule'
> o = Object.new
> o.extend(Module.const_get(name))
>
>

I don't know if this is the proper way, but you could just eval the name:

name = 'MyModule'
o = Object.new
o.extend( eval name )

Or alternatively:

eval("o.extend #{name}")

--
Ross Bamford - rosco@roscopeco.remove.co.uk
"\e[1;31mL"

Mauricio Fernández

12/9/2005 2:03:00 PM

0

On Fri, Dec 09, 2005 at 12:50:40PM +0900, ara.t.howard@noaa.gov wrote:
> this will fail for "ModuleA::ModuleB". for that you need something like:
>
> #
> # creates a class by class name
> #
> def klass_stamp(hierachy, *a, &b)
> #--{{{
> ancestors = hierachy.split(%r/::/)
> parent = Object
> while((child = ancestors.shift))
> klass = parent.const_get child
> parent = klass
> end
> klass::new(*a, &b)
> #--}}}
> end

def klass_stamp(name, *a, &b)
name.split(/::/).inject(Object){|s,x| s.const_get(x)}.new(*a,&b)
end

class A; class B; def foo; "A::B#foo" end end end
klass_stamp("A::B").foo # => "A::B#foo"

> this will work for
>
> m = klass_stamp "A::B::C::Module"
# ^
# that would try to instantiate the module
m = "A::B::C::Module".split(/::/).inject(Object){|s,x| s.const_get(x)}
> o = Object::new
> o.extend m

PS: have you seen http://eigenclass.org/hiki.rb?Usable+Ruby+foldi... ?
It might be of interest to you if you often use manual markers for
methods...

--
Mauricio Fernandez


Trans

12/9/2005 2:40:00 PM

0

require 'facet/kernel/constant'

name = 'MyModule'
o = Object.new
o.extend(constant(name))

T.

Ara.T.Howard

12/9/2005 3:15:00 PM

0