Class: Ru::Process

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

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Process

Returns a new instance of Process.



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

def initialize(options={})
  @command_manager = CommandManager.new
  @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
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/ru/process.rb', line 10

def run
  output = process_options
  return output if output

  args = ARGV
  first_arg = args.shift

  if first_arg == 'list'
    commands = @command_manager.all
    if commands.present?
      lines = ['Saved commands:']
      lines += commands.sort_by(&:first).map { |name, code| "#{name}\t#{code}" }
    else
      lines = [
        'No saved commands. To save a command, use `save`:',
        "ru save sum 'map(:to_i).sum'"
      ]
    end
    return lines.join("\n")
  elsif first_arg == 'run'
    name = args.shift
    @code = @command_manager.get(name)
    if @code.blank?
      STDERR.puts "Unable to find command '#{name}'"
      exit 1
      return
    end
  elsif first_arg == 'save'
    name = args[0]
    code = args[1]
    @command_manager.save(name, code)
    return "Saved command: #{name} is '#{code}'"
  elsif first_arg.blank?
    STDERR.puts @option_printer.run(:help)
    exit 1
    return
  else
    @code = first_arg
  end

  @stdin = get_stdin(args) unless @code.start_with?('! ')
  @code = prepare_code(@code) if @code

  lines = []
  unless @stdin.nil?
    # Prevent 'invalid byte sequence in UTF-8'
    @stdin.encode!('UTF-8', 'UTF-8', :invalid => :replace)
    lines = @stdin.split("\n")
  end
  array = Ru::Array.new(lines)
  output = array.instance_eval(@code) || @stdin
  output = prepare_output(output)
  output
end