Sha256: f285abe27a49804849efe3291e35b230fb41180ad8e2f622d077546821819962

Contents?: true

Size: 1.4 KB

Versions: 8

Compression:

Stored size: 1.4 KB

Contents

require "readline"

module Ellen
  module Adapters
    class Shell < Base
      PROMPT = "> "

      SOURCE = "shell"

      USAGE = "Type `exit` or `quit` to end the session."

      attr_accessor :stopped

      def initialize(*args)
        super
        remember
      end

      def run
        explain
        listen
      end

      def say(message)
        Ellen.logger.info(message[:body])
      end

      private

      def explain
        Ellen.logger.info(USAGE)
      end

      def read
        Readline.readline(PROMPT, true).tap do |line|
          history_file.puts(line)
        end
      end

      def listen
        step until stopped?
      rescue Interrupt
        stop
      end

      def step
        case body = read
        when "exit", "quit"
          stop
        else
          robot.receive(body: body, source: SOURCE)
        end
      end

      def stopped?
        !!stopped
      end

      def stop
        self.stopped = true
      end

      def remember
        if history_pathname.exist?
          history_pathname.each_line do |line|
            Readline::HISTORY << line.rstrip
          end
        end
      end

      def history_pathname
        @history_pathname ||= Pathname.new("~/.ellen_history").expand_path
      end

      def history_file
        @history_file ||= history_pathname.open("a").tap do |file|
          file.sync = true
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
ellen-0.2.8 lib/ellen/adapters/shell.rb
ellen-0.2.7 lib/ellen/adapters/shell.rb
ellen-0.2.6 lib/ellen/adapters/shell.rb
ellen-0.2.5 lib/ellen/adapters/shell.rb
ellen-0.2.4 lib/ellen/adapters/shell.rb
ellen-0.2.3 lib/ellen/adapters/shell.rb
ellen-0.2.2 lib/ellen/adapters/shell.rb
ellen-0.2.1 lib/ellen/adapters/shell.rb