Class: Fringe::Server

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

Constant Summary collapse

@@app_dir =
nil
@@routes =
{
  get: {},
  post: {},
  put: {},
  delete: {}
}

Class Method Summary collapse

Class Method Details

.add_route(verb, path, klass, action) ⇒ Object



66
67
68
# File 'lib/fringe/server.rb', line 66

def self.add_route(verb, path, klass, action)
  @@routes[verb][path] = [klass, action]
end

.call(env) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/fringe/server.rb', line 84

def self.call(env)
  begin
    path = env["REQUEST_PATH"] || env['PATH_INFO']
    verb = env['REQUEST_METHOD']
    req = Rack::Request.new(env)
    STDOUT.puts %{[#{Time.now.to_s}] Started \e[1;34m#{verb}\e[0m \e[1;32m"#{path}"\e[0m for \e[1;31m#{env['REMOTE_ADDR']}\e[0m}
    return route_request(verb.downcase.to_sym, path, req)
  rescue => e
    puts e
    puts e.backtrace
    [500, {"Content-Type" => "text/html"}, [e.message]]
  end
end

.initialize(app_dir) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/fringe/server.rb', line 38

def self.initialize(app_dir)
  @@app_dir = app_dir
  FileUtils.mkdir_p(@@app_dir + "/tmp/logs")
  Dir["#{@@app_dir}/config/initializers/*.rb"].each do |file|
    match = file.match(/\/([^\/.]+)\.rb$/)
    if match
      file_name = match[1]
      require("#{@@app_dir}/config/initializers/#{file_name}")
    end
  end
  Dir["#{@@app_dir}/app/models/*.rb"].each do |file|
    match = file.match(/\/([^\/.]+)\.rb$/)
    if match
      file_name = match[1]
      autoload(file_name.camelize.to_sym, file)
    end
  end
  Dir["#{@@app_dir}/app/controllers/*.rb"].each do |file|
    match = file.match(/\/([^\/.]+)\.rb$/)
    if match
      file_name = match[1]
      require("#{@@app_dir}/app/controllers/#{file_name}")
    end
  end

  require("#{@@app_dir}/app/routes")
end

.route_request(verb, path, req) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/fringe/server.rb', line 70

def self.route_request(verb, path, req)
  response = [404, {"Content-Type" => "text/html"}, ['404']]
  if @@routes[verb]
    @@routes[verb].keys.each do |pattern|
      if path.match(pattern)
        controller = @@routes[verb][pattern]
        STDOUT.puts "[#{Time.now.to_s}]    Processing by \e[1;34m#{controller[0].to_s}\e[0m#\e[1;32m#{controller[1]}\e[0m"
        response = controller[0].new(req).send(controller[1])
      end
    end
  end
  response
end