Monday, January 1, 2007

define_method

I frequently find myself writing the exact same method over and over with only minor differences between them (I'm sure there are plenty of design patterns to get around this in every language). One way of getting around this in ruby without much fuss is 'define_method'. Here's a snippet from Widi:


['header', 'footer'].each do |m|
define_method('generate_' + m) {
@widi_config = WEBrick::Config::Widi
file = @widi_config[m.capitalize.to_sym]
if
file =~ /rhtml/ && File.exists?(file)
data = open(file) {|io| io.read}
return
ERB.new(data).result(binding)
elsif file.nil?
constant = self.class.to_s + '::DEFAULT_' + m.upcase
return
constant.split('::').inject(Object) do |x,y|
x.const_get(y)
end
end
}
end
Once that code is run the encompassing class will have two methods called 'generate_header' and 'generate_footer'. This approach would be more justifiable if I needed more than just two methods so I may end up ripping it out.

One thing that did not behave how I expected was Module#const_get. It doesn't handle the ::'s nicely and I had to use an idiom I found in The Ruby Way.

1 comment:

brenton said...

uy.. I need to find a better way to do html syntax highlighting. This was made with enscript and I think blogger is messing it up.

Tags

my google reader feed