class Mustermann::Flask

Flask style pattern implementation.

@example

Mustermann.new('/<foo>', type: :flask) === '/bar' # => true

@see Mustermann::Pattern @see file:README.md#flask Syntax description in the README

Attributes

converters[R]

Public Class Methods

converters(inherited = true) click to toggle source

Generally available converters. @!visibility private

# File lib/mustermann/flask.rb, line 101
def self.converters(inherited = true)
  return @converters ||= {} unless inherited
  defaults = superclass.respond_to?(:converters) ? superclass.converters : {}
  defaults.merge(converters(false))
end
new(input, converters: {}, **options) click to toggle source
Calls superclass method
# File lib/mustermann/flask.rb, line 193
def initialize(input, converters: {}, **options)
  @converters = self.class.converters.dup
  converters.each { |k,v| @converters[k.to_s] = v } if converters
  super(input, **options)
end
register_converter(name, converter = nil, &block) click to toggle source

Allows you to register your own converters.

It is reommended to use this on a subclass, so to not influence other subsystems using flask templates.

The object passed in as converter can implement convert and/or constraint.

It can also instead implement new, which will then return an object responding to some of these methods. Arguments from the flask pattern will be passed to new.

If passed a block, it will be yielded to with a {Mustermann::Flask::Converter} instance and any arguments in the flask pattern.

@example with simple object

require 'mustermann/flask'

MyPattern    = Class.new(Mustermann::Flask)
up_converter = Struct.new(:convert).new(:upcase.to_proc)
MyPattern.register_converter(:upper, up_converter)

MyPattern.new("/<up:name>").params('/foo') # => { "name" => "FOO" }

@example with block

require 'mustermann/flask'

MyPattern    = Class.new(Mustermann::Flask)
MyPattern.register_converter(:upper) { |c| c.convert = :upcase.to_proc }

MyPattern.new("/<up:name>").params('/foo') # => { "name" => "FOO" }

@example with converter class

require 'mustermann/flasl'

class MyPattern < Mustermann::Flask
  class Converter
    attr_reader :convert
    def initialize(send: :to_s)
      @convert = send.to_sym.to_proc
    end
  end

  register_converter(:t, Converter)
end

MyPattern.new("/<t(send=upcase):name>").params('/Foo')   # => { "name" => "FOO" }
MyPattern.new("/<t(send=downcase):name>").params('/Foo') # => { "name" => "foo" }

@param [#to_s] name converter name @param [#new, convert, constraint, nil] converter

# File lib/mustermann/flask.rb, line 156
def self.register_converter(name, converter = nil, &block)
  converter ||= Converter.create(&block)
  converters(false)[name.to_s] = converter
end