Class: QuestionCompiler::Server::QuestionHandler

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

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ QuestionHandler

Returns a new instance of QuestionHandler.



31
32
33
34
# File 'lib/question_compiler/server.rb', line 31

def initialize(root)
  @root = root
  @context_reader = LocalContextReader.new File.join(@root, '../../../contexts')
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
# File 'lib/question_compiler/server.rb', line 14

def call(env)
  req = Rack::Request.new env
  
  if req.path == '/question.html'
    serve_question
  else
    maybe_serve_context_file env, req
  end
end

#cleanupObject



24
25
26
27
28
29
# File 'lib/question_compiler/server.rb', line 24

def cleanup
  path = File.join @root, '.context-path'
  if File.exists? path
    File.delete path
  end
end

#maybe_serve_context_file(env, req) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/question_compiler/server.rb', line 45

def maybe_serve_context_file(env, req)
  if context_path = read_context_path
    context_root = File.expand_path(
      File.join(@root, '../../../contexts', context_path)
    )
    file_path = File.join(context_root, req.path)
    if File.exists? file_path
      Rack::File.new(context_root).call env
    else
      Rack::File.new(@root).call env
    end
  else
    serve_generic env
  end
end

#read_context_pathObject



36
37
38
39
40
41
42
43
# File 'lib/question_compiler/server.rb', line 36

def read_context_path
  path = File.join @root, '.context-path'
  if File.exists? path
    File.read path
  else
    nil
  end
end

#serve_generic(env) ⇒ Object



61
62
63
# File 'lib/question_compiler/server.rb', line 61

def serve_generic(env)
  Rack::File.new(@root).call env
end

#serve_questionObject



65
66
67
68
69
70
71
72
# File 'lib/question_compiler/server.rb', line 65

def serve_question
  compiler = QuestionCompiler::Compiler.new(Logger.new(STDOUT))
  question_src = File.read 'question.html'
  question_doc = Nokogiri.HTML question_src
  question_doc = compiler.transform_question question_doc, @context_reader
  write_context_path compiler.context_path
  [200, {'Content-Type' => 'text/html'}, [question_doc.to_html]]
end

#write_context_path(context_path) ⇒ Object



74
75
76
77
78
# File 'lib/question_compiler/server.rb', line 74

def write_context_path(context_path)
  File.open('.context-path', 'w') do |f|
    f << context_path
  end
end