forked from ruby-oembed/ruby-oembed
-
Notifications
You must be signed in to change notification settings - Fork 0
/
provider.rb
71 lines (59 loc) · 1.91 KB
/
provider.rb
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
module OEmbed
class Provider
attr_accessor :format, :name, :url, :urls, :endpoint
def initialize(endpoint, format = :json)
@endpoint = endpoint
@urls = []
@format = format
end
def <<(url)
full, scheme, domain, path = *url.match(%r{([^:]*)://?([^/?]*)(.*)})
domain = Regexp.escape(domain).gsub("\\*", "(.*?)").gsub("(.*?)\\.", "([^\\.]+\\.)?")
path = Regexp.escape(path).gsub("\\*", "(.*?)")
@urls << Regexp.new("^#{Regexp.escape(scheme)}://#{domain}#{path}")
end
def build(url, options = {})
raise OEmbed::NotFound, url unless include?(url)
query = options.merge({:url => url})
endpoint = @endpoint.clone
if format_in_url?
format = endpoint["{format}"] = (query[:format] || @format).to_s
query.delete(:format)
else
format = query[:format] ||= @format
end
query_string = "?" + query.inject("") do |memo, (key, value)|
"#{key}=#{value}&#{memo}"
end.chop
URI.parse(endpoint + query_string).instance_eval do
@format = format; def format; @format; end
self
end
end
def raw(url, options = {})
uri = build(url, options)
res = Net::HTTP.start(uri.host, uri.port) do |http|
http.get(uri.request_uri)
end
case res
when Net::HTTPNotImplemented
raise OEmbed::UnknownFormat, uri.format
when Net::HTTPNotFound
raise OEmbed::NotFound, url
when Net::HTTPOK
res.body
else
raise OEmbed::UnknownResponse, res.code
end
end
def get(url, options = {})
OEmbed::Response.new(raw(url, options.merge(:format => :json)), self)
end
def format_in_url?
@endpoint.include?("{format}")
end
def include?(url)
@urls.empty? || !!@urls.detect{ |u| u =~ url }
end
end
end