Sha256: f96bb41b133b4a3fa0cb78dcbbd4a6a88acf4096fc8a48ec87e85ef093d544a4

Contents?: true

Size: 857 Bytes

Versions: 6

Compression:

Stored size: 857 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, "No parameter for token :#{token} found" unless param
        @url.sub!(%r{:#{token}}, CGI.escape(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

6 entries across 6 versions & 1 rubygems

Version Path
rest-in-peace-6.0.3 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-6.0.2 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-6.0.0 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-5.1.0 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-5.0.2 lib/rest_in_peace/template_sanitizer.rb
rest-in-peace-5.0.1 lib/rest_in_peace/template_sanitizer.rb