Class: AbstractCommand

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

Overview

Shell Command Abstraction.

Hides away all the details to generate a command. And privides an easy interface to interact with shell commands as if they were objects.

This is good for the following reasons:

  1. Stadardization.

  2. Simplicity of code.

  3. Reduces smells in methods that interpolate values.

  4. Provides an elegant way to interact shell objects.

  5. Secure ensures that shell commands are executed safely.

Constant Summary collapse

VARIABLE_REGEX =

‘%<name>s’.scan(/(%<)(w+)(>)/)

> [[“%<”, “name”, “>”]]

/(%<)(\w+)(>)/

Instance Method Summary collapse

Constructor Details

#initialize(properties = {}) ⇒ AbstractCommand

Returns a new instance of AbstractCommand.



35
36
37
38
39
40
41
42
43
# File 'lib/abstract_command.rb', line 35

def initialize(properties = {})
  variables.each do |variable|
    self.class.send(:attr_accessor, variable.to_sym)
  end
  properties.each do |key, value|
    setter = (key.to_s + '=').to_sym
    send(setter, value)
  end
end

Instance Method Details

#backtickObject



58
59
60
# File 'lib/abstract_command.rb', line 58

def backtick
  `#{to_s}`
end

#executeObject



62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/abstract_command.rb', line 62

def execute
  begin
    stdout, stderr, status = Open3.capture3(to_s)
    status = status.exitstatus
  rescue StandardError => error
    stdout = ""
    if(error.message)
      stderr = error.message
    end
    status = 1
  end
  return stdout, stderr, status
end

#systemObject



54
55
56
# File 'lib/abstract_command.rb', line 54

def system
  super(to_s)
end

#templateObject



23
24
25
# File 'lib/abstract_command.rb', line 23

def template
  raise 'must implement'
end

#to_sObject



45
46
47
48
49
50
51
52
# File 'lib/abstract_command.rb', line 45

def to_s
  bindings = {}
  variables.each do |variable|
    value = instance_variable_get("@#{variable}")
    bindings[variable.to_sym] = "#{value}".shellescape
  end
  format(template, bindings)
end

#variablesObject



27
28
29
30
31
32
33
# File 'lib/abstract_command.rb', line 27

def variables
  result = []
  template.scan(VARIABLE_REGEX).each do |variable|
    result.push(variable[1])
  end
  result
end