[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

Calling class method from instance method

Yu-shan Fung

4/7/2008 8:59:00 AM

Pretty dumb question -- how do I call a class method from inside an
instance method (of the same class)?

The use case I have is that in an activerecord model class, I would like
to define an instance method which calls find_by_sql.

I have tried and found that this works:
self.class.find_by_sql


But this seems pretty verbose for something so obvious.

Thanks!
--
Posted via http://www.ruby-....

2 Answers

Stefano Crocco

4/7/2008 9:12:00 AM

0

On Monday 07 April 2008, Yu-shan Fung wrote:
> Pretty dumb question -- how do I call a class method from inside an
> instance method (of the same class)?
>
> The use case I have is that in an activerecord model class, I would like
> to define an instance method which calls find_by_sql.
>
> I have tried and found that this works:
> self.class.find_by_sql
>
>
> But this seems pretty verbose for something so obvious.
>
> Thanks!

You can replace self.class with the name of the class. For example:

class C

def C.x
end

def y
self.class.x
C.x
end

end

There's a difference, however. If you derive a class from C and override C.x
from D:

class D < C
def self.x
end
end

using self.class.x from C#y will use the version of x defined in the
instance's class (that is, C.x if called by an instance of C and D.x if called
by an instance of D). Using C.x will, obviously, always call C.x. Here's some
code which demonstrates this:

class C
def self.x
puts "x of C"
end

def y
self.class.x
end

def z
C.x
end
end

class D < C
def self.x
puts "x of D"
end
end

puts "Calling y on an instance of C"
C.new.y
puts "Calling y on an instance of D"
D.new.y
puts "Calling z on an instance of D"
D.new.z

I hope this helps

Stefano

David A. Black

4/7/2008 9:13:00 AM

0

Hi --

On Mon, 7 Apr 2008, Yu-shan Fung wrote:

> Pretty dumb question -- how do I call a class method from inside an
> instance method (of the same class)?
>
> The use case I have is that in an activerecord model class, I would like
> to define an instance method which calls find_by_sql.
>
> I have tried and found that this works:
> self.class.find_by_sql
>
>
> But this seems pretty verbose for something so obvious.

You need the 'self.' part because class is a keyword. It's a bit
verbose but something's got to give :-)


David

--
Rails training from David A. Black and Ruby Power and Light:
ADVANCING WITH RAILS April 14-17 New York City
INTRO TO RAILS June 9-12 Berlin
ADVANCING WITH RAILS June 16-19 Berlin
See http://www.r... for details and updates!