[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

how to define "global" function from within class method?

Its Me

11/8/2004 6:48:00 AM

I have defined class X. Anytime X is inherited (say, by Y), I want to
generate a global function definition
def y(...) { ... }

The hook I am using is
class X
def self.inherited(child)
...
end
end

What should go into the ...? Should it be

Object.class_eval "def #{child.name.downcase} ... end" ?

Thanks


2 Answers

Christoph R.

11/8/2004 8:04:00 AM

0

itsme213 schrieb:

>I have defined class X. Anytime X is inherited (say, by Y), I want to
>generate a global function definition
> def y(...) { ... }
>
>The hook I am using is
>class X
> def self.inherited(child)
> ...
> end
>end
>
>What should go into the ...? Should it be
>
>Object.class_eval "def #{child.name.downcase} ... end" ?
>
>
Well this should work, however, global functions are
usually private so you should use something along the
lines of

class X
def self.inherited(child)
::Object.class_eval <<-Body
private
def #{child.to_s.downcase}
p "hello from #{child}"
end
Body
end
private_class_method :inherited
end

class Y < X
end
y()

/Christoph

Robert Klemme

11/8/2004 9:30:00 AM

0


"itsme213" <itsme213@hotmail.com> schrieb im Newsbeitrag
news:xEEjd.34130$tL5.5547@fe2.texas.rr.com...
> I have defined class X. Anytime X is inherited (say, by Y), I want to
> generate a global function definition
> def y(...) { ... }
>
> The hook I am using is
> class X
> def self.inherited(child)
> ...
> end
> end
>
> What should go into the ...? Should it be
>
> Object.class_eval "def #{child.name.downcase} ... end" ?

How about

class X
def self.inherited(child)
Kernel.instance_eval do
define_method(child.name.downcase) do
puts "Method defined for #{child}"
end
end
end
end

class Y < X
end

>> y
Method defined for Y
=> nil

Kind regards

robert