Gregory Seidman
1/11/2007 4:34:00 PM
On Fri, Jan 12, 2007 at 12:55:09AM +0900, Greg Hurrell wrote:
[...]
> Specifically, just say I add some methods to an existing standard class
> like Array, what would be the best convention for choosing where to
> store the added code? Here's a concrete example: let's say I want to
> add a "eol?" method to the StringScanner class?
>
> class StringScanner
> def eol?
> return true if self.eos? or self.match?(/[\n\r]/)
> false
> end
> end
In many cases it is not necessary to reopen existing classes at all, and is
often preferable not to. For your example, I would guess that you are doing
some sort of parsing, maybe something like (pseudo-Ruby, because I don't
really know StringScanner):
scanner = StringScanner.new(open(filename))
scanner.each do |token|
if scanner.eol?
#do stuff
else
#do other stuff
end
end
You need scanner to respond to #eol?, but you don't need to modify
StringScanner to do it. Consider using a module:
module StringScannerEol
def eol?
# cleaned up a little
self.eos? or self.match?(/[\n\r]/)
end
end
Now we change the first line of the code above to:
scanner = StringScanner.new(open(filename)).extend(StringScannerEol)
Now scanner will respond to #eol? and all is well.
> At the moment I have stuck it inside another file (for one of the
> classes that needs to use this method). But what if I want to keep it
> in a separate file? What would be the conventional name for such a file
> (evidently not "strscan.rb" because that would most likely cause
> confusion with the StringScanner implementation when doing a "require
> 'strscan'").
The module I gave above can be appropriately included in the file with the
code that uses it.
> Likewise I had a similar doubt when I wanted to added some assertions
> of my own in addition to those which come with Test::Unit::Assertions.
[...]
Again, a good opportunity for a module. Your test classes can include a
module with the additional assertions.
--Greg