Method: Addressable::Template#expand

Defined in:
lib/addressable/template.rb

#expand(mapping, processor = nil, normalize_values = true) ⇒ Addressable::URI

Expands a URI template into a full URI.

The object should respond to either the validate or transform messages or both. Both the validate and transform methods should take two parameters: name and value. The validate method should return true or false; true if the value of the variable is valid, false otherwise. An InvalidTemplateValueError exception will be raised if the value is invalid. The transform method should return the transformed variable value as a String. If a transform method is used, the value will not be percent encoded automatically. Unicode normalization will be performed both before and after sending the value to the transform method.

Examples:

class ExampleProcessor
  def self.validate(name, value)
    return !!(value =~ /^[\w ]+$/) if name == "query"
    return true
  end

  def self.transform(name, value)
    return value.gsub(/ /, "+") if name == "query"
    return value
  end
end

Addressable::Template.new(
  "http://example.com/search/{query}/"
).expand(
  {"query" => "an example search query"},
  ExampleProcessor
).to_str
#=> "http://example.com/search/an+example+search+query/"

Addressable::Template.new(
  "http://example.com/search/{query}/"
).expand(
  {"query" => "an example search query"}
).to_str
#=> "http://example.com/search/an%20example%20search%20query/"

Addressable::Template.new(
  "http://example.com/search/{query}/"
).expand(
  {"query" => "bogus!"},
  ExampleProcessor
).to_str
#=> Addressable::Template::InvalidTemplateValueError

Parameters:

  • mapping (Hash)

    The mapping that corresponds to the pattern.

  • processor (#validate, #transform) (defaults to: nil)

    An optional processor object may be supplied.

  • normalize_values (Boolean) (defaults to: true)

    Optional flag to enable/disable unicode normalization. Default: true

Returns:



591
592
593
594
595
596
597
598
# File 'lib/addressable/template.rb', line 591

def expand(mapping, processor=nil, normalize_values=true)
  result = self.pattern.dup
  mapping = normalize_keys(mapping)
  result.gsub!( EXPRESSION ) do |capture|
    transform_capture(mapping, capture, processor, normalize_values)
  end
  return Addressable::URI.parse(result)
end