Class: Wrest::UriTemplate

Inherits:
Object
  • Object
show all
Defined in:
lib/wrest/uri_template.rb

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (UriTemplate) initialize(uri_pattern, options = {})



13
14
15
16
# File 'lib/wrest/uri_template.rb', line 13

def initialize(uri_pattern, options = {})
  @uri_pattern = uri_pattern.clone
  @options = options.clone
end

Instance Attribute Details

- (Object) uri_pattern (readonly)

Returns the value of attribute uri_pattern



12
13
14
# File 'lib/wrest/uri_template.rb', line 12

def uri_pattern
  @uri_pattern
end

Instance Method Details

- (Object) ==(other)



54
55
56
57
# File 'lib/wrest/uri_template.rb', line 54

def ==(other)
  return false if other.class != self.class
  return other.uri_pattern == self.uri_pattern 
end

- (Object) [](path)



50
51
52
# File 'lib/wrest/uri_template.rb', line 50

def [](path)
  UriTemplate.new(File.join(uri_pattern, path))
end

- (Object) to_uri(options = {})

Builds a new Wrest::Uri from this uri template by replacing the keys in the options that match with the corressponding values.

Example: template = UriTemplate.new("coathangers.com/:resource/:id.:format") template.to_uri(:resource => 'shen_coins', :id => 5, :format => :json)

> #<Wrest::Uri:0x1225514 @uri=#<URI::HTTP:0x9127d8 URL:localhost:3000/shen_coins/5.json>>

This feature can also be used to handle HTTP authentication where the username and password needs changing at runtime. However, this approach will fail if the password contains characters like ^ and @.

Note that beacuse because both HTTP Auth and UriTemplate use ':' as a delimiter, the pattern does look slightly weird, but it still works. Example: template = UriTemplate.new(":username::password@coathangers.com/:resource/:id.:format") template.to_uri(

:user => 'kaiwren',
:password => 'fupuppies',
:resource => 'portal',
:id => '1'

)

=> #<Wrest::Uri:0x18e0bec @uri=#<URI::HTTP:0x18e09a8 URL:http://kaiwren:fupuppies@coathangers.com/portal/1>>


42
43
44
45
46
47
48
# File 'lib/wrest/uri_template.rb', line 42

def to_uri(options = {})
 merged_options = @options.merge(options) 
  Wrest::Uri.new(merged_options.inject(uri_pattern.clone) do |uri_string, tuple| 
    key, value = tuple
    uri_string.gsub(":#{key.to_s}", value.to_s)
  end , @options)
end