Class: Camcorder::Recorder

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename, verify_recordings: Camcorder.config.verify_recordings) ⇒ Recorder

Returns a new instance of Recorder.



11
12
13
14
15
16
# File 'lib/camcorder/recorder.rb', line 11

def initialize(filename, verify_recordings: Camcorder.config.verify_recordings)
  @filename = filename
  @recordings = {}
  @changed = false
  @verify_recordings = verify_recordings
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



9
10
11
# File 'lib/camcorder/recorder.rb', line 9

def filename
  @filename
end

#recordingsObject (readonly)

Returns the value of attribute recordings.



8
9
10
# File 'lib/camcorder/recorder.rb', line 8

def recordings
  @recordings
end

Instance Method Details

#commitObject



35
36
37
38
39
# File 'lib/camcorder/recorder.rb', line 35

def commit
  return unless @changed
  FileUtils.mkdir_p File.dirname(filename)
  File.open(filename, 'w') {|f| YAML.dump(recordings, f) }
end

#record(key, &block) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/camcorder/recorder.rb', line 41

def record(key, &block)
  if @replaying
    if recordings.has_key?(key)
      recordings[key].replay
    else
      raise PlaybackError.new(key)
    end
  else
    begin
      recording = Recording.new
      result = recording.record(&block)
    ensure
      @changed = true
      if recordings.has_key?(key)
        unless verify_recordings(recordings[key], recording)
          raise RecordingError.new(key)
        end
      else
        recordings[key] = recording
      end
      result
    end
  end
end

#startObject



25
26
27
28
29
30
31
32
33
# File 'lib/camcorder/recorder.rb', line 25

def start
  if File.exists?(filename)
    @recordings = YAML.load_file(filename)
    @replaying = true
  else
    @recordings = {}
    @replaying = false
  end
end

#transaction(&block) ⇒ Object



18
19
20
21
22
23
# File 'lib/camcorder/recorder.rb', line 18

def transaction(&block)
  start
  yield
ensure
  commit
end

#verify_recordings(a, b) ⇒ Object



66
67
68
69
70
71
72
73
74
# File 'lib/camcorder/recorder.rb', line 66

def verify_recordings(a, b)
  if @verify_recordings.is_a?(Proc)
    @verify_recordings.call(a, b)
  elsif @verify_recordings
    a == b
  else
    true
  end
end