I’ve been working on a Coffee con Backbone project, and recently I’ve wanted a config file for my front end code. Stack Overflow had several good solutions, but once I started adapting them to CoffeeScript I decided to make use of the CoffeeScript Cookbook’s Singleton Pattern. Here’s what I wound up with:

config.js.coffee

 1 class SingletonConfig
 2   # Private scope
 3   # Ensure correct scope by setting instance to null.
 4   instance = null
 5 
 6   # This private class gets initialized by the singleton.
 7   class Config
 8     # The actual configuration attributes
 9     defaults:
10       foo: "bar"
11     development:
12       foo: "baz"
13 
14     # Set up our environment specific config,
15     # overriding defaults.
16     constructor: (env) ->
17       @config = _.extend @defaults, @[env]
18 
19     # Provide a Backbone-style shortcut to retrieve our
20     # config values.
21     get: (key) -> @config[key]
22 
23   # The static method to retrieve/create instance
24   @get: () ->
25     env = switch window.location.hostname
26       when "localhost", "127.0.0.1" then "development"
27       else "production"
28     instance ?= new Config(env)
29 
30 MyApp.Config = SingletonConfig.get()
31 
32 # http://localhost:3000/
33 MyApp.Config.get('foo') # => baz