Sha256: 6eaf7dac22697c61e864398b29604a542edf186265dc616c15e3d3cd1be452e3

Contents?: true

Size: 850 Bytes

Versions: 3

Compression:

Stored size: 850 Bytes

Contents

require 'rest_in_peace/errors'

module RESTinPeace
  class TemplateSanitizer

    class IncompleteParams < RESTinPeace::DefaultError; end

    def initialize(url_template, params, klass)
      @url_template = url_template
      @params = params.dup
      @klass = klass
      @url = nil
    end

    def url
      return @url if @url
      @url = @url_template.dup
      tokens.each do |token|
        param = @params.delete(token.to_sym)
        param ||= @klass.send(token) if @klass.respond_to?(token)
        raise IncompleteParams, "Unknown parameter for token :#{token} found" unless param
        @url.sub!(%r{:#{token}}, param.to_s)
      end
      @url
    end

    def tokens
      @url_template.scan(%r{:([a-z_]+)}).flatten
    end

    def leftover_params
      @params.delete_if { |param| tokens.include?(param.to_s) }
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rest-in-peace-4.2.1 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-4.2.0 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-4.1.1 lib/rest_in_peace/template_sanitizer.rb