Robert Klemme | 1 Jun 2008 11:34
Gravatar

Re: Class Module

On 01.06.2008 02:16, David A. Black wrote:
> Hi --
> 
> On Sun, 1 Jun 2008, Wesley Silva wrote:
> 
>> Thanks a lot David!
>>
>> I would like to make another question please...:)
>>
>> If i just change Modules's name for Father for example:
>>
>> class Father
>>   <at>  <at> docs = {}
>>  def doc(str)
>>     <at>  <at> docs[self.name] = self.name + ":\n" + str.gsub(/^\s+/, '')
>>  end
>>  def Father::show_doc(aClass)
>>    aClass = aClass.name if aClass.class <= Module
>>     <at>  <at> docs[aClass] || "No documentation for #{aClass}"
>>  end
>> end
>> class Example<Father
>>  doc("This is a sample documentation string")
>> end
>>
>> puts Father::show_doc(Example)
>>
>> Produces:
>>
>> undefined method `doc' for Example:Class (NoMethodError)
>>
>> Can you tell why? :)
> 
> doc is an instance method of Father, and Example is not an instance of
> Father (it's an instance of Class). So you can't call doc on Example.

Wesley, IMHO there is an easier as well as safer solution: safer, 
because a class's name may be unset.  Also, your solution keeps 
documentation of all classes in memory even if they are GC'ed (if that's 
possible, I am not sure).  So here's what I'd do:

class Module
   def doc(str = nil)
     if str
        <at> doc = (name + ":\n" + str.strip).freeze
     else
        <at> doc
     end
   end
end

Kind regards

	robert


Gmane