Class: Betamax::Tape

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

Constant Summary collapse

PERMITTED_YAML_CLASSES =
[
  Betamax::Recording,
  Betamax::RecordedObject,
  Betamax::RecordedMethod,
  Betamax::RecordedYielding,
  Symbol
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Tape

Returns a new instance of Tape.



16
17
18
19
# File 'lib/betamax/tape.rb', line 16

def initialize path
  @path = Pathname.new path
  @recording = nil
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



14
15
16
# File 'lib/betamax/tape.rb', line 14

def path
  @path
end

#recordingObject (readonly)

Returns the value of attribute recording.



14
15
16
# File 'lib/betamax/tape.rb', line 14

def recording
  @recording
end

Class Method Details

.cassette_name_for(metadata) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/betamax/tape.rb', line 33

def self.cassette_name_for 
  # Build name from example group hierarchy + example description
  description_parts = []

  # Add the example description first
  description_parts << [:description] if [:description]

  # Walk up the example group hierarchy
  current = [:example_group]
  while current
    description_parts.unshift current[:description] if current[:description]
    current = current[:parent_example_group]
  end

  description_parts.join "/"
end

.from_rspec_example(example, tapes_folder:) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
# File 'lib/betamax/tape.rb', line 21

def self.from_rspec_example example, tapes_folder:
  name = cassette_name_for example.
  name.gsub! "::", "_"
  name.gsub!(/[\s-]+/, "_")
  name.gsub! %r{[^a-zA-Z0-9_/]}, ""

  filename = Pathname.new(name).sub_ext ".yaml"
  full_path = tapes_folder / filename

  new full_path
end

Instance Method Details

#exists?Boolean

Returns:

  • (Boolean)


74
75
76
# File 'lib/betamax/tape.rb', line 74

def exists?
  File.exist? @path
end

#loadObject



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/betamax/tape.rb', line 50

def load
  FileUtils.mkdir_p @path.dirname

  if exists?
    load_existing_recording
  else
    prepare_new_recording
  end

  self
end

#save(proxy) ⇒ Object



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

def save proxy
  return if exists? # Don't overwrite existing recordings

  recording = Betamax::Recording.new \
    version: Recording::VERSION,
    objects: { default: proxy }

  File.open @path, "w" do |file|
    file.puts recording.to_yaml
  end
end