Class: PS::Command

Inherits:
Object
  • Object
show all
Defined in:
lib/ps/command.rb

Constant Summary collapse

ARR_ARGS =
{
  :format => '-o ',
  :gid => '-G ',
  :group => '-g ',
  :uid => '-u ',
  :pid => '-p ',
  :tty => '-t ',
  :user => '-U ',
  :flag => '-'
}
FLAG_LIST =
'AaCcEefhjlMmrSTvwXx'.split('').freeze

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Command

Returns a new instance of Command.



17
18
19
20
21
22
# File 'lib/ps/command.rb', line 17

def initialize opts={}
  ARR_ARGS.keys.each do |arg|
    arr = opts[arg] || []
    instance_variable_set "@#{arg}s", arr
  end
end

Instance Method Details

#regexObject



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/ps/command.rb', line 42

def regex
  r = @last_ran_formats.inject("") do |reg,fmt|
    reg << '\s*' << case fmt
    when 'command='
      '(.+)$'
    when 'lstart='
      '(\w{3}\s\w{3}\s[\s\d]{2}\s[\d\:]{8}\s\d{4})'
    else
      '([\w\,_\-\.]+)'
    end
  end

  Regexp.new(r)
end

#run!Object



38
39
40
# File 'lib/ps/command.rb', line 38

def run!
  `#{to_s}`.chomp
end

#to_hashesObject



57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/ps/command.rb', line 57

def to_hashes
  reg = nil
  run!.split("\n").collect do |line|
    reg ||= regex
    m = line.match(reg)
    hsh = {}
    @last_ran_formats.each_with_index do |val,i|
      hsh[val.sub('=','')] = m[i+1].rstrip
    end

    hsh
  end
end

#to_processesObject



71
72
73
# File 'lib/ps/command.rb', line 71

def to_processes
  to_hashes.inject(ProcessList.new) {|plist,hsh| plist << Process.new(hsh)}
end

#to_sObject



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ps/command.rb', line 24

def to_s
  cmd = []

  parse_formats!

  ARR_ARGS.each do |var,trigger|
    sep = var == :flags ? nil : ','
    vals = instance_variable_get("@#{var}s").uniq
    cmd << trigger+vals.join(sep) unless vals.empty?
  end

  "ps "<<cmd.join(' ')
end