1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actionpack/lib/action_dispatch/http/url.rb

378 lines
12 KiB
Ruby
Raw Normal View History

require 'active_support/core_ext/module/attribute_accessors'
module ActionDispatch
module Http
module URL
IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
2015-04-16 16:20:57 -04:00
HOST_REGEXP = /(^[^:]+:\/\/)?(\[[^\]]+\]|[^:]+)(?::(\d+$))?/
PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/
2012-01-12 11:35:43 -05:00
mattr_accessor :tld_length
self.tld_length = 1
2010-12-03 07:27:43 -05:00
class << self
# Returns the domain part of a host given the domain level.
#
# # Top-level domain example
# extract_domain('www.example.com', 1) # => "example.com"
# # Second-level domain example
# extract_domain('dev.www.example.co.uk', 2) # => "example.co.uk"
def extract_domain(host, tld_length)
extract_domain_from(host, tld_length) if named_host?(host)
2010-12-03 07:27:43 -05:00
end
# Returns the subdomains of a host as an Array given the domain level.
#
# # Top-level domain example
# extract_subdomains('www.example.com', 1) # => ["www"]
# # Second-level domain example
# extract_subdomains('dev.www.example.co.uk', 2) # => ["dev", "www"]
def extract_subdomains(host, tld_length)
if named_host?(host)
extract_subdomains_from(host, tld_length)
else
[]
end
2010-12-03 07:27:43 -05:00
end
# Returns the subdomains of a host as a String given the domain level.
#
# # Top-level domain example
# extract_subdomain('www.example.com', 1) # => "www"
# # Second-level domain example
# extract_subdomain('dev.www.example.co.uk', 2) # => "dev.www"
def extract_subdomain(host, tld_length)
2010-12-03 07:27:43 -05:00
extract_subdomains(host, tld_length).join('.')
end
def url_for(options)
2014-07-16 21:15:15 -04:00
if options[:only_path]
path_for options
else
full_url_for options
2014-07-16 21:15:15 -04:00
end
end
def full_url_for(options)
host = options[:host]
protocol = options[:protocol]
port = options[:port]
unless host
raise ArgumentError, 'Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true'
end
build_host_url(host, port, protocol, options, path_for(options))
end
2014-07-16 21:15:15 -04:00
def path_for(options)
path = options[:script_name].to_s.chomp("/".freeze)
path << options[:path] if options.key?(:path)
add_trailing_slash(path) if options[:trailing_slash]
add_params(path, options[:params]) if options.key?(:params)
add_anchor(path, options[:anchor]) if options.key?(:anchor)
path
end
private
def add_params(path, params)
2014-07-31 12:08:58 -04:00
params = { params: params } unless params.is_a?(Hash)
params.reject! { |_,v| v.to_param.nil? }
query = params.to_query
path << "?#{query}" unless query.empty?
end
def add_anchor(path, anchor)
if anchor
path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}"
end
2010-12-03 07:27:43 -05:00
end
def extract_domain_from(host, tld_length)
host.split('.').last(1 + tld_length).join('.')
end
def extract_subdomains_from(host, tld_length)
parts = host.split('.')
parts[0..-(tld_length + 2)]
end
def add_trailing_slash(path)
# includes querysting
if path.include?('?')
path.sub!(/\?/, '/\&')
# does not have a .format
elsif !path.include?(".")
path.sub!(/[^\/]\z|\A\z/, '\&/')
end
end
def build_host_url(host, port, protocol, options, path)
if match = host.match(HOST_REGEXP)
2014-07-31 12:18:51 -04:00
protocol ||= match[1] unless protocol == false
host = match[2]
port = match[3] unless options.key? :port
2014-05-20 18:29:40 -04:00
end
2014-07-31 12:18:51 -04:00
protocol = normalize_protocol protocol
host = normalize_host(host, options)
result = protocol.dup
2014-05-20 18:29:40 -04:00
if options[:user] && options[:password]
result << "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@"
end
result << host
normalize_port(port, protocol) { |normalized_port|
result << ":#{normalized_port}"
2014-06-11 14:33:22 -04:00
}
result.concat path
end
2010-12-03 07:27:43 -05:00
def named_host?(host)
IP_HOST_REGEXP !~ host
2010-12-03 07:27:43 -05:00
end
def normalize_protocol(protocol)
case protocol
when nil
"http://"
when false, "//"
"//"
when PROTOCOL_REGEXP
"#{$1}://"
else
raise ArgumentError, "Invalid :protocol option: #{protocol.inspect}"
end
end
def normalize_host(_host, options)
return _host unless named_host?(_host)
tld_length = options[:tld_length] || @@tld_length
subdomain = options.fetch :subdomain, true
domain = options[:domain]
host = ""
if subdomain == true
return _host if domain.nil?
host << extract_subdomains_from(_host, tld_length).join('.')
2014-06-11 18:30:12 -04:00
elsif subdomain
host << subdomain.to_param
end
host << "." unless host.empty?
host << (domain || extract_domain_from(_host, tld_length))
host
end
def normalize_port(port, protocol)
2014-06-11 14:33:22 -04:00
return unless port
case protocol
2014-06-11 14:33:22 -04:00
when "//" then yield port
when "https://"
2014-06-11 14:33:22 -04:00
yield port unless port.to_i == 443
else
2014-06-11 14:33:22 -04:00
yield port unless port.to_i == 80
end
end
end
def initialize
2012-08-09 14:21:58 -04:00
super
@protocol = nil
@port = nil
end
# Returns the complete URL used for this request.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com'
# req.url # => "http://example.com"
def url
protocol + host_with_port + fullpath
end
# Returns 'https://' if this is an SSL request and 'http://' otherwise.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com'
# req.protocol # => "http://"
#
# req = Request.new 'HTTP_HOST' => 'example.com', 'HTTPS' => 'on'
# req.protocol # => "https://"
def protocol
@protocol ||= ssl? ? 'https://' : 'http://'
end
# Returns the \host for this request, such as "example.com".
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com'
# req.raw_host_with_port # => "example.com"
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.raw_host_with_port # => "example.com:8080"
def raw_host_with_port
2015-08-24 19:14:42 -04:00
if forwarded = x_forwarded_host.presence
forwarded.split(/,\s?/).last
else
2015-08-24 19:14:42 -04:00
get_header('HTTP_HOST') || "#{server_name || server_addr}:#{get_header('SERVER_PORT')}"
end
end
# Returns the host for this request, such as example.com.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.host # => "example.com"
def host
Freeze string literals when not mutated. I wrote a utility that helps find areas where you could optimize your program using a frozen string instead of a string literal, it's called [let_it_go](https://github.com/schneems/let_it_go). After going through the output and adding `.freeze` I was able to eliminate the creation of 1,114 string objects on EVERY request to [codetriage](codetriage.com). How does this impact execution? To look at memory: ```ruby require 'get_process_mem' mem = GetProcessMem.new GC.start GC.disable 1_114.times { " " } before = mem.mb after = mem.mb GC.enable puts "Diff: #{after - before} mb" ``` Creating 1,114 string objects results in `Diff: 0.03125 mb` of RAM allocated on every request. Or 1mb every 32 requests. To look at raw speed: ```ruby require 'benchmark/ips' number_of_objects_reduced = 1_114 Benchmark.ips do |x| x.report("freeze") { number_of_objects_reduced.times { " ".freeze } } x.report("no-freeze") { number_of_objects_reduced.times { " " } } end ``` We get the results ``` Calculating ------------------------------------- freeze 1.428k i/100ms no-freeze 609.000 i/100ms ------------------------------------------------- freeze 14.363k (± 8.5%) i/s - 71.400k no-freeze 6.084k (± 8.1%) i/s - 30.450k ``` Now we can do some maths: ```ruby ips = 6_226k # iterations / 1 second call_time_before = 1.0 / ips # seconds per iteration ips = 15_254 # iterations / 1 second call_time_after = 1.0 / ips # seconds per iteration diff = call_time_before - call_time_after number_of_objects_reduced * diff * 100 # => 0.4530373333993266 miliseconds saved per request ``` So we're shaving off 1 second of execution time for every 220 requests. Is this going to be an insane speed boost to any Rails app: nope. Should we merge it: yep. p.s. If you know of a method call that doesn't modify a string input such as [String#gsub](https://github.com/schneems/let_it_go/blob/b0e2da69f0cca87ab581022baa43291cdf48638c/lib/let_it_go/core_ext/string.rb#L37) please [give me a pull request to the appropriate file](https://github.com/schneems/let_it_go/blob/b0e2da69f0cca87ab581022baa43291cdf48638c/lib/let_it_go/core_ext/string.rb#L37), or open an issue in LetItGo so we can track and freeze more strings. Keep those strings Frozen ![](https://www.dropbox.com/s/z4dj9fdsv213r4v/let-it-go.gif?dl=1)
2015-07-19 17:19:15 -04:00
raw_host_with_port.sub(/:\d+$/, ''.freeze)
end
# Returns a \host:\port string for this request, such as "example.com" or
# "example.com:8080".
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:80'
# req.host_with_port # => "example.com"
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.host_with_port # => "example.com:8080"
def host_with_port
"#{host}#{port_string}"
end
# Returns the port number of this request as an integer.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com'
# req.port # => 80
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.port # => 8080
def port
@port ||= begin
if raw_host_with_port =~ /:(\d+)$/
$1.to_i
else
standard_port
end
end
end
# Returns the standard \port number for this request's protocol.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.standard_port # => 80
def standard_port
case protocol
when 'https://' then 443
else 80
end
end
# Returns whether this request is using the standard port
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:80'
# req.standard_port? # => true
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.standard_port? # => false
def standard_port?
port == standard_port
end
# Returns a number \port suffix like 8080 if the \port number of this request
# is not the default HTTP \port 80 or HTTPS \port 443.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:80'
# req.optional_port # => nil
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.optional_port # => 8080
def optional_port
standard_port? ? nil : port
end
# Returns a string \port suffix, including colon, like ":8080" if the \port
# number of this request is not the default HTTP \port 80 or HTTPS \port 443.
#
# class Request < Rack::Request
# include ActionDispatch::Http::URL
# end
#
# req = Request.new 'HTTP_HOST' => 'example.com:80'
# req.port_string # => ""
#
# req = Request.new 'HTTP_HOST' => 'example.com:8080'
# req.port_string # => ":8080"
def port_string
standard_port? ? '' : ":#{port}"
end
def server_port
2015-08-24 19:39:47 -04:00
get_header('SERVER_PORT').to_i
end
# Returns the \domain part of a \host, such as "rubyonrails.org" in "www.rubyonrails.org". You can specify
# a different <tt>tld_length</tt>, such as 2 to catch rubyonrails.co.uk in "www.rubyonrails.co.uk".
def domain(tld_length = @@tld_length)
ActionDispatch::Http::URL.extract_domain(host, tld_length)
end
# Returns all the \subdomains as an array, so <tt>["dev", "www"]</tt> would be
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
# such as 2 to catch <tt>["www"]</tt> instead of <tt>["www", "rubyonrails"]</tt>
# in "www.rubyonrails.co.uk".
def subdomains(tld_length = @@tld_length)
ActionDispatch::Http::URL.extract_subdomains(host, tld_length)
end
# Returns all the \subdomains as a string, so <tt>"dev.www"</tt> would be
# returned for "dev.www.rubyonrails.org". You can specify a different <tt>tld_length</tt>,
# such as 2 to catch <tt>"www"</tt> instead of <tt>"www.rubyonrails"</tt>
# in "www.rubyonrails.co.uk".
def subdomain(tld_length = @@tld_length)
ActionDispatch::Http::URL.extract_subdomain(host, tld_length)
end
end
end
2010-10-26 14:31:05 -04:00
end