File: erb_renderer.rb

package info (click to toggle)
ruby-vcr 6.0.0%2Breally5.0.0-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,320 kB
  • sloc: ruby: 8,456; sh: 177; makefile: 7
file content (55 lines) | stat: -rw-r--r-- 1,413 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
require 'erb'

module VCR
  class Cassette
    # @private
    class ERBRenderer
      def initialize(raw_template, erb, cassette_name=nil)
        @raw_template, @erb, @cassette_name = raw_template, erb, cassette_name
      end

      def render
        return @raw_template if @raw_template.nil? || !use_erb?
        binding = binding_for_variables if erb_variables
        template.result(binding)
      rescue NameError => e
        handle_name_error(e)
      end

    private

      def handle_name_error(e)
        example_hash = (erb_variables || {}).merge(e.name => 'some value')

        raise Errors::MissingERBVariableError.new(
          "The ERB in the #{@cassette_name} cassette file references undefined variable #{e.name}.  " +
          "Pass it to the cassette using :erb => #{ example_hash.inspect }."
        )
      end

      def use_erb?
        !!@erb
      end

      def erb_variables
        @erb if @erb.is_a?(Hash)
      end

      def template
        @template ||= ERB.new(@raw_template)
      end

      @@struct_cache = Hash.new do |hash, attributes|
        hash[attributes] = Struct.new(*attributes)
      end

      def variables_object
        @variables_object ||= @@struct_cache[erb_variables.keys].new(*erb_variables.values)
      end

      def binding_for_variables
        @binding_for_variables ||= variables_object.instance_eval { binding }
      end
    end
  end
end