Class: Ru::Process

Inherits:
Object
  • Object
show all
Defined in:
lib/ru/process.rb

Instance Method Summary collapse

Constructor Details

#initializeProcess

Returns a new instance of Process.



6
7
8
# File 'lib/ru/process.rb', line 6

def initialize
  @option_printer = OptionPrinter.new
end

Instance Method Details

#runObject



10
11
12
13
14
15
16
17
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
48
49
50
# File 'lib/ru/process.rb', line 10

def run
  output = process_options
  return output if output

  args  = ARGV.dup
  @code = args.shift

  if @code.blank?
    $stderr.puts @option_printer.run(:help)
    return
  end

  @parsed = prepare_code(@code)
  @stdin  = get_stdin(args, @options[:stream]) if @parsed[:get_stdin]

  context =
    if @stdin.nil?
      Ru::Array.new([])
    else
      if @options[:stream]
        if @options[:binary]
          Ru::Stream.new(@stdin.each_byte.lazy)
        else
          Ru::Stream.new(@stdin.each_line.lazy.map { |line| line.chomp("\n".freeze) })
        end
      else
        if @options[:binary]
          Ru::Array.new(@stdin.bytes)
        else
          # Prevent 'invalid byte sequence in UTF-8'
          @stdin.encode!('UTF-8', 'UTF-8', invalid: :replace)
          Ru::Array.new(@stdin.split("\n"))
        end
      end
    end

  output = context.instance_eval(@parsed[:code])
  output = @stdin if output == nil

  prepare_output(output)
end