Skip to content

Instantly share code, notes, and snippets.

@SebDeclercq
Created April 17, 2016 20:31
Show Gist options
  • Select an option

  • Save SebDeclercq/06b1e54ced744c8c97b3eb2b8d30e658 to your computer and use it in GitHub Desktop.

Select an option

Save SebDeclercq/06b1e54ced744c8c97b3eb2b8d30e658 to your computer and use it in GitHub Desktop.
Gère la bdd hiragana
require "sinatra"
require "sqlite3"
require "json"
db = SQLite3::Database.new "hiragana.db"
set :public_folder, "."
######################################################################################
### UI web
get "/" do
erb :index
end
post "/" do
if params["action"] == "insertion" # S'il s'agit d'une insertion
@insert, @hiragana, @rômaji, @français, @erreur = *insereBdd(params, db)
elsif params["action"] == "recherche" # S'il s'agit d'une recherche
@liste = chercheBdd(params, db)
end
erb :index
end
######################################################################################
### RESTful
['/resources', '/resources/:romaji'].each do |route|
get route do
params["romaji"] ||= params[:romaji] if defined? params[:romaji] # Si l'URL est /resources/:romaji
params["romaji"] ||= '' # la clef si elle n'existe pas
params["francais"] ||= '' # la clef si elle n'existe pas
@liste = chercheBdd(params, db)
@liste.to_json + "\n"
end
end
post '/resources' do
halt 400, "Données POST absentes\n" if params["romaji"].nil? # S'il n'y a pas de rômaji à insérer, erreur
@insert, @hiragana, @rômaji, @français, @erreur = *insereBdd(params, db) # Gère l'insertion
if @insert == true
@resultat = {hiragana: @hiragana, rômaji: @rômaji, français: @français}
@resultat.to_json + "\n"
elsif @insert == false
halt 400, "Une erreur est survenue : #@erreur\n"
else
"#{params['romaji']} existe déjà\n"
end
end
delete '/resources' do
halt 400, "Données DELETE absentes\n" if params["romaji"].nil?
@insert, @erreur = *supprimeBdd(params["romaji"], db) # Gère la suppression
if @insert == true
"#{params['romaji']} a été supprimé\n"
else
halt 400, "Une erreur est survenue : #@erreur\n"
end
end
patch '/resources' do
halt 400, "Données PATCH absentes\n" if params["romaji"].nil? || params["francais"].nil?
@update, @hiragana, @rômaji, @français, @erreur = *modifieBdd(params, db) # Gère la modification
if @update == true
@resultat = {hiragana: @hiragana, rômaji: @rômaji, français: @français}
@resultat.to_json + "\n"
else
halt 400, "Une erreur est survenue : #@erreur\n"
end
end
def chercheBdd(params, db)
sql = "SELECT hiragana, rômaji, français FROM mots where " # Initie le SQL
if params['romaji'].size > 0 && params['francais'].size > 0 # Si la rechercher porte sur le rômaji et le français
sql << "rômaji = ? or français = ?" # Complète le SQL
resultat = db.execute sql, [params['romaji'], params['francais']]
elsif params['romaji'].size > 0 # Si elle ne porte que sur le rômaji
sql << "rômaji = ?" # Complète le SQL
resultat = db.execute sql, params['romaji']
elsif params['francais'].size > 0 # Si elle ne porte que sur le français
sql << "français = ?" # Complète le SQL
resultat = db.execute sql, params['francais']
end
liste = [] # Crée la liste pour générer la sortie
if defined? resultat && resultat.size > 0 # S'il y a un résultat
resultat.each do |rs| # Pour chaque résultat
hiragana, rômaji, français = *rs # Splatte les éléments
mot = {hiragana: hiragana, rômaji: rômaji, français: français} # Crée un hash pour le résultat
liste.push mot # Ajoute le hash à la liste
end
end
liste
end
def insereBdd(params, db)
insert = nil
if params["romaji"].size > 0 # S'il y a bien du rômaji
mots = params["romaji"].split(" ") # Récupère le rômaji mot par mot
phrase = [] # Initie la phrase en hiragana
mots.each do |mot| # Pour chaque mot
hiraganas = [] # Initie le mot en hiragana
syllabes = mot.downcase.split /(?<=[aiueo])|(?<=n)(?![aiueo])/ # Éclate par syllabe
syllabes.each do |syllabe| # Pour chaque syllabe
sql = "SELECT hiragana FROM hiraganas WHERE syllabe = '#{syllabe}' " # Crée le SQL
db.execute sql do |hiragana| # Exécute le SQL et récupère la réponse
hiraganas.push hiragana # Insère le caractère dans le mot en hiragana
end
end
phrase.push hiraganas.join "" # Insère le nouveau mot dans la phrase
end
hiragana = phrase.join " " # Génère la phrase en hiragana (mots séparés par des espaces)
rômaji = params["romaji"]
français = params["francais"]
sql = "SELECT count(*) as total FROM mots where hiragana = ?"
db.execute sql, hiragana do |total|
if total[0] == 0
begin
sql = "INSERT INTO mots (rômaji, français, hiragana) VALUES (?, ?, ?)"
db.execute sql, [rômaji, français, hiragana]
insert = true
erreur = nil
rescue SQLite3::Exception => erreur
insert = false
end
else
insert = 'existe'
end
end
else
insert = false
erreur = 'Veuillez insérer le rômaji'
end
[insert, hiragana, rômaji, français, erreur]
end
def supprimeBdd(rômaji, db)
insert = nil
sql = "DELETE FROM mots where rômaji = ?"
begin
db.execute sql, rômaji
insert = true
rescue SQLite3::Exception => erreur
insert = false
end
[insert, erreur]
end
def modifieBdd(params, db)
français = params["francais"]
rômaji = params["romaji"]
update = nil
sql = "UPDATE mots SET français = ? where rômaji = ?"
begin
db.execute sql, [français, rômaji]
update = true
rescue SQLite3::Exception => erreur
update = false
end
sql = "SELECT hiragana FROM mots where rômaji = ?"
rs = db.execute sql, rômaji
hiragana = rs[0]
[update, hiragana, rômaji, français, erreur]
end
__END__
@@index
<html>
<head>
<meta charset="utf-8">
<title>Ma BDD franco-japonaise</title>
<style type="text/css">
dl {
width: 40pc;
border: solid 0.5px;
display: table;
padding: 0.5pc;
padding-right: 2pc;
}
dt {
font-style: italic;
}
dd {
margin-left: 5pc;
}
dd.ddhiragana {
font-weight: bold;
font-size: 15pt;
}
button.modif, button.suppr {
margin-top: 1pc;
float: right;
}
.hidden {
display: none;
}
</style>
<noscript><style>#hideIfNoScript { display: none; }</style></noscript>
<% if File.exists? "jquery.js" %>
<script type="text/javascript" src="jquery.js"></script>
<% else %>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
<% end %>
<script type="text/javascript">
$(document).ready(function() {
$("input[name='action'][value='insertion']").prop("checked", true) // Force la valeur a "insertion"
$("#submit").attr("value", "Ajouter") // Définit le bouton
$("input[name='action']").change(function() { // Change le texte du bouton en fonction de l'option
$(this).val() == "recherche" ? $("#submit").val("Rechercher") : $("#submit").val("Ajouter")
})
$("button.modif").click(function() { // En cliquant sur modif
romaji = $(this).closest("dl").attr("id")
ddfrancais = $(this).parent("div").siblings("dd.ddfrancais")
francais = ddfrancais.text()
if ($(this).text() == "Modifier") { // Si le texte du bouton est "Modifier", il s'agit d'un premier clic
ddfrancais.html("<div class='hidden'>"+francais+"</div><input class='fauxFormulaire' type='text' value='"+francais+"'/>") // Remplace le <dd> par un input
$(this).text("Sauvegarder")
$("input.fauxFormulaire").keyup(function(e) {
btnModif = $(this).closest("dl").children("div").children("button.modif")
if (e.keyCode === 13) { // Si <enter> dans l'input
btnModif.trigger("click") // Trigger un clic sur button.modif
}
else if (e.keyCode === 27) { // Si <escape>, rétablit comme avant
btnModif.text("Modifier")
ancien = $(this).prev("div.hidden").text()
$(this).parent("dd").html(ancien)
}
})
}
else { // Si le texte du bouton est "Sauvegarder", il s'agit d'un deuxième clic
$.ajax({ // Appelle à PATCH /resources pour modification
url: '/resources',
type: 'PATCH',
data: "romaji="+romaji+"&francais="+ddfrancais.children("input").val(),
success: function(resultat) {
ddfrancais.html(ddfrancais.children("input").val())
ddfrancais.parent("dl").children("div").children("button.modif").text("Modifier")
},
fail: function(resultat) {
alert("Une erreur est survenue lors de la modification !")
}
})
}
})
$("button.suppr").click(function() { // En cliquant sur suppr
dl = $(this).parent("div").parent("dl")
romaji = $(this).parent("div").parent("dl").attr("id")
var confirmation = confirm("Confirmer la suppression de \""+romaji+"\"")
if (!confirmation) {
return false;
}
$.ajax({ // Appelle à DELETE /resources pour suppression
url: '/resources',
type: 'DELETE',
data: "romaji="+romaji,
success: function (resultat) {
dl.fadeOut()
},
fail: function (resultat) {
alert("Une erreur est survenue lors de la suppression !")
}
})
})
})
</script>
</head>
<body>
<% if @insert == true %>
<form>
<fieldset>
<legend>Succès de l'insertion</legend>
<dl>
<dt>Hiragana</dt><dd class="ddhiragana"><%= @hiragana %></dd>
<dt>Rômaji</dt><dd class="ddromaji"><%= @rômaji %></dd>
<dt>Français</dt><dd class="ddfrancais"><%= @français %></dd>
</dl>
</fieldset>
</form>
<% elsif @insert == false %>
<p>Erreur à l'insertion</p>
<p><strong>Erreur:&nbsp;&nbsp;</strong><%= @e %></p>
<% elsif @insert == 'existe' %>
<p>Le mot existe déjà !</p>
<% elsif defined? @liste %>
<h3>Résultats de la recherche</h3>
<% @liste.each do |mot| %>
<dl id="<%= mot[:rômaji] %>">
<dt>Hiragana</dt><dd class="ddhiragana"><%= mot[:hiragana] %></dd>
<dt>Rômaji</dt><dd class="ddromaji"><%= mot[:rômaji] %></dd>
<dt>Français</dt><dd class="ddfrancais"><%= mot[:français] %></dd>
<div id="hideIfNoScript">
<button class="suppr">Supprimer</button>
<button class="modif">Modifier</button>
</div>
</dl>
<% end %>
<% else %>
<form action="/" method="POST">
<fieldset class="container">
<legend>Saisir le(s) mot(s)</legend>
<label for="romaji">Rômaji&nbsp;:&nbsp;</label>
<input type="text" name="romaji"/>
<label for="francais">Français&nbsp;:&nbsp;</label>
<input type="text" name="francais"/>
<br/><br/>
<input type="radio" name="action" value="insertion" checked="checked">Insertion</input>
<input type="radio" name="action" value="recherche">Recherche</input>
<br/><br/>
<input id="submit" type="submit" value="Ajouter"/>
</fieldset>
</form>
<% end %>
<br/><br/>
<a href="/">Retour</a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment