Module: Juicer::Chainable

Included in:
CssCacheBuster, ImageEmbed, Merger::Base, Minifyer::ClosureCompiler, Minifyer::YuiCompressor
Defined in:
lib/juicer/chainable.rb

Overview

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

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

Add the chain_method to classes that includes the module



57
58
59
# File 'lib/juicer/chainable.rb', line 57

def self.included(base)
  base.extend(ClassMethods)
end

Instance Method Details

#next_in_chainObject

Get next command in chain



74
75
76
77
# File 'lib/juicer/chainable.rb', line 74

def next_in_chain
  @_next_in_chain ||= nil
  @_next_in_chain
end

#next_in_chain=(next_obj) ⇒ Object Also known as: set_next

Sets the next command in the chain



64
65
66
67
# File 'lib/juicer/chainable.rb', line 64

def next_in_chain=(next_obj)
  @_next_in_chain = next_obj
  next_obj || self
end