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) ⇒ Recorder

Returns a new instance of Recorder.



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

def initialize(filename)
  @filename = filename
  @recordings = {}
  @changed = false
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



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

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



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

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)
        if recordings[key] != recording
          raise RecordingError.new(key)
        end
      else
        recordings[key] = recording
      end
      result
    end
  end
end

#startObject



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

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

#transaction(&block) ⇒ Object



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

def transaction(&block)
  start
  yield
ensure
  commit
end