Instance and Related Class Methods

M

Michael Guterl

I have a class with a lot of instance methods which are related to
class methods from within the same class.

Example:

class A
def initialize(start_date, end_date)
@start_date, @end_date = start_date, end_date
end

def total_hours
A.total_hours(@start_date, @end_date)
end

def self.total_hours(start_date, end_date)
self.sum:)hours, :conditions => between(start_date, end_date))
end

def total_incoming
A.total_incoming(@start_date, @end_date)
end

def self.total_incoming(start_date, end_date)
self.sum:)incoming, :conditions => between(start_date, end_date))
end

def total_outgoing
A.total_outgoing(@start_date, @end_date)
end

def self.total_outgoing(start_date, end_date)
self.sum:)outgoing, :conditions => between(start_date, end_date))
end
end

Everything works as expected. However, I am wondering if there is a
more Rubyish way of accomplishing this so I can avoid the repetition.
Any other suggestions are welcome. Thanks in advance.

Michael Guterl
 
E

Eero Saynatkari

Michael said:
I have a class with a lot of instance methods which are related to
class methods from within the same class.

Example:

<snip />

Everything works as expected. However, I am wondering if there is a
more Rubyish way of accomplishing this so I can avoid the repetition.
Any other suggestions are welcome. Thanks in advance.

The simplest thing would be to eliminate these calls on
the instances completely since no instance data is needed.

If you do want to do this, you can automate it by creating
a #method_missing handler for the instance methods--it will
check whether a class method by the same name exists and
then forward to it (falling back on the normal #method_missing
on failure).
 
E

Eero Saynatkari

Michael said:
I'm not sure I understand. I would like to have access to both class
and
instance methods. Basically some of my code looks like this.

Yes, I apologise, I misread this as a simpler scenario.
In your case, there is no simple automation unless you
can generalise how the mapping from instance- to class
methods would work (for example, if all the methods pass
@start_date and @end_date you could map it easily).

Alternately you could modify the class methods to accept
an instance and extract the data from it--while of course
still accepting the times when no instance is available.
This way you can automate a missing instance method mapping
to call the class method with the instance as the argument.
The #method_missing, er, method works for this.

There is no built-in way to achieve this, though.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top