Friday, January 30, 2009

nice module pattern

This is a really nice pattern for mixins. It allows for clear separation of instance and class methods and allows you to cleanly specify constants and call any class methods you need.

module VarkLogging
# any constants you want to define
VARK_LOG_MESSAGE = "vark log!"

def self.included(base)
base.send(:include, InstanceMethods)
base.send(:extend, ClassMethods)
base.class_eval do
# any class methods we need to call
alias_method_chain :add, :vark_logging
end
end

module InstanceMethods
def add_with_vark_logging(*args)
puts VARK_LOG_MESSAGE
add_without_vark_logging(*args)
end
end

module ClassMethods
def vark?
true
end
end
end

# and if you want to include it without altering the original class definition:
Logger.send(:include, VarkLogging)

No comments:

Post a Comment