Class: Hostrich
- Inherits:
-
Object
- Object
- Hostrich
- Defined in:
- lib/hostrich.rb,
lib/hostrich/version.rb
Constant Summary collapse
- VERSION =
'0.2.0'- @@hosts =
[]
Class Method Summary collapse
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, hosts = []) ⇒ Hostrich
constructor
A new instance of Hostrich.
Constructor Details
#initialize(app, hosts = []) ⇒ Hostrich
Returns a new instance of Hostrich.
16 17 18 19 |
# File 'lib/hostrich.rb', line 16 def initialize(app, hosts = []) @app = app @@hosts += Array(hosts) end |
Class Method Details
.hosts ⇒ Object
8 9 10 |
# File 'lib/hostrich.rb', line 8 def self.hosts @@hosts end |
.hosts=(array) ⇒ Object
12 13 14 |
# File 'lib/hostrich.rb', line 12 def self.hosts=(array) @@hosts = array end |
Instance Method Details
#call(env) ⇒ Object
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 |
# File 'lib/hostrich.rb', line 21 def call(env) return @app.call(env) if @@hosts.empty? # Extract suffix from current request host. match = nil @@hosts.detect { |host| match = env['HTTP_HOST'].match(/#{host}(\.[\.\w-]+)?/) } return @app.call(env) if match.nil? suffix = match[1] # Fake request host. # Eg. If request is made from http://example.com.dev or http://example.com.127.0.0.1.xip.io, # the Rack app will see it just as a request to http://example.com. env['HTTP_HOST'] = remove_suffix(env['HTTP_HOST'], suffix) env['SERVER_NAME'] = remove_suffix(env['SERVER_NAME'], suffix) # Get regular response from Rack app status, headers, body = @app.call(env) body.close if body.respond_to? :close chunks = [] body.each { |chunk| chunks << chunk.to_s } body = chunks.join # Add current host suffix in all response bodies, so that occurences of http://example.com # appear as http://example.com.dev or http://example.com.127.0.0.1.xip.io in the browser. body = [add_suffix(body, suffix)] # Do the same in response headers. This is important for cookies and redirects. headers = Hash[headers.map { |k,v| [k, add_suffix(v, suffix)] }] # Return hacked response [status, headers, body] end |