Created
March 1, 2017 14:55
-
-
Save yannski/6495634a6cef6f00d57f0f986ff979ae to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "sinatra" | |
get '/' do | |
html = "" | |
filenames = Dir.glob("articles/*.txt").sort.reverse | |
filenames.each{|filename| | |
html += article_as_html(filename, 100) | |
} | |
return layout(html) | |
end | |
get '/articles/:id' do | |
filename = "articles/" + params[:id] + ".txt" | |
return layout(article_as_html(filename)) | |
end | |
# à partir d'un nom de fichier, retourne un fragment HTML | |
def article_as_html filename, length = nil | |
content = File.read filename | |
lines = content.lines | |
first_line = lines.shift | |
other_lines = lines | |
res = "<h1>"+first_line+"</h1>" | |
body = other_lines.join(" ") | |
# si le paramètre length n'est pas null | |
if length != nil | |
# on tronque le corps de texte | |
res += "<p>"+body[0, length]+"</p>" | |
# on ajoute un lien vers la page de l'article | |
res += "<a href='/"+filename.split(".").first+"'>lire la suite</a>" | |
else | |
res += "<p>"+body+"</p>" | |
res += "<a href='/'>Revenir à la liste</a>" | |
end | |
end | |
# englobe un contenu dans un layout HTML | |
def layout content | |
html = '<html><head><title>Mon blog</title><link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous"></head><body>' | |
html += '<div class="container"><div class="row"><div class="col-12">' | |
html += content | |
html += "</div></div></div></body></html>" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment