Class: SSHake::Recorder

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

Class Attribute Summary collapse

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, cache: nil) ⇒ Recorder

Returns a new instance of Recorder.



19
20
21
22
# File 'lib/sshake/recorder.rb', line 19

def initialize(name, cache: nil)
  @name = name
  @cache = cache || {}
end

Class Attribute Details

.save_rootnil, String

Return the root where all recorded sessions should be stored

Returns:

  • (nil, String)


12
13
14
# File 'lib/sshake/recorder.rb', line 12

def save_root
  @save_root
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



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

def cache
  @cache
end

#nameObject (readonly)

Returns the value of attribute name.



16
17
18
# File 'lib/sshake/recorder.rb', line 16

def name
  @name
end

Instance Method Details

#loadObject



24
25
26
27
28
# File 'lib/sshake/recorder.rb', line 24

def load
  return if self.class.save_root.nil?

  @cache = YAML.load_file(File.join(self.class.save_root, "#{name}.yml"))
end

#play(command, connection: {}, options: nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/sshake/recorder.rb', line 37

def play(command, connection: {}, options: nil)
  possibilities = @cache[command]
  return nil if possibilities.nil?

  options_as_hash = options_to_hash(options)

  possibility = possibilities.find do |p|
    p[:options] == options_as_hash &&
      p[:connection] == connection
  end

  return nil if possibility.nil?

  response = Response.new(cached: true)
  possibility[:response].each do |key, value|
    response.public_send("#{key}=", value)
  end
  response
end

#record(command, response, connection: {}, options: nil) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/sshake/recorder.rb', line 57

def record(command, response, connection: {}, options: nil)
  @cache[command] ||= []
  @cache[command] << {
    connection: connection,
    options: options_to_hash(options),
    response: response_to_hash(response)
  }
  save
end

#saveObject



30
31
32
33
34
35
# File 'lib/sshake/recorder.rb', line 30

def save
  return if self.class.save_root.nil?

  FileUtils.mkdir_p(self.class.save_root)
  File.write(File.join(self.class.save_root, "#{name}.yml"), @cache.to_yaml)
end