class Neruda::PreviewServlet

A tiny preview server, which main goal is to replace references to the target domain by localhost.

Public Instance Methods

do_GET(request, response) click to toggle source
# File lib/neruda/preview.rb, line 12
def do_GET(request, response) # rubocop:disable Naming/MethodName
  file = local_path(request.path)
  response.body = parse_body(file, "http://#{request.host}:#{request.port}")
  response.status = 200
  response.content_type = mime_type(file, DefaultMimeTypes)
end

Private Instance Methods

local_path(requested_path) click to toggle source
# File lib/neruda/preview.rb, line 21
def local_path(requested_path)
  routes = Neruda::Config.settings.dig('preview', 'routes') || {}
  return routes[requested_path] if routes.has_key? requested_path
  local_path = Neruda::Config.settings['public_folder'] + requested_path
  if File.directory? local_path
    local_path = format(
      '%<path>s/index.html', path: local_path.delete_suffix('/')
    )
  end
  return local_path if File.exist? local_path
  raise WEBrick::HTTPStatus::NotFound, 'Not found.'
end
parse_body(local_path, local_host) click to toggle source
# File lib/neruda/preview.rb, line 34
def parse_body(local_path, local_host)
  body = IO.read local_path
  return body unless local_path.match?(/\.(?:ht|x)ml\z/)
  domain = Neruda::Config.settings['domain']
  return body if domain == ''
  body.gsub(/"file:\/\//, format('"%<host>s', host: local_host))
      .gsub(/"#{domain}/, format('"%<host>s', host: local_host))
end