Oh!Coder

Coding Life

Addressable Gem简介

| Comments

今天记录的gem名叫addressable。Addressable是Ruby标准库的一部分,是实现URI的一种有效方案。它的实现尽可能的遵从RFC 3986,RFC 3987以及RFC 6570(level 4)标准,提供支持IRI和URI模版。

基本使用

安装

1
$ sudo gem install addressable

通过安装libidn和idn gem,可以开启本地IDN:

1
2
3
$ sudo apt-get install idn # Debian/Ubuntu
$ brew install libidn # OS X
$ gem install idn-ruby

参照

主要分为两个大的方面:

  • {Addressable::URI}
  • {Addressable::Template}

简单例子

1
2
3
4
5
6
7
8
9
10
11
12
13
require "addressable/uri"

uri = Addressable::URI.parse("http://example.com/path/to/resource/")
uri.scheme
#=> "http"
uri.host
#=> "example.com"
uri.path
#=> "/path/to/resource/"

uri = Addressable::URI.parse("http://www.詹姆斯.com/")
uri.normalize
#=> #<Addressable::URI:0xc9a4c8 URI:http://www.xn--8ws00zhy3a.com/>

URI Templates

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
require "addressable/template"

template = Addressable::Template.new("http://example.com/{?query*}/")
template.expand({
  "query" => {
    'foo' => 'bar',
    'color' => 'red'
  }
})
#=> #<Addressable::URI:0xc9d95c URI:http://example.com/?foo=bar&color=red>

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

template = Addressable::Template.new(
  "http://{host}{/segments*}/{?one,two,bogus}{#fragment}"
)
uri = Addressable::URI.parse(
  "http://example.com/a/b/c/?one=1&two=2#foo"
)
template.extract(uri)
#=>
# {
#   "host" => "example.com",
#   "segments" => ["a", "b", "c"],
#   "one" => "1",
#   "two" => "2",
#   "fragment" => "foo"
# }

此处用法更多详情可以参见RFC 6570

更多

此gem的更多详情可参见原文档

Comments