Skip to content

Commit c0fab4f

Browse files
committed
[Rule] in the middle of refactoring (wip)
1 parent 2eb01ec commit c0fab4f

File tree

3 files changed

+86
-60
lines changed

3 files changed

+86
-60
lines changed

lib/rack_reverse_proxy.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
require "rack_reverse_proxy/version"
22
require "rack_reverse_proxy/errors"
3-
require "rack_reverse_proxy/matcher"
3+
require "rack_reverse_proxy/rule"
44
require "rack_reverse_proxy/middleware"
55

66
# A Reverse Proxy for Rack

lib/rack_reverse_proxy/matcher.rb

Lines changed: 0 additions & 59 deletions
This file was deleted.

lib/rack_reverse_proxy/rule.rb

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
module RackReverseProxy
2+
# Rule understands which urls need to be proxied
3+
class Rule
4+
# FIXME: It needs to be hidden
5+
attr_reader :options
6+
7+
def initialize(spec, url = nil, options = {})
8+
@default_url = url
9+
@url = url
10+
@options = options
11+
@spec = build_matcher(spec)
12+
end
13+
14+
def proxy?(path, *args)
15+
match_path(path, *args).count > 0
16+
end
17+
18+
# Lots of calls with passing path and env around
19+
# Sounds like a class to me, Candidate?
20+
def get_uri(path, env)
21+
return nil unless url
22+
evaluated_url = evaluate_url(env)
23+
if with_substitutions?(evaluated_url)
24+
substitute_matches(evaluated_url, path)
25+
else
26+
build_simple_url(evaluated_url, path)
27+
end
28+
end
29+
30+
def to_s
31+
%("#{spec}" => "#{url}")
32+
end
33+
34+
private
35+
36+
attr_reader :spec, :url, :default_url
37+
38+
def build_simple_url(url, path)
39+
return URI.parse(url) unless default_url
40+
URI.join(url, path)
41+
end
42+
43+
def evaluate_url(env)
44+
return url.clone unless url.respond_to?(:call)
45+
url.call(env)
46+
end
47+
48+
def with_substitutions?(url)
49+
url =~ /\$\d/
50+
end
51+
52+
# FIXME: This function currently is stressful for GC
53+
def substitute_matches(url, path)
54+
match_path(path).each_with_index do |match, i|
55+
url = url.gsub("$#{i}", match)
56+
end
57+
URI(url)
58+
end
59+
60+
def build_matcher(spec)
61+
return /^#{spec}/ if spec.is_a?(String)
62+
return spec if spec.respond_to?(:match)
63+
fail ArgumentError, "Invalid Rule for reverse_proxy"
64+
end
65+
66+
def match_path(path, *args)
67+
headers = args[0]
68+
rackreq = args[1]
69+
arity = spec.method(:match).arity
70+
if arity == -1
71+
match = spec.match(path)
72+
else
73+
params = [path, (@options[:accept_headers] ? headers : nil), rackreq]
74+
match = spec.match(*params[0..(arity - 1)])
75+
end
76+
# FIXME: This state mutation is very confusing
77+
@url = match.url(path) if match && default_url.nil?
78+
Array(match)
79+
end
80+
81+
# Candidate represents a path being verified
82+
class Candidate
83+
end
84+
end
85+
end

0 commit comments

Comments
 (0)