class URITemplate::Colon

A colon based template denotes variables with a colon.

This template type is somewhat compatible with sinatra.

@example

tpl = URITemplate::Colon.new('/foo/:bar')
tpl.extract('/foo/baz') #=> {'bar'=>'baz'}
tpl.expand('bar'=>'boom') #=> '/foo/boom'

Constants

VAR

Attributes

pattern[R]

Public Class Methods

new(pattern) click to toggle source
# File lib/uri_template/colon.rb, line 159
def initialize(pattern)
  raise ArgumentError,"Expected a String but got #{pattern.inspect}" unless pattern.kind_of? String
  @pattern = pattern
end
try_convert(x) click to toggle source

Tries to convert the value into a colon-template. @example

URITemplate::Colon.try_convert('/foo/:bar/').pattern #=> '/foo/:bar/'
URITemplate::Colon.try_convert(URITemplate.new(:rfc6570, '/foo/{bar}/')).pattern #=> '/foo/{:bar}/'
# File lib/uri_template/colon.rb, line 147
def self.try_convert(x)
  if x.kind_of? String
    return new(x)
  elsif x.kind_of? self
    return x
  elsif x.kind_of? URITemplate::RFC6570 and x.level == 1
    return new( x.pattern.gsub(/\{(.*?)\}/u){ "{:#{$1}}" } )
  else
    return nil
  end
end

Public Instance Methods

extract(uri) { |result| ... } click to toggle source

Extracts variables from an uri.

@param uri [String] @return nil,Hash

# File lib/uri_template/colon.rb, line 168
def extract(uri)
  md = self.to_r.match(uri)
  return nil unless md
  result = {}
  splat = []
  self.tokens.select{|tk| tk.kind_of? URITemplate::Expression }.each_with_index do |tk,i|
    if tk.kind_of? Token::Splat
      splat << md[i+1]
      result['splat'] = splat unless result.key? 'splat'
    else
      result[tk.name] = Utils.unescape_url( md[i+1] )
    end
  end
  if block_given?
    return yield(result)
  end
  return result
end
to_r() click to toggle source
# File lib/uri_template/colon.rb, line 191
def to_r
  @regexp ||= Regexp.new('\A' + tokens.map(&:to_r).join + '\z', Utils::KCODE_UTF8)
end
tokens() click to toggle source
# File lib/uri_template/colon.rb, line 195
def tokens
  @tokens ||= tokenize!
end
type() click to toggle source
# File lib/uri_template/colon.rb, line 187
def type
  :colon
end

Protected Instance Methods

tokenize!() click to toggle source
# File lib/uri_template/colon.rb, line 201
def tokenize!
  number_of_splats = 0
  RegexpEnumerator.new(VAR).each(@pattern).map{|x|
    if x.kind_of? String
      Token::Static.new(Utils.escape_uri(x))
    elsif x[0] == '*'
      n = number_of_splats
      number_of_splats = number_of_splats + 1
      Token::Splat.new(n)
    else
      # TODO: when rubinius supports ambigious names this could be replaced with x['name'] *sigh*
      Token::Variable.new(x[1] || x[2])
    end
  }.to_a
end