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.

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.



29
30
31
32
33
34
35
36
37
# File 'lib/abstract_command.rb', line 29

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



52
53
54
# File 'lib/abstract_command.rb', line 52

def backtick
  `#{to_s}`
end

#systemObject



48
49
50
# File 'lib/abstract_command.rb', line 48

def system
  Kernel.system(to_s)
end

#templateObject



17
18
19
# File 'lib/abstract_command.rb', line 17

def template
  raise 'must implement'
end

#to_sObject



39
40
41
42
43
44
45
46
# File 'lib/abstract_command.rb', line 39

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

#variablesObject



21
22
23
24
25
26
27
# File 'lib/abstract_command.rb', line 21

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