Skip to content

Commit f4a1cc7

Browse files
committed
Add rubocop + fix all styling issues
1 parent 1267345 commit f4a1cc7

File tree

13 files changed

+330
-204
lines changed

13 files changed

+330
-204
lines changed

.rubocop.yml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Style/StringLiterals:
2+
EnforcedStyle: double_quotes
3+
4+
Metrics/LineLength:
5+
Max: 100
6+
7+
Style/TrailingComma:
8+
EnforcedStyleForMultiline: comma
9+
10+
#begin ruby 1.8 support
11+
Style/HashSyntax:
12+
EnforcedStyle: hash_rockets
13+
14+
Style/Lambda:
15+
Enabled: false

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ group :test do
66
gem "rspec"
77
gem "rack-test"
88
gem "webmock"
9+
gem "rubocop"
910
end
1011

1112
group :development, :test do

Rakefile

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
1-
require 'rubygems'
2-
require 'rake'
3-
require 'bundler/gem_tasks'
4-
require 'rspec/core/rake_task'
1+
require "rubygems"
2+
require "rake"
3+
require "bundler/gem_tasks"
4+
require "rspec/core/rake_task"
55

66
RSpec::Core::RakeTask.new(:spec) do |spec|
7-
spec.pattern = 'spec/**/*_spec.rb'
7+
spec.pattern = "spec/**/*_spec.rb"
88
end
99

1010
task :default => :spec

lib/rack/reverse_proxy.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
require "rack_reverse_proxy"
22

3+
# Re-opening Rack module only to define ReverseProxy constant
34
module Rack
45
ReverseProxy = RackReverseProxy::Middleware
56
end

lib/rack_reverse_proxy.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
require "rack_reverse_proxy/version"
12
require "rack_reverse_proxy/errors"
23
require "rack_reverse_proxy/matcher"
34
require "rack_reverse_proxy/middleware"
5+
6+
# A Reverse Proxy for Rack
7+
module RackReverseProxy
8+
end

lib/rack_reverse_proxy/errors.rb

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
module RackReverseProxy
22
module Errors
3+
# GenericURI indicates that url is too generic
34
class GenericURI < Exception
45
attr_reader :url
56

@@ -8,25 +9,27 @@ def intialize(url)
89
end
910

1011
def to_s
11-
%Q(Your URL "#{@url}" is too generic. Did you mean "http://#{@url}"?)
12+
%(Your URL "#{@url}" is too generic. Did you mean "http://#{@url}"?)
1213
end
1314
end
1415

16+
# AmbiguousMatch indicates that path matched more than one endpoint
1517
class AmbiguousMatch < Exception
1618
attr_reader :path, :matches
19+
1720
def initialize(path, matches)
1821
@path = path
1922
@matches = matches
2023
end
2124

2225
def to_s
23-
%Q(Path "#{path}" matched multiple endpoints: #{formatted_matches})
26+
%(Path "#{path}" matched multiple endpoints: #{formatted_matches})
2427
end
2528

2629
private
2730

2831
def formatted_matches
29-
matches.map {|matcher| matcher.to_s}.join(', ')
32+
matches.map(&:to_s).join(", ")
3033
end
3134
end
3235
end

lib/rack_reverse_proxy/matcher.rb

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,47 @@
11
module RackReverseProxy
2+
# FIXME: Enable them and fix issues during refactoring
3+
# rubocop:disable Metrics/MethodLength
4+
# rubocop:disable Metrics/AbcSize
5+
6+
# Matcher understands if specific url matches encapsulated rule or not
27
class Matcher
3-
def initialize(matcher, url=nil, options={})
4-
@default_url=url
5-
@url=url
6-
@options=options
8+
def initialize(matcher, url = nil, options = {})
9+
@default_url = url
10+
@url = url
11+
@options = options
712

8-
if matcher.kind_of?(String)
9-
@matcher = /^#{matcher.to_s}/
13+
if matcher.is_a?(String)
14+
@matcher = /^#{matcher}/
1015
elsif matcher.respond_to?(:match)
1116
@matcher = matcher
1217
else
13-
raise "Invalid Matcher for reverse_proxy"
18+
fail ArgumentError, "Invalid Matcher for reverse_proxy"
1419
end
1520
end
1621

17-
attr_reader :matcher,:url, :default_url,:options
22+
attr_reader :matcher, :url, :default_url, :options
1823

1924
def match?(path, *args)
2025
match_path(path, *args) ? true : false
2126
end
2227

23-
def get_uri(path,env)
28+
def get_uri(path, env)
2429
return nil if url.nil?
25-
_url=(url.respond_to?(:call) ? url.call(env) : url.clone)
26-
if _url =~/\$\d/
27-
match_path(path).to_a.each_with_index { |m, i| _url.gsub!("$#{i.to_s}", m) }
28-
URI(_url)
30+
realized_url = (url.respond_to?(:call) ? url.call(env) : url.clone)
31+
if realized_url =~ /\$\d/
32+
match_path(path).to_a.each_with_index { |m, i| realized_url.gsub!("$#{i}", m) }
33+
URI(realized_url)
2934
else
30-
default_url.nil? ? URI.parse(_url) : URI.join(_url, path)
35+
default_url.nil? ? URI.parse(realized_url) : URI.join(realized_url, path)
3136
end
3237
end
3338

3439
def to_s
35-
%Q("#{matcher.to_s}" => "#{url}")
40+
%("#{matcher}" => "#{url}")
3641
end
3742

3843
private
44+
3945
def match_path(path, *args)
4046
headers = args[0]
4147
rackreq = args[1]

lib/rack_reverse_proxy/middleware.rb

Lines changed: 56 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,44 @@
1-
require 'net/http'
2-
require 'net/https'
1+
require "net/http"
2+
require "net/https"
33
require "rack-proxy"
44

55
module RackReverseProxy
6+
# FIXME: Enable them and fix issues during refactoring
7+
# rubocop:disable Metrics/ClassLength
8+
# rubocop:disable Metrics/MethodLength
9+
# rubocop:disable Metrics/CyclomaticComplexity
10+
# rubocop:disable Metrics/PerceivedComplexity
11+
# rubocop:disable Metrics/AbcSize
12+
13+
# Rack middleware for handling reverse proxying
614
class Middleware
715
include NewRelic::Agent::Instrumentation::ControllerInstrumentation if defined? NewRelic
816

917
def initialize(app = nil, &b)
10-
@app = app || lambda {|env| [404, [], []] }
18+
@app = app || lambda { |_| [404, [], []] }
1119
@matchers = []
12-
@global_options = {:preserve_host => true, :x_forwarded_host => true, :matching => :all, :replace_response_host => false}
20+
@global_options = {
21+
:preserve_host => true,
22+
:x_forwarded_host => true,
23+
:matching => :all,
24+
:replace_response_host => false,
25+
}
1326
instance_eval(&b) if block_given?
1427
end
1528

1629
def call(env)
1730
rackreq = Rack::Request.new(env)
18-
matcher = get_matcher(rackreq.fullpath, Rack::Proxy.extract_http_request_headers(rackreq.env), rackreq)
31+
matcher = get_matcher(
32+
rackreq.fullpath,
33+
Rack::Proxy.extract_http_request_headers(rackreq.env),
34+
rackreq,
35+
)
1936
return @app.call(env) if matcher.nil?
2037

2138
if @global_options[:newrelic_instrumentation]
22-
action_name = "#{rackreq.path.gsub(/\/\d+/,'/:id').gsub(/^\//,'')}/#{rackreq.request_method}" # Rack::ReverseProxy/foo/bar#GET
39+
# Rack::ReverseProxy/foo/bar#GET
40+
action_path = rackreq.path.gsub(%r{/\d+}, "/:id").gsub(%r{^/}, "")
41+
action_name = "#{action_path}/#{rackreq.request_method}"
2342
perform_action_with_newrelic_trace(:name => action_name, :request => rackreq) do
2443
proxy(env, rackreq, matcher)
2544
end
@@ -31,40 +50,43 @@ def call(env)
3150
private
3251

3352
def proxy(env, source_request, matcher)
34-
uri = matcher.get_uri(source_request.fullpath,env)
35-
if uri.nil?
36-
return @app.call(env)
37-
end
53+
uri = matcher.get_uri(source_request.fullpath, env)
54+
return @app.call(env) if uri.nil?
55+
3856
options = @global_options.dup.merge(matcher.options)
3957

4058
# Initialize request
41-
target_request = Net::HTTP.const_get(source_request.request_method.capitalize).new(uri.request_uri)
59+
target_request = Net::HTTP.const_get(
60+
source_request.request_method.capitalize,
61+
).new(uri.request_uri)
4262

4363
# Setup headers
4464
target_request_headers = Rack::Proxy.extract_http_request_headers(source_request.env)
4565

4666
if options[:preserve_host]
4767
if uri.port == uri.default_port
48-
target_request_headers['HOST'] = uri.host
68+
target_request_headers["HOST"] = uri.host
4969
else
50-
target_request_headers['HOST'] = "#{uri.host}:#{uri.port}"
70+
target_request_headers["HOST"] = "#{uri.host}:#{uri.port}"
5171
end
5272
end
5373

5474
if options[:x_forwarded_host]
55-
target_request_headers['X-Forwarded-Host'] = source_request.host
56-
target_request_headers['X-Forwarded-Port'] = "#{source_request.port}"
75+
target_request_headers["X-Forwarded-Host"] = source_request.host
76+
target_request_headers["X-Forwarded-Port"] = "#{source_request.port}"
5777
end
5878

5979
target_request.initialize_http_header(target_request_headers)
6080

6181
# Basic auth
62-
target_request.basic_auth options[:username], options[:password] if options[:username] and options[:password]
82+
if options[:username] && options[:password]
83+
target_request.basic_auth options[:username], options[:password]
84+
end
6385

6486
# Setup body
6587
if target_request.request_body_permitted? && source_request.body
6688
source_request.body.rewind
67-
target_request.body_stream = source_request.body
89+
target_request.body_stream = source_request.body
6890
end
6991

7092
target_request.content_length = source_request.content_length || 0
@@ -79,16 +101,18 @@ def proxy(env, source_request, matcher)
79101
target_response.use_ssl = "https" == uri.scheme
80102

81103
# Let rack set the transfer-encoding header
82-
response_headers = Rack::Utils::HeaderHash.new Rack::Proxy.normalize_headers(format_headers(target_response.headers))
83-
response_headers.delete('Transfer-Encoding')
84-
response_headers.delete('Status')
104+
response_headers = Rack::Utils::HeaderHash.new(
105+
Rack::Proxy.normalize_headers(format_headers(target_response.headers)),
106+
)
107+
response_headers.delete("Transfer-Encoding")
108+
response_headers.delete("Status")
85109

86110
# Replace the location header with the proxy domain
87-
if response_headers['Location'] && options[:replace_response_host]
88-
response_location = URI(response_headers['location'])
111+
if response_headers["Location"] && options[:replace_response_host]
112+
response_location = URI(response_headers["location"])
89113
response_location.host = source_request.host
90114
response_location.port = source_request.port
91-
response_headers['Location'] = response_location.to_s
115+
response_headers["Location"] = response_location.to_s
92116
end
93117

94118
[target_response.status, response_headers, target_response.body]
@@ -102,26 +126,27 @@ def get_matcher(path, headers, rackreq)
102126
if matches.length < 1
103127
nil
104128
elsif matches.length > 1 && @global_options[:matching] != :first
105-
raise Errors::AmbiguousMatch.new(path, matches)
129+
fail Errors::AmbiguousMatch.new(path, matches)
106130
else
107131
matches.first
108132
end
109133
end
110134

111135
def reverse_proxy_options(options)
112-
@global_options=options
136+
@global_options = options
113137
end
114138

115-
def reverse_proxy(matcher, url=nil, opts={})
116-
raise Errors::GenericURI.new(url) if matcher.is_a?(String) && url.is_a?(String) && URI(url).class == URI::Generic
117-
@matchers << Matcher.new(matcher,url,opts)
139+
def reverse_proxy(matcher, url = nil, opts = {})
140+
if matcher.is_a?(String) && url.is_a?(String) && URI(url).class == URI::Generic
141+
fail Errors::GenericURI.new, url
142+
end
143+
@matchers << Matcher.new(matcher, url, opts)
118144
end
119145

120146
def format_headers(headers)
121-
headers.reduce({}) do |acc, (key, val)|
122-
formated_key = key.split('-').map(&:capitalize).join('-')
147+
headers.each_with_object({}) do |(key, val), acc|
148+
formated_key = key.split("-").map(&:capitalize).join("-")
123149
acc[formated_key] = Array(val)
124-
acc
125150
end
126151
end
127152
end

lib/rack_reverse_proxy/version.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#:nodoc:
12
module RackReverseProxy
23
VERSION = "0.9.1"
34
end

rack-reverse-proxy.gemspec

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,31 @@
1-
lib = File.expand_path('../lib', __FILE__)
1+
lib = File.expand_path("../lib", __FILE__)
22
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
3-
require 'rack_reverse_proxy/version'
3+
require "rack_reverse_proxy/version"
44

55
Gem::Specification.new do |spec|
66
spec.name = "rack-reverse-proxy"
77
spec.version = RackReverseProxy::VERSION
8-
spec.authors = ["Jon Swope", "Ian Ehlert", "Roman Ernst", "Oleksii Fedorov"]
9-
10-
spec.summary = %q{A Simple Reverse Proxy for Rack}
11-
spec.description = %q{A Rack based reverse proxy for basic needs. Useful for testing or in cases where webserver configuration is unavailable.}
8+
9+
spec.authors = [
10+
"Jon Swope",
11+
"Ian Ehlert",
12+
"Roman Ernst",
13+
"Oleksii Fedorov",
14+
]
15+
16+
spec.email = [
17+
18+
19+
20+
21+
]
22+
23+
spec.summary = "A Simple Reverse Proxy for Rack"
24+
spec.description = <<eos
25+
A Rack based reverse proxy for basic needs.
26+
Useful for testing or in cases where webserver configuration is unavailable.
27+
eos
28+
1229
spec.homepage = "https://github.com/waterlink/rack-reverse-proxy"
1330
spec.license = "MIT"
1431

0 commit comments

Comments
 (0)