Skip to content

Commit

Permalink
Cache jade data
Browse files Browse the repository at this point in the history
  • Loading branch information
rstacruz committed Oct 19, 2015
1 parent ba4cf19 commit 56bcfd7
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
19 changes: 14 additions & 5 deletions index.js
Expand Up @@ -11,6 +11,7 @@ const buildCss = require('./lib/build_css')
const hash = require('./lib/hash')
const eachCons = require('./lib/helpers/each_cons')
const toArray = require('./lib/helpers/to_array')
const memoize = require('./lib/memoize')

/**
* Metalsmith middleware
Expand Down Expand Up @@ -129,24 +130,32 @@ function addJs (files, ms, done) {
function relayout (files, ms, done) {
const toc = files['_docpress.json'].toc
const index = files['_docpress.json'].index

const path = fs.readFileSync(join(__dirname, 'data/layout.jade'), 'utf-8')
const layout = jade.compile(path, { pretty: true })
const meta = ms.metadata()

const jadeData = fs.readFileSync(join(__dirname, 'data/layout.jade'), 'utf-8')
const layout = memoize(['jade', jadeData], () => {
return jade.compile(jadeData, { pretty: true })
})

eachCons(index, (_, fname, __, prevName, ___, nextName) => {
if (!fname.match(/\.html$/)) return
const file = files[fname]
const base = Array(fname.split('/').length).join('../')
const styles = this.styles.map(relativize(base))
const scripts = this.scripts.map(relativize(base))

file.contents = layout(assign({}, file, {
const locals = {
base, toc, index, meta, styles, scripts,
prev: prevName && assign({}, index[prevName], { url: base + prevName }),
next: nextName && assign({}, index[nextName], { url: base + nextName }),
active: fname
}))
}

const key = [ jadeData, locals, file ]

file.contents = memoize(['jadedata', key], () => {
return layout(assign({}, file, locals))
})
})

done()
Expand Down
10 changes: 10 additions & 0 deletions lib/memoize.js
@@ -0,0 +1,10 @@
'use strict'

const cache = {}

module.exports = function memoize (keyObject, fn) {
const key = JSON.stringify(keyObject)
if (cache[key]) return cache[key]
cache[key] = fn()
return cache[key]
}

0 comments on commit 56bcfd7

Please sign in to comment.