Class: RemoteRails::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/rrails/client.rb

Overview

client for RemoteRails::Server.

Examples:

client = RemoteRails::Client.new({
  :cmd => "rails generate model Sushi",
  :port => 5656,
  :host => 'localhost'
})
client.run

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Client

Returns a new instance of Client.



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rrails/client.rb', line 18

def initialize(options={})
  @cmd = options[:cmd] || ""

  @rails_env = options[:rails_env] || ENV['RAILS_ENV'] || 'development'


  @use_pty = options[:pty]
  @ondemand_callback = options[:ondemand_callback]

  if @cmd.is_a? Array
    require 'shellwords'
    @cmd = Shellwords.join(@cmd)
  end

  if (options[:host] || options[:port]) && !options[:socket]
    @socket = nil
    @host = options[:host] || 'localhost'
    @port = options[:port] || DEFAULT_PORT[@rails_env]
  else
    @socket = "#{options[:socket] || './tmp/sockets/rrails-'}#{@rails_env}.socket"
  end

  if @use_pty.nil?
    # decide use_pty from cmd
    case @cmd
    when /^rails (?:c(?:onsole)?|db(?:console)?)$/, 'pry'
      @use_pty = true
    end
  end
end

Instance Method Details

#runObject



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rrails/client.rb', line 49

def run
  sock = nil
  begin
    sock = connect
  rescue
    if @ondemand_callback
      @ondemand_callback.call
      sock = connect
    end
  end

  sock.puts("#{@use_pty ? 'P' : ' '}#@cmd")
  running = true

  begin
    # input thread
    thread = Thread.start do
      while running do
        begin
          input = @use_pty ? STDIN.getch : STDIN.gets
          sock.write(input)
          sock.flush
        rescue
          running = false
          sock.close unless sock.closed?
        end
      end
    end

    while running && line = sock.gets
      case line.chomp
      when /^EXIT\t(.+)$/
        return $1.to_i
      when /^OUT\t(.+)$/
        STDOUT.write($1.split(',').map(&:to_i).pack('c*'))
      when /^ERR\t(.+)$/
        STDERR.write($1.split(',').map(&:to_i).pack('c*'))
      end
    end

  rescue EOFError
    running = false
  rescue Interrupt
    running = false
    return 130
  ensure
    running = false
    thread.kill
  end

  STDERR.puts "\r\nERROR: RRails server disconnected"
  return -1
end