Module: Tool::Decoration

Defined in:
lib/tool/decoration.rb

Overview

Mixin for easy method decorations.

Examples:

class Frank
  extend Tool::Decoration
  def self.get(path, &block)
    decorate(block) do |method|
      puts "mapping GET #{path} to #{method}"
    end
  end
end

# Output:
#   mapping GET /hi to __generated1
#   mapping GET / to index
#   mapping GET /index.php to index
class MyApp < Frank
  get '/hi' do
    "Hello World"
  end

  get '/'; get '/index.php'
  def index
    "This is the index page."
  end
end

Instance Method Summary collapse

Instance Method Details

#decorate(block = nil, name: "generated") {|method| ... } ⇒ Object

Set up a decoration.

Parameters:

  • block (Proc, UnboundMethod, nil) (defaults to: nil)

    used for defining a method right away

  • name (String, Symbol) (defaults to: "generated")

    given to the generated method if block is given

Yields:

  • callback called with method name once method is defined

Yield Parameters:

  • method (Symbol)

    name of the method that is to be decorated



67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/tool/decoration.rb', line 67

def decorate(block = nil, name: "generated", &callback)
  @decorations << callback

  if block
    alias_name = "__" << name.to_s.downcase.gsub(/[^a-z]+/, ?_) << ?1
    alias_name = alias_name.succ while respond_to? alias_name, true
    without_decorations { define_method(name, &block) }
    alias_method(alias_name, name)
    remove_method(name)
    private(alias_name)
  end
end

#without_decorations { ... } ⇒ Object

Runs a given block without applying decorations defined outside of the block. Decorations defined before the block will still be registered after the block.

Yields:

  • block to run without decorations



84
85
86
87
88
89
# File 'lib/tool/decoration.rb', line 84

def without_decorations
  @decorations.clear if was = @decorations.to_a.dup
  yield
ensure
  @decorations.replace(was) if was
end