class Inkcite::Cli::Server

Constants

NO_CACHE
REQUEST_ROOT

Public Class Methods

start(email, opts) click to toggle source
# File lib/inkcite/cli/server.rb, line 14
      def self.start email, opts

        Util.log "Inkcite #{Inkcite::VERSION} is starting up ..."
        Util.log 'Documentation available at http://inkcite.readme.io'

        # Read the hostname and port from the opts provided on the command
        # line - or inherit the default of localhost:4567
        port = opts[:port].to_i
        host = opts[:host]

        # Attempt to resolve the machine's public IP so we can display the
        # address for mobile devices.
        ip = begin
          IPSocket.getaddress(Socket.gethostname)
        rescue
          nil
        end

        fork do

          # Programmatically construct a Guard configuration file that
          # instructs it to monitor all of the HTML, TSV, YML and images
          # that can be used in the email project.
          guardfile = <<-EOF
            guard :livereload do
              watch(%r{^*.+\.(html|tsv|yml)})
              watch(%r{images/.+\.(gif|jpg|png)})
            end

            logger level: :error
          EOF

          # You can omit the call to Guard.setup, Guard.start will call Guard.setup
          # under the hood if Guard has not been setuped yet
          Guard.start :guardfile_contents => guardfile, :no_interactions => true

        end

        # Assemble the Rack app with the static content middleware and the
        # InkciteApp to server the email as the root index page.
        app = Rack::Builder.new do
          use Rack::LiveReload
          use Rack::Static, :urls => %w( /images/ ), :root => '.'
          use OptimizedImage, :email => email, :urls => %w( /images-optim/ ), :root => '.'
          run InkciteApp.new(email, opts)
        end

        Util.log ''
        Util.log "Your email is being served at http://#{host}:#{port}"
        Util.log "Point your mobile device to http://#{ip}:#{port}" if ip
        Util.log 'Press CTRL-C to exit server mode'
        Util.log ''

        begin

          # Start the server and disable WEBrick's verbose logging.
          Rack::Server.start({
                  :Host => host,
                  :Port => port,
                  :AccessLog => [],
                  :Logger => WEBrick::Log.new(nil, 0),
                  :app => app
              })
        rescue Errno::EADDRINUSE
          abort <<-USAGE.strip_heredoc

            Oops!  Inkcite can't start its preview server.  Port #{port} is
            unavailable. Either close the instance of Inkcite already running
            on that port or start this Inkcite instance on a new port with:

              inkcite server --port=#{port+1}

          USAGE
        end

      end