Sha256: 866fb9eae65bdca156179b9752ec10a9da78e8cd2a477a38ae8bd32ad0f2f759

Contents?: true

Size: 1.64 KB

Versions: 2

Compression:

Stored size: 1.64 KB

Contents

require 'pact/logging'

module Pact
  module Generator
    # ProviderState provides the provider state generator which will inject
    # values provided by the provider state setup url.
    class ProviderState
      include Pact::Logging

      # rewrite of https://github.com/DiUS/pact-jvm/blob/master/core/support/src/main/kotlin/au/com/dius/pact/core/support/expressions/ExpressionParser.kt#L27
      VALUES_SEPARATOR = ','
      START_EXPRESSION = "\${"
      END_EXPRESSION = '}'

      def can_generate?(hash)
        hash.key?('type') && hash['type'] == 'ProviderState'
      end

      def call(hash, params = nil, _example_value = nil)
        params ||= {}
        parse_expression hash['expression'], params
      end

      def parse_expression(expression, params)
        return_string = []
        buffer = expression
        # initial value
        position = buffer.index(START_EXPRESSION)

        while position && position >= 0
          if position.positive?
            # add string
            return_string.push(buffer[0...position])
          end
          end_position = buffer.index(END_EXPRESSION, position)
          raise 'Missing closing brace in expression string' if !end_position || end_position.negative?

          variable = buffer[position + 2...end_position]

          logger.info "Could not subsitute provider state key #{variable}, have #{params}" unless params[variable]

          expression = params[variable] || ''
          return_string.push(expression)

          buffer = buffer[end_position + 1...-1]
          position = buffer.index(START_EXPRESSION)
        end

        return_string.join('')
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
pact-support-1.21.1 lib/pact/generator/provider_state.rb
pact-support-1.21.0 lib/pact/generator/provider_state.rb