-
Notifications
You must be signed in to change notification settings - Fork 6
hook module idiom
tqbf edited this page Sep 13, 2010
·
2 revisions
Ruckus::Structure was getting extremely unwieldy.
The idiom I’m now using to add more features to it is as follows. First, assume the following:
class Structure
def method
# do a bunch of stuff
# do a bunch more stuff
return ret
end
end
We want to add functionality in between the two comment lines:
class Structure
def method
# do a bunch of stuff
# 80 more lines of inserted code
# do a bunch more stuff
return ret
end
end
Instead, we do this:
class Structure
include EightyLinesOfCode
def method_hook(*args); super; end
def method
# do a bunch of stuff
method_hook
# do a bunch more stuff
return ret
end
end
module EightyLinesOfCode
def included(klass); klass.extend(ClassMethods); end
module ClassMethods
# no classmethods needed this time, but keep the boilerplate
end
def method_hook(*args)
# 80 lines of code now goes here
# do we want to chain this hook? are we NOT the last hook called? then:
super
end
end
Easy enough. We’ll use hooks to create extension points wherever we need them in Structure, reusing as many as possible.
What’s the win? Structure now just does the core structure stuff. Random new features can be added to the ruckus/structure directory, and new features don’t cloud up the already-complicated core structure stuff.