mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-21 01:53:26 +00:00
Add context code support to exercises (optional)
Partial #52, fixes #49, fixes #46
This commit is contained in:
@@ -8,6 +8,7 @@ define([
|
||||
var prepareExercise = function($exercise) {
|
||||
var codeSolution = $exercise.find(".code-solution").text();
|
||||
var codeValidation = $exercise.find(".code-validation").text();
|
||||
var codeContext = $exercise.find(".code-context").text();
|
||||
|
||||
var editor = ace.edit($exercise.find(".editor").get(0));
|
||||
editor.setTheme("ace/theme/tomorrow");
|
||||
@@ -20,7 +21,7 @@ define([
|
||||
|
||||
analytic.track("exercise.submit");
|
||||
|
||||
execute("javascript", editor.getValue(), codeValidation, function(err, result) {
|
||||
execute("javascript", editor.getValue(), codeValidation, codeContext, function(err, result) {
|
||||
$exercise.toggleClass("return-error", err != null);
|
||||
$exercise.toggleClass("return-success", err == null);
|
||||
if (err) $exercise.find(".alert-danger").text(err.message || err);
|
||||
|
||||
@@ -2,6 +2,7 @@ define(function() {
|
||||
return {
|
||||
id: "javascript",
|
||||
assertCode: "function assert(condition, message) { \nif (!condition) { \n throw message || \"Assertion failed\"; \n } \n }\n",
|
||||
REPL: JSREPL
|
||||
REPL: JSREPL,
|
||||
sep: ";\n",
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
@@ -71,13 +71,21 @@ define([
|
||||
repl.loadLanguage(lang.id, eventHandler);
|
||||
};
|
||||
|
||||
var execute = function(lang, solution, validation, callback) {
|
||||
var execute = function(lang, solution, validation, context, callback) {
|
||||
// Language data
|
||||
var langd = LANGUAGES[lang];
|
||||
|
||||
// Check language is supported
|
||||
if (!LANGUAGES[lang]) return callback(new Error("Language '"+lang+"' not available for execution"));
|
||||
if (!langd) return callback(new Error("Language '"+lang+"' not available for execution"));
|
||||
|
||||
// Validate with validation code
|
||||
var code = [solution, LANGUAGES[lang].assertCode, validation].join(";\n");
|
||||
evalJS(LANGUAGES[lang], code, function(err, res) {
|
||||
var code = [
|
||||
context,
|
||||
solution,
|
||||
langd.assertCode,
|
||||
validation,
|
||||
].join(langd.sep);
|
||||
evalJS(langd, code, function(err, res) {
|
||||
if(err) return callback(err);
|
||||
|
||||
if (res.type == "error") callback(new Error(res.value));
|
||||
@@ -86,4 +94,4 @@ define([
|
||||
};
|
||||
|
||||
return execute;
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user