Sha256: 55b40038e016b86c9bf3dc8507d37946dc4c407157a86807a226b8c8cdc920c6

Contents?: true

Size: 1.56 KB

Versions: 3

Compression:

Stored size: 1.56 KB

Contents

require 'sinatra'

module WhippedCream
  # A server handles building a plugin/runner and starting a web server
  class Server
    attr_reader :plugin

    def initialize(plugin)
      @plugin = plugin
    end

    def start(options = {})
      ensure_routes_built
      ensure_runner_started

      start_web(options)
    end

    def runner
      @runner ||= Runner.create_instance(plugin)
    end

    def port
      8080
    end

    def web
      @web ||= Web
    end

    private

    def ensure_runner_started
      runner
    end

    def ensure_routes_built
      @routes_built ||= build_routes || true
    end

    def start_web(options = {})
      options = options.merge({ app: web, port: port })

      Rack::Server.start options
    end

    def build_routes
      build_button_routes
      build_switch_routes
    end

    def build_button_routes
      plugin.buttons.each do |button|
        web.get "/#{button.id}" do
          runner.send(button.id)
          redirect to('/')
        end
      end
    end

    def build_switch_routes
      plugin.switches.each do |switch|
        web.get "/#{switch.id}" do
          runner.send(switch.id)
          redirect to('/')
        end
      end
    end

    # A Sinatra application skeleton that is used to build up the web server
    # for this plugin.
    class Web < Sinatra::Application
      get '/' do
        erb :index
      end

      private

      def controls
        runner.plugin.controls
      end

      def runner
        Runner.instance
      end

      def title
        runner.name
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
whipped-cream-0.0.1 lib/whipped-cream/server.rb
whipped-cream-0.0.1pre5 lib/whipped-cream/server.rb
whipped-cream-0.0.1pre4 lib/whipped-cream/server.rb