Skip to content

Commit

Permalink
Add utility for loading files that modify the Monarch module
Browse files Browse the repository at this point in the history
  • Loading branch information
maxbrunsfeld committed Dec 2, 2012
1 parent d8e46f1 commit 1faa86d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
11 changes: 11 additions & 0 deletions lib/server/index.coffee
Original file line number Diff line number Diff line change
@@ -1,3 +1,14 @@
_ = require 'underscore'
Monarch = require './load_core'

loader = require './util/global_loader'
loader.configure(
dir: __dirname,
globals: { Monarch, _ }
)

Monarch.Sql = {}

loader.requireTree('.')

module.exports = Monarch
38 changes: 38 additions & 0 deletions lib/server/util/global_loader.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Global Loader - a utility for loading multiple files that collectively define
# a common global module. Each file should export a function that receives a
# single object containing the global modules to be modified.

_ = require 'underscore'
fs = require 'fs'
glob = require 'glob'
path = require 'path'

loader =
dir: '.'
globals: {}

configure: (options) ->
for key in ['globals', 'dir']
loader[key] = options[key] if options[key]

require: (filePath) ->
fileExport = require(fullPath(filePath))
fileExport(loader.globals) if _.isFunction(fileExport)

requireTree: (dirPath) ->
filePaths = glob.sync("#{dirPath}/**/*", cwd: loader.dir)
filePaths.forEach (filePath) ->
if isFile(fullPath(filePath))
loader.require(stripExtension(filePath))

fullPath = (filePath) ->
path.resolve(loader.dir, filePath)

isFile = (filePath) ->
fs.statSync(filePath).isFile()

stripExtension = (filePath) ->
extension = path.extname(filePath)
filePath.replace("#{extension}$", '')

module.exports = loader
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
},
"dependencies": {
"underscore": "1.4.x",
"jasmine-node": "1.0.x"
"jasmine-node": "1.0.x",
"glob": "3.1.x"
},
"devDependencies": {
"coffee-script": "1.3.x",
Expand Down

0 comments on commit 1faa86d

Please sign in to comment.