class Rack::Capture

Constants

VERSION

Public Class Methods

call(**args) click to toggle source
# File lib/rack/capture.rb, line 10
def call(**args)
  new(**args).call
end
new( app:, url:, output_directory_path: 'output', script_name: '' ) click to toggle source

@param [#call] app Rack application. @param [String] output_directory_path @param [String] script_name @param [String] url

# File lib/rack/capture.rb, line 19
def initialize(
  app:,
  url:,
  output_directory_path: 'output',
  script_name: ''
)
  @app = app
  @output_directory_path = output_directory_path
  @script_name = script_name
  @url = url
end

Public Instance Methods

call() click to toggle source
# File lib/rack/capture.rb, line 31
def call
  response = get_response
  destination = calculate_destination(response: response)
  destination.parent.mkpath
  content = ''
  response.body.each do |element|
    content += element
  end
  destination.write(content)
end

Private Instance Methods

calculate_destination(response:) click to toggle source

@param [Rack::Response] response

# File lib/rack/capture.rb, line 45
def calculate_destination(response:)
  destination = ::Pathname.new("#{@output_directory_path}#{path_info}")
  if response.content_type&.include?('text/html')
    destination += 'index' if path_info == '/'
    destination = destination.sub_ext('.html')
  end
  destination
end
get_response() click to toggle source

@return [Rack::Response]

# File lib/rack/capture.rb, line 55
def get_response
  status, headers, body = @app.call(rack_env)
  ::Rack::Response.new(body, status, headers)
end
path_info() click to toggle source

@return [String]

# File lib/rack/capture.rb, line 61
def path_info
  uri.path.delete_prefix(@script_name)
end
rack_env() click to toggle source

@return [Hash]

# File lib/rack/capture.rb, line 66
def rack_env
  {
    'HTTP_HOST' => @host,
    'PATH_INFO' => path_info,
    'QUERY_STRING' => uri.query || '',
    'rack.url_scheme' => rack_url_scheme,
    'REQUEST_METHOD' => 'GET',
    'SCRIPT_NAME' => @script_name,
    'SERVER_NAME' => uri.host
  }
end
rack_url_scheme() click to toggle source

@return [String]

# File lib/rack/capture.rb, line 79
def rack_url_scheme
  if uri.scheme == 'https'
    'https'
  else
    'http'
  end
end
uri() click to toggle source

@return [URI]

# File lib/rack/capture.rb, line 88
def uri
  @uri ||= ::URI.parse(@url)
end