Method: Addressable::Template#partial_expand

Defined in:
lib/vendor/addressable/lib/addressable/template.rb

#partial_expand(mapping, processor = nil) ⇒ Addressable::Template

Expands a URI template into another URI template.

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:

Addressable::Template.new(
  "http://example.com/{one}/{two}/"
).partial_expand({"one" => "1"}).pattern
#=> "http://example.com/1/{two}/"

Addressable::Template.new(
  "http://example.com/search/{-list|+|query}/"
).partial_expand(
  {"query" => "an example search query".split(" ")}
).pattern
#=> "http://example.com/search/an+example+search+query/"

Addressable::Template.new(
  "http://example.com/{-join|&|one,two}/"
).partial_expand({"one" => "1"}).pattern
#=> "http://example.com/?one=1{-prefix|&two=|two}"

Addressable::Template.new(
  "http://example.com/{-join|&|one,two,three}/"
).partial_expand({"one" => "1", "three" => 3}).pattern
#=> "http://example.com/?one=1{-prefix|&two=|two}&three=3"


367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/vendor/addressable/lib/addressable/template.rb', line 367

def partial_expand(mapping, processor=nil)
  result = self.pattern.dup
  transformed_mapping = transform_mapping(mapping, processor)
  result.gsub!(
    /#{OPERATOR_EXPANSION}|#{VARIABLE_EXPANSION}/
  ) do |capture|
    if capture =~ OPERATOR_EXPANSION
      operator, argument, variables, default_mapping =
        parse_template_expansion(capture, transformed_mapping)
      expand_method = "expand_#{operator}_operator"
      if ([expand_method, expand_method.to_sym] & private_methods).empty?
        raise InvalidTemplateOperatorError,
          "Invalid template operator: #{operator}"
      else
        send(
          expand_method.to_sym, argument, variables,
          default_mapping, true
        )
      end
    else
      varname, _, vardefault = capture.scan(/^\{(.+?)(=(.*))?\}$/)[0]
      if transformed_mapping[varname]
        transformed_mapping[varname]
      elsif vardefault
        "{#{varname}=#{vardefault}}"
      else
        "{#{varname}}"
      end
    end
  end
  return Addressable::Template.new(result)
end