module DecoratorDsl

DSL for Decorator to define before and after hooks for a wrapped method

Public Class Methods

extended(receiver) click to toggle source

Injects the DSL attributes in the class received

@param receiver [Class] the class extending DecoratorDsl

@return [Void]

@api private

# File lib/decorator_dsl.rb, line 16
def self.extended(receiver)
  class << receiver
    private

    attr_accessor :before_method, :before_set,
                  :after_method, :after_set,
                  :around_method, :around_set
  end
end

Public Instance Methods

after() click to toggle source

Adds the next method to be hook into executing after decorated method

@return [Void]

@example

class DecoratorDemo < Decorator
  after
  def print_message
    puts "'#{decorated_class}' has '#{decorated_method.name}' decorated"
  end
end

class Demo
  extend Decorations

  decorate DecoratorDemo
  def demo_method
    puts 'am I decorated?'
  end
end

demo = Demo.new
demo.demo_method
# => am I decorated?
# => 'Demo' has 'demo_method' decorated

@api public

# File lib/decorator_dsl.rb, line 87
def after
  @after_method ||= Set.new
  @after_set = true
end
around() click to toggle source

Adds the next method to be hook into executing around decorated method

@return [Void]

@example

class DecoratorDemo < Decorator
  around
  def print_message
    puts "'#{decorated_class}' has '#{decorated_method.name}' decorated"
    yield
    puts "'#{decorated_class}' has '#{decorated_method.name}' decorated"
  end
end

class Demo
  extend Decorations

  decorate DecoratorDemo
  def demo_method
    puts 'am I decorated?'
  end
end

demo = Demo.new
demo.demo_method
# => am I decorated?
# => 'Demo' has 'demo_method' decorated

@api public

# File lib/decorator_dsl.rb, line 122
def around
  @around_method ||= Set.new
  @around_set = true
end
before() click to toggle source

Adds the next method to be hook into executing before decorated method

@return [Void]

@example

class DecoratorDemo < Decorator
  before :print_message
  def print_message
    puts "'#{decorated_class}' has '#{decorated_method.name}' decorated"
  end
end

class Demo
  extend Decorations

  decorate DecoratorDemo
  def demo_method
    puts 'am I decorated?'
  end
end

demo = Demo.new
demo.demo_method
# => 'Demo' has 'demo_method' decorated
# => am I decorated?

@api public

# File lib/decorator_dsl.rb, line 54
def before
  @before_method ||= Set.new
  @before_set = true
end

Private Instance Methods

method_added(name) click to toggle source

Hooks the methods defined for a class

@param name [Symbol] the name of the method being defined

@return [Void]

@api private

# File lib/decorator_dsl.rb, line 137
def method_added(name) # rubocop:disable Metrics/MethodLength
  if before_set
    @before_set = false
    @before_method << name
  end

  if after_set
    @after_set = false
    @after_method << name
  end

  return unless around_set

  @around_set = false
  @around_method << name
end