Wednesday, May 14, 2008

Conditional includes

This little problem came up at work a few days ago: what if you want to include a module but, based on the including class, get some different behavior? Enter conditional includes.

module Foo
module Bar
def hello
puts "hi from bar"
end
end

module Baz
def hello
puts "hi from baz"
end
end

def self.included(klass)
if klass.to_s == "Blah"
klass.send(:include,Bar)
else
klass.send(:include,Baz)
end
end
end


Of course, we can change the conditional logic to fit our needs. Now we'll include this module into two classes:

class Blah
include Foo
end

class Barf
include Foo
end

Blah.new.hello # => 'hi from bar'
Barf.new.hello # => 'hi from baz'


Yahoo! We get different behavior from each class without exposing the complexity to the end user.

1 comments:

bayesian said...

yeah self.included is pretty slick.