Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

CoffeeScript bridge mode


May 09, 2021 CoffeeScript


Table of contents


Bridge mode

Problem

You need to maintain a reliable interface for your code that can change frequently or be converted between multiple implementations.

Solution

Use briddle mode as an intermediate for different implementations and remaining code.

Suppose you have developed a browser text editor to save to the cloud. However, now you need to save it locally through the port of a stand-alone client.

class TextSaver
    constructor: (@filename, @options) ->
    save: (data) ->

class CloudSaver extends TextSaver
    constructor: (@filename, @options) ->
        super @filename, @options
    save: (data) ->
        # Assuming jQuery
        # Note the fat arrows
        $( =>
            $.post "#{@options.url}/#{@filename}", data, =>
                alert "Saved '#{data}' to #{@filename} at #{@options.url}."
        )

class FileSaver extends TextSaver
    constructor: (@filename, @options) ->
        super @filename, @options
        @fs = require 'fs'
    save: (data) ->
        @fs.writeFile @filename, data, (err) => # Note the fat arrow
            if err? then console.log err
            else console.log "Saved '#{data}' to #{@filename} in #{@options.directory}."

filename = "temp.txt"
data = "Example data"

saver = if window?
    new CloudSaver filename, url: 'http://localhost' # => Saved "Example data" to temp.txt at http://localhost
else if root?
    new FileSaver filename, directory: './' # => Saved "Example data" to temp.txt in ./

saver.save data

Discuss

Briddle mode can help you keep the code for a particular implementation out of sight so you can focus on the specific code in your program. In the example above, the rest of the application can be called save.save data, regardless of the end of the file.