From 5958af69141d4daa3a7438b906655898bdd0d657 Mon Sep 17 00:00:00 2001 From: Robert Krimen Date: Wed, 10 Oct 2012 15:46:10 -0700 Subject: [PATCH] Add registry package Automatic inclusion of source on import --- Makefile | 1 + otto.go | 6 ++++++ registry/registry.go | 42 ++++++++++++++++++++++++++++++++++++++++ underscore/underscore.go | 14 ++++++++++++++ underscore_test.go | 4 ++++ 5 files changed, 67 insertions(+) create mode 100644 registry/registry.go diff --git a/Makefile b/Makefile index 85028d1..f75e516 100644 --- a/Makefile +++ b/Makefile @@ -21,6 +21,7 @@ TEST := -v --run OttoError TEST := . test: + go test -i go test $(TEST) assets: diff --git a/otto.go b/otto.go index af1866a..f4ca166 100644 --- a/otto.go +++ b/otto.go @@ -74,6 +74,7 @@ package otto import ( "fmt" + "github.com/robertkrimen/otto/registry" ) // Otto is the representation of the JavaScript runtime. Each instance of Otto has a self-contained namespace. @@ -87,6 +88,11 @@ func New() *Otto { runtime: newContext(), } self.Set("console", self.runtime.newConsole()) + + registry.Apply(func(entry registry.Entry){ + self.Run(entry.Source()) + }) + return self } diff --git a/registry/registry.go b/registry/registry.go new file mode 100644 index 0000000..6dd1971 --- /dev/null +++ b/registry/registry.go @@ -0,0 +1,42 @@ +package registry + +var registry []*Entry = make([]*Entry, 0) + +type Entry struct { + active bool + source string +} + +func newEntry(source string) *Entry { + return &Entry{ + active: true, + source: source, + } +} + +func (self *Entry) Enable() { + self.active = true +} + +func (self *Entry) Disable() { + self.active = false +} + +func (self Entry) Source() string { + return self.source +} + +func Apply(callback func(Entry)) { + for _, entry := range registry { + if !entry.active { + continue + } + callback(*entry) + } +} + +func Register(source string) *Entry { + entry := newEntry(source) + registry = append(registry, entry) + return entry +} diff --git a/underscore/underscore.go b/underscore/underscore.go index ef1b9b7..4d020ce 100644 --- a/underscore/underscore.go +++ b/underscore/underscore.go @@ -7,6 +7,20 @@ https://github.com/documentcloud/underscore */ package underscore +import ( + "github.com/robertkrimen/otto/registry" +) + +var entry *registry.Entry = registry.Register(Source()) + +func Enable() { + entry.Enable() +} + +func Disable() { + entry.Disable() +} + // Source returns the underscore source. func Source() string { return string(underscore()) diff --git a/underscore_test.go b/underscore_test.go index aa1a930..be0805d 100644 --- a/underscore_test.go +++ b/underscore_test.go @@ -6,6 +6,10 @@ import ( "github.com/robertkrimen/otto/underscore" ) +func init() { + underscore.Disable() +} + func underscoreTest() func(string, ... interface{}) Value { Otto, test := runTestWithOtto() Otto.Run(underscore.Source())