Hi --
Hello !
I have a rather tortured architecture where several classes should
share code for some class methods and for some instance methods. To fix
the ideas, I need that some class I define have:
def ThisClass.desc
return @desc
end
def desc
return self.class.desc
end
To do that, I define two modules
module BaseInclude
def desc
return self.class.desc
end
end
module BaseExtend
def desc
return @desc
end
end
and I include them with
class ThisClass
include BaseInclude
extend BaseExtend
end
That works perfectly fine. My question, then, is : is there a simpler
way ? I can't afford to have a shared ancestor for these classes.
Personally, I like your approach: you've grouped methods according to
plan, and then carried out the plan. There are more elaborate ways,
but this seems to work for you, and it's very clear.
Just to point you to a couple of possible variations:
You could make the module that's destined for the extend operation a
nested module inside the other. In fact, you'll sometimes see this:
module Something
def a_method
end
module ClassMethods
def some_class_level_method
end
end
end
followed by:
class MyClass
include Something
extend Something::ClassMethods
end
(And you can even hook the extend operation into the include operation
by defining an appropriate self.included hook method in Something, so
that you don't have to have a separate extend call.)
I use the name "ClassMethods" advisedly: it's a popular choice. It
has the disadvantage of being inaccurate, in the sense that the
methods inside it are instance methods. But as long as they're
destined to be class methods (which, after all, are really instance
methods of the singleton class of a class!), it might be a reasonable
name.
David
···
On Wed, 27 Sep 2006, Vincent Fourmond wrote:
--
David A. Black | dblack@wobblini.net
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org