Module | Juicer::Chainable |
In: |
lib/juicer/chainable.rb
|
Facilitates the chain of responsibility pattern. Wraps given methods and calls them in a chain.
To make an object chainable, simply include the module and call the class method chain_method for each method that should be chained.
Example is a simplified version of the Wikipedia one (en.wikipedia.org/wiki/Chain-of-responsibility_pattern)
class Logger include Juicer::Chainable ERR = 3 NOTICE = 5 DEBUG = 7 def initialize(level) @level = level end def log(str, level) if level <= @level write str else abort_chain end end def write(str) puts str end chain_method :message end class EmailLogger < Logger def write(str) p "Logging by email" # ... end end logger = Logger.new(Logger::NOTICE) logger.next_in_chain = EmailLogger.new(Logger::ERR) logger.log("Some message", Logger::DEBUG) # Ignored logger.log("A warning", Logger::NOTICE) # Logged to console logger.log("An error", Logger::ERR) # Logged to console and email