class StubRequests::URI::Builder
Builder
constructs and validates URIs
@author Mikael Henriksson <mikael@zoolutions.se>
Constants
- URI_KEY
@return [Regexp] A pattern for matching url segment keys
Attributes
@!attribute [r] expected_keys
@return [Array<String>] a list of expected route keys
@!attribute [r] received_keys
@return [Array<String>] a list with actual {#route_params} keys
@!attribute [r] route_params
@return [Hash<Symbol] a hash with keys matching the {#template}
@!attribute [r] uri
@return [String] the URI to the service endpoint
Public Class Methods
Convenience method to avoid .new.build
@raise [UriSegmentMismatch] when there are unused URI
segments @raise [UriSegmentMismatch] when the template have unplaced URI
segments
@param [String] the URI
to the service endpoint @param [Hash<Symbol>] route_params
a list of uri_replacement keys
@return [String] a validated URI
string
# File lib/stub_requests/uri/builder.rb, line 38 def self.build(uri, route_params = {}) new(uri, route_params).build end
Initializes a new Builder
@param [String] uri the URI
used to reach the service @param [Hash<Symbol>] route_params
a list of uri_replacement keys
# File lib/stub_requests/uri/builder.rb, line 66 def initialize(uri, route_params = {}) @uri = +uri @route_params = route_params.to_route_param @received_keys = @route_params.keys @expected_keys = uri.scan(URI_KEY).flatten.uniq end
Public Instance Methods
Builds a URI
string
@raise [UriSegmentMismatch] when there are unused URI
segments @raise [UriSegmentMismatch] when the template have unplaced URI
segments
@return [String] a validated URI
string
# File lib/stub_requests/uri/builder.rb, line 82 def build validate_uri_has_route_params! build_uri validate_uri uri end
Private Instance Methods
# File lib/stub_requests/uri/builder.rb, line 102 def build_uri route_params.each do |key, value| replace_key(key, value) end end
# File lib/stub_requests/uri/builder.rb, line 108 def replace_key(key, value) uri.gsub!(key, value.to_s) end
Validates {#uri} is valid
@return [true, false]
# File lib/stub_requests/uri/builder.rb, line 118 def validate_uri StubRequests::URI::Validator.valid?(uri) rescue InvalidUri StubRequests.logger.warn("URI (#{uri}) is not valid.") false end
# File lib/stub_requests/uri/builder.rb, line 98 def validate_uri_has_route_params expected_keys.sort == received_keys.sort end
# File lib/stub_requests/uri/builder.rb, line 92 def validate_uri_has_route_params! return if validate_uri_has_route_params raise UriSegmentMismatch, uri: uri, expected_keys: expected_keys, received_keys: received_keys end