Class: Server::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/server/dispatcher.rb

Constant Summary collapse

WEB_ROOT =
'web_root'
DEV_ROOT =
'dev_root'

Instance Method Summary collapse

Instance Method Details

#dispatch(request, response, server) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/server/dispatcher.rb', line 8

def dispatch(request, response, server)
  path = request.path

  regenerate_files_if(path, server)

  return response.send_404 unless File.exist?(path)

  if !File.directory?(path)
    if path.include? '.php'
      response.send(200, execute_php(path, request.params))
    else
      response.send_file path
    end
  else
    if File.exist?("#{path}/index.html")
      response.send_301 "#{path}/index.html"
    else
      response.send(200, list_dir(path, server))
    end
  end
end

#execute_php(path, params) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/server/dispatcher.rb', line 57

def execute_php(path, params)
  params_s = ''
  params.each do |key, value|
    params_s += "#{key}=#{value[0]} "
  end
  executors = ['php', 'php-cgi', 'php-fpm']
  cmd = "#{executors[0]} #{path} #{params_s}"
  STDERR.puts(cmd)
  %x[ #{cmd} ]
end

#list_dir(path, server) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/server/dispatcher.rb', line 30

def list_dir(path, server)
  content = ''
  Dir.glob("#{path.gsub(WEB_ROOT, DEV_ROOT)}/*/").each do |f|
    f = f.gsub(DEV_ROOT, WEB_ROOT)

    regenerate_files_if("#{f}index.html", server)

    f_name = File.basename(f)
    f_path = "#{path}/#{f_name}".sub("#{WEB_ROOT}/", '')
    content += "<li><a href='#{f_path}'>#{f_name}</a></li>" if File.directory?(path)
  end

  "<!DOCTYPE html><html><head><body><h1>#{path}</h1><ul>#{content}</ul><a target='_blank' href='https://github.com/dennisvandehoef/easy-html-creator'>ehc on Github</a></body></html>"
end

#regenerate_files_if(path, server) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/server/dispatcher.rb', line 45

def regenerate_files_if(path, server)
  return unless path.include? '.html'

  #no html? no reload -> no regenarate
  server.log "#######################"
  server.log "#                     #"
  server.log "#   Renew all files   #"
  server.log "#                     #"
  server.log "#######################"
  Generator::Generator.new.generate
end