Class: Mustermann::Flask::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/mustermann/flask.rb

Overview

A class for easy creating of converters.

See Also:

  • #register_converter

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#constraintObject

Constraint on the format used for the capture. Should be a regexp (or a string corresponding to a regexp)

See Also:

  • Mustermann::Flask#register_converter


45
46
47
# File 'lib/mustermann/flask.rb', line 45

def constraint
  @constraint
end

#convertObject

Callback Should be a Proc.

See Also:

  • Mustermann::Flask#register_converter


50
51
52
# File 'lib/mustermann/flask.rb', line 50

def convert
  @convert
end

Instance Method Details

#between(min, max) ⇒ Object

Makes sure a given value falls inbetween a min and a max. Uses the passed block to convert the value from a string to whatever format you’d expect.

Examples:

require 'mustermann/flask'

class MyPattern < Mustermann::Flask
  register_converter(:x) { between(5, 15, &:to_i) }
end

pattern = MyPattern.new('<x:id>')
pattern.params('/12') # => { 'id' => 12 }
pattern.params('/16') # => { 'id' => 15 }

See Also:

  • Mustermann::Flask#register_converter


87
88
89
90
91
92
93
94
# File 'lib/mustermann/flask.rb', line 87

def between(min, max)
  self.convert = proc do |input|
    value = yield(input)
    value = yield(min) if min and value < yield(min)
    value = yield(max) if max and value > yield(max)
    value
  end
end