title: best/most elegant way to share objects between a stack of rack mounted apps/middlewares?
body: <p>What is the best idiom to share an object between rack mounted applications/middlewares? </p>
  
  <p>For example, this config.ru has two Sinatra apps mapped to differents endpoints:</p>
  
  <pre><code>class App1 &lt; Sinatra::Base
    # ...
  end
  
  class App2 &lt; Sinatra::Base
    # ...
  end
  
  map '/app1' do
    run App1
  end
  
  map '/app2' do
    run App2
  end
  </code></pre>
  
  <p>Now if these two applications need to share an object, be it a database connector or any other object, what would be the best idiom for this?</p>
  
  <p>I see basically two options:</p>
  
  <p>1- Create a constant at the config.ru level and simply refer to that constant within the apps. For example:</p>
  
  <pre><code>SHARED_OBJECT = "hello world"
  
  class App1 &lt; Sinatra::Base
    get '/' do
      SHARED_OBJECT
    end
  end
  
  class App2 &lt; Sinatra::Base
    get '/' do
      SHARED_OBJECT
    end
  end
  
  map '/app1' do
    run App1
  end
  
  map '/app2' do
    run App2
  end
  </code></pre>
  
  <p>2- Create a singleton object at the config.ru level and use it within the apps. For example:</p>
  
  <pre><code>class SharedObject
    include Singleton
  
    def test
      @test ||= "hello world"
    end
  end
  
  class App1 &lt; Sinatra::Base
    get '/' do
      SharedObject.instance.test
    end
  end
  
  class App2 &lt; Sinatra::Base
    get '/' do
      SharedObject.instance.test
    end
  end
  
  map '/app1' do
    run App1
  end
  
  map '/app2' do
    run App2
  end
  </code></pre>
  
  <p>Comments/suggestions?<br>
  Colin</p>