модуль Bundler::URI
Bundler::URI — это модуль, предоставляющий классы для работы с универсальными идентификаторами ресурсов (RFC2396).
Возможности
-
Единый способ работы с URI.
-
Гибкость введения пользовательских схем
Bundler::URI. -
Гибкость для использования альтернативного
Bundler::URI::Parser(или просто разных шаблонов и регулярных выражений).
Базовый пример
require 'bundler/vendor/uri/lib/uri'
uri = Bundler::URI("http://foo.com/posts?id=30&limit=5#time=1305298413")
#=> #<Bundler::URI::HTTP http://foo.com/posts?id=30&limit=5#time=1305298413>
uri.scheme #=> "http"
uri.host #=> "foo.com"
uri.path #=> "/posts"
uri.query #=> "id=30&limit=5"
uri.fragment #=> "time=1305298413"
uri.to_s #=> "http://foo.com/posts?id=30&limit=5#time=1305298413"
Добавление пользовательских URI
module Bundler::URI
class RSYNC < Generic
DEFAULT_PORT = 873
end
@@schemes['RSYNC'] = RSYNC
end
#=> Bundler::URI::RSYNC
Bundler::URI.scheme_list
#=> {"FILE"=>Bundler::URI::File, "FTP"=>Bundler::URI::FTP, "HTTP"=>Bundler::URI::HTTP,
# "HTTPS"=>Bundler::URI::HTTPS, "LDAP"=>Bundler::URI::LDAP, "LDAPS"=>Bundler::URI::LDAPS,
# "MAILTO"=>Bundler::URI::MailTo, "RSYNC"=>Bundler::URI::RSYNC}
uri = Bundler::URI("rsync://rsync.foo.com")
#=> #<Bundler::URI::RSYNC rsync://rsync.foo.com>
Ссылки на RFC
Хорошее место для просмотра спецификаций RFC — www.ietf.org/rfc.html.
Вот список всех соответствующих RFC:
Class дерево
-
Bundler::URI::Generic(в uri/generic.rb)-
Bundler::URI::File- (в uri/file.rb) -
Bundler::URI::FTP- (в uri/ftp.rb) -
Bundler::URI::HTTP- (в uri/http.rb)-
Bundler::URI::HTTPS- (в uri/https.rb)
-
-
Bundler::URI::LDAP- (в uri/ldap.rb)-
Bundler::URI::LDAPS- (в uri/ldaps.rb)
-
-
Bundler::URI::MailTo- (в uri/mailto.rb)
-
-
Bundler::URI::Parser- (в uri/common.rb) -
Bundler::URI::REGEXP- (в uri/common.rb)-
Bundler::URI::REGEXP::PATTERN - (в uri/common.rb)
-
-
Bundler::URI::Util - (в uri/common.rb)
-
Bundler::URI::Escape- (в uri/common.rb) -
Bundler::URI::Error- (в uri/common.rb)-
Bundler::URI::InvalidURIError- (в uri/common.rb) -
Bundler::URI::InvalidComponentError- (в uri/common.rb) -
Bundler::URI::BadURIError- (в uri/common.rb)
-
Информация об авторских правах
- Автор
-
Akira Yamada <akira@ruby-lang.org>
- Документация
-
Akira Yamada <akira@ruby-lang.org> Dmitry V. Sabanin <sdmitry@lrn.ru> Vincent Batts <vbatts@hashbangbash.com>
- Лицензия
-
Авторские права © 2001 akira yamada <akira@ruby-lang.org> Вы можете распространять и/или изменять его на тех же условиях, что и Ruby.
- Ревизия
-
$Id$
Константы
- DEFAULT_PARSER
- Parser
- REGEXP
- RFC3986_PARSER
Методы публичного класса
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 454
def self.decode_www_form(str, enc=Encoding::UTF_8, separator: '&', use__charset_: false, isindex: false)
raise ArgumentError, "the input of #{self.name}.#{__method__} must be ASCII only string" unless str.ascii_only?
ary = []
return ary if str.empty?
enc = Encoding.find(enc)
str.b.each_line(separator) do |string|
string.chomp!(separator)
key, sep, val = string.partition('=')
if isindex
if sep.empty?
val = key
key = +''
end
isindex = false
end
if use__charset_ and key == '_charset_' and e = get_encoding(val)
enc = e
use__charset_ = false
end
key.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
if val
val.gsub!(/\+|%\h\h/, TBLDECWWWCOMP_)
else
val = +''
end
ary << [key, val]
end
ary.each do |k, v|
k.force_encoding(enc)
k.scrub!
v.force_encoding(enc)
v.scrub!
end
ary
end Декодирует данные формы URL, закодированные по данным str.
Декодирует данные application/x-www-form-urlencoded и возвращает массив массивов ключ-значение.
Ссылается на url.spec.whatwg.org/#concept-urlencoded-parser, поэтому поддерживает только разделитель '&', и не поддерживает разделитель ';'.
ary = Bundler::URI.decode_www_form("a=1&a=2&b=3")
ary #=> [['a', '1'], ['a', '2'], ['b', '3']]
ary.assoc('a').last #=> '1'
ary.assoc('b').last #=> '3'
ary.rassoc('a').last #=> '2'
Hash[ary] #=> {"a"=>"2", "b"=>"3"}
См. Bundler::URI.decode_www_form_component, Bundler::URI.encode_www_form.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 386
def self.decode_www_form_component(str, enc=Encoding::UTF_8)
raise ArgumentError, "invalid %-encoding (#{str})" if /%(?!\h\h)/ =~ str
str.b.gsub(/\+|%\h\h/, TBLDECWWWCOMP_).force_encoding(enc)
end Декодирует заданные str данных формы URL.
Декодирует + в пробел.
См. Bundler::URI.encode_www_form_component, Bundler::URI.decode_www_form.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 418
def self.encode_www_form(enum, enc=nil)
enum.map do |k,v|
if v.nil?
encode_www_form_component(k, enc)
elsif v.respond_to?(:to_ary)
v.to_ary.map do |w|
str = encode_www_form_component(k, enc)
unless w.nil?
str << '='
str << encode_www_form_component(w, enc)
end
end.join('&')
else
str = encode_www_form_component(k, enc)
str << '='
str << encode_www_form_component(v, enc)
end
end.join('&')
end Генерирует данные формы URL из заданных enum.
Генерирует данные application/x-www-form-urlencoded, определённые в HTML5, из объекта Enumerable.
Внутренне использует Bundler::URI.encode_www_form_component(str).
Этот метод не преобразует кодировку заданных элементов, поэтому преобразуйте их перед вызовом этого метода, если вы хотите отправить данные в кодировке, отличной от исходной, или с смешанной кодировкой. (Строки, закодированные в кодировке, несовместимой с HTML5 ASCII, преобразуются в UTF-8.)
Этот метод не обрабатывает файлы. При отправке файла используйте multipart/form-data.
Ссылается на url.spec.whatwg.org/#concept-urlencoded-serializer
Bundler::URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
#=> "q=ruby&lang=en"
Bundler::URI.encode_www_form("q" => "ruby", "lang" => "en")
#=> "q=ruby&lang=en"
Bundler::URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
#=> "q=ruby&q=perl&lang=en"
Bundler::URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
#=> "q=ruby&q=perl&lang=en"
См. Bundler::URI.encode_www_form_component, Bundler::URI.decode_www_form.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 368
def self.encode_www_form_component(str, enc=nil)
str = str.to_s.dup
if str.encoding != Encoding::ASCII_8BIT
if enc && enc != Encoding::ASCII_8BIT
str.encode!(Encoding::UTF_8, invalid: :replace, undef: :replace)
str.encode!(enc, fallback: ->(x){"&##{x.ord};"})
end
str.force_encoding(Encoding::ASCII_8BIT)
end
str.gsub!(/[^*\-.0-9A-Z_a-z]/, TBLENCWWWCOMP_)
str.force_encoding(Encoding::US_ASCII)
end Кодирует заданные str в данные формы URL.
Этот метод не преобразует *, -, ., 0-9, A-Z, _, a-z, но преобразует SP (пробел ASCII) в + и преобразует остальные символы в %XX.
Если enc задан, преобразуйте str в кодировку перед кодированием в процентах.
Это реализация www.w3.org/TR/2013/CR-html5-20130806/forms.html#url-encoded-form-data.
См. Bundler::URI.decode_www_form_component, Bundler::URI.encode_www_form.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 298 def self.extract(str, schemes = nil, &block) warn "Bundler::URI.extract is obsolete", uplevel: 1 if $VERBOSE DEFAULT_PARSER.extract(str, schemes, &block) end
Описание
Bundler::URI::extract(str[, schemes][,&blk])
Аргументы
-
str -
Stringдля извлечения URI из неё. -
schemes -
Ограничение
Bundler::URIсоответствия определёнными схемами.
Описание
Извлекает URI из строки. Если блок задан, итерирует по всем совпавшим URI. Возвращает nil, если блок задан, или массив с совпадениями.
Использование
require "bundler/vendor/uri/lib/uri"
Bundler::URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# => ["http://foo.example.com/bla", "mailto:test@example.com"]
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 270 def self.join(*str) RFC3986_PARSER.join(*str) end
Описание
Bundler::URI::join(str[, str, ...])
Аргументы
-
str -
Строка(и) для работы, будут преобразованы в URI RFC3986 перед объединением.
Описание
Объединяет URI.
Использование
require 'bundler/vendor/uri/lib/uri'
Bundler::URI.join("http://example.com/","main.rbx")
# => #<Bundler::URI::HTTP http://example.com/main.rbx>
Bundler::URI.join('http://example.com', 'foo')
# => #<Bundler::URI::HTTP http://example.com/foo>
Bundler::URI.join('http://example.com', '/foo', '/bar')
# => #<Bundler::URI::HTTP http://example.com/bar>
Bundler::URI.join('http://example.com', '/foo', 'bar')
# => #<Bundler::URI::HTTP http://example.com/bar>
Bundler::URI.join('http://example.com', '/foo/', 'bar')
# => #<Bundler::URI::HTTP http://example.com/foo/bar>
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 233 def self.parse(uri) RFC3986_PARSER.parse(uri) end
Описание
Bundler::URI::parse(uri_str)
Аргументы
-
uri_str -
StringсоBundler::URI.
Описание
Создаёт экземпляр одного из подклассов Bundler::URI из строки.
Возбуждает
-
Bundler::URI::InvalidURIError -
Возбуждается, если переданный
Bundler::URIне является корректным.
Использование
require 'bundler/vendor/uri/lib/uri'
uri = Bundler::URI.parse("http://www.ruby-lang.org/")
# => #<Bundler::URI::HTTP http://www.ruby-lang.org/>
uri.scheme
# => "http"
uri.host
# => "www.ruby-lang.org"
Рекомендуется сначала ::escape предоставленный uri_str , если есть какие-либо недопустимые символы Bundler::URI.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 335 def self.regexp(schemes = nil) warn "Bundler::URI.regexp is obsolete", uplevel: 1 if $VERBOSE DEFAULT_PARSER.make_regexp(schemes) end
Описание
Bundler::URI::regexp([match_schemes])
Аргументы
-
match_schemes -
Arrayсхем. Если задано, результирующее регулярное выражение соответствует URI, схема которого является одной из схем match_schemes.
Описание
Возвращает объект Regexp, который соответствует строкам типа Bundler::URI. Объект Regexp, возвращаемый этим методом, содержит произвольное количество групп захвата (скобки). Никогда не полагайтесь на их количество.
Использование
require 'bundler/vendor/uri/lib/uri' # extract first Bundler::URI from html_string html_string.slice(Bundler::URI.regexp) # remove ftp URIs html_string.sub(Bundler::URI.regexp(['ftp']), '') # You should not rely on the number of parentheses html_string.scan(Bundler::URI.regexp) do |*matches| p $& end
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 144 def self.scheme_list @@schemes end
Возвращает Hash определённых схем.
# File lib/bundler/vendor/uri/lib/uri/common.rb, line 196 def self.split(uri) RFC3986_PARSER.split(uri) end
Описание
Bundler::URI::split(uri)
Аргументы
-
uri
Описание
Разделяет строку на следующие части и возвращает массив с результатом:
-
Схема
-
Пользователь/пароль
-
Хост
-
Порт
-
Регистр
-
Путь
-
Непрозрачная часть
-
Запрос
-
Фрагмент
Использование
require 'bundler/vendor/uri/lib/uri'
Bundler::URI.split("http://www.ruby-lang.org/")
# => ["http", nil, "www.ruby-lang.org", nil, nil, "/", nil, nil, nil]
Ruby Core © 1993–2017 Yukihiro Matsumoto
Licensed under the Ruby License.
Ruby Standard Library © contributors
Licensed under their own licenses.