Last active
February 24, 2016 16:53
-
-
Save yannski/f7ed17106a1db86c9ce4 to your computer and use it in GitHub Desktop.
ENSIIE 2°16 TP1
This file contains hidden or 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
<html> | |
<head> | |
<title>Mon blog</title> | |
</head> | |
<body> | |
<% @articles.each{|article| %> | |
<h1><%= article[:title] %></h1> | |
<p><%= article[:body] %></p> | |
<a href='<%= article[:link] %>'> | |
Voir détails | |
</a> | |
<% } %> | |
</body> | |
</html> |
This file contains hidden or 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' | |
# extration des données depuis un nom de fichier | |
# filename est le nom du fichier | |
def extract_from_file filename | |
lines = IO.readlines(filename) | |
title = lines.shift | |
body = lines.join(" ") | |
number = filename.split("articles/").last.split(".txt").first | |
link = "/articles/" + number | |
# on renvoie un Hash avec les clés title, body, link | |
# sans return explicite, Ruby renvoie l'évaluation de la dernière ligne | |
# celle ci-dessous | |
{ | |
title: title, | |
body: body, | |
link: link | |
} | |
end | |
# racine du site | |
get '/' do | |
filenames = Dir.glob("articles/*").sort.reverse | |
# on initialise un tableau vide | |
@articles = [] | |
filenames.each{|filename| | |
# on rajoute chaque Hash au tableeau d'articles | |
@articles << extract_from_file(filename) | |
} | |
erb :index | |
end | |
# voir un article en particulier | |
get '/articles/:id' do | |
# on transforme le paramètre en Integer | |
position = params[:id].to_i | |
filename = "articles/#{position}.txt" | |
# on initialise un tableau vide | |
@articles = [] | |
# on extrait les informations et on range dans le tableau articles | |
@articles << extract_from_file(filename) | |
erb :index | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment