Class: Luna::Middleware::Markdown

Inherits:
Protocol::HTTP::Middleware
  • Object
show all
Defined in:
lib/luna/middleware/markdown.rb

Overview

Render Markdown files to HTML on-the-fly. Intercepts requests that target .md/.markdown files.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, root: Dir.pwd, index_candidates: ["index.md", "README.md"]) ⇒ Markdown

Returns a new instance of Markdown.



19
20
21
22
23
# File 'lib/luna/middleware/markdown.rb', line 19

def initialize(app, root: Dir.pwd, index_candidates: ["index.md", "README.md"]) 
	super(app)
	@root = File.expand_path(root)
	@index_candidates = index_candidates
end

Instance Attribute Details

#index_candidatesObject (readonly)

Returns the value of attribute index_candidates.



26
27
28
# File 'lib/luna/middleware/markdown.rb', line 26

def index_candidates
  @index_candidates
end

#rootObject (readonly)

Returns the value of attribute root.



25
26
27
# File 'lib/luna/middleware/markdown.rb', line 25

def root
  @root
end

Instance Method Details

#call(request) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/luna/middleware/markdown.rb', line 34

def call(request)
	return super unless request.method == "GET" || request.method == "HEAD"
	path = request.path.split("?", 2).first
	
	fs_path = safe_join(path)
	return super unless fs_path
	
	if File.directory?(fs_path)
		candidate = @index_candidates.map {|n| File.join(fs_path, n)}.find {|p| File.file?(p)}
		return render_file(candidate, head: request.method == "HEAD") if candidate
	elsif File.file?(fs_path) && markdown_file?(fs_path)
		return render_file(fs_path, head: request.method == "HEAD")
	end
	
	super
end

#safe_join(path) ⇒ Object



28
29
30
31
32
# File 'lib/luna/middleware/markdown.rb', line 28

def safe_join(path)
	full = File.expand_path(File.join(@root, path))
	return nil unless full.start_with?(@root)
	full
end