Sha256: efa4d0cb91e807dcc5c0c23ab626f71d273368d3c75c6e235f50b602a20f0a6e

Contents?: true

Size: 1.41 KB

Versions: 3

Compression:

Stored size: 1.41 KB

Contents

require 'cgi'

require_relative 'token'
require_relative 'config'

module DocJuan
  class NoHostGivenError < StandardError; end

  class UrlGenerator
    attr_reader :url, :filename, :format, :options

    def initialize url, filename, format = 'pdf', options = {}
      @url = url
      @filename = filename.to_s
      @format = format

      options = {} unless options
      options = options.merge authentication_credentials if has_authentication_credentials?
      @options = options

      raise NoHostGivenError if host == ''
    end

    def generate
      params = []
      params << "url=#{CGI.escape(url)}"
      params << "filename=#{CGI.escape(filename)}"
      params << "format=#{CGI.escape(format)}"
      options.each do |k,v|
        params << "options[#{CGI.escape(k.to_s)}]=#{CGI.escape v.to_s}"
      end
      params << "key=#{public_key}"

      "#{host}/render?#{params.join('&')}"
    end

    def public_key
      @public_key ||= DocJuan::Token.new(self).key
    end

    def host
      @host ||= DocJuan.config.host.to_s.strip.tap do |host|
        if host != '' && ! host.start_with?('http')
          host.replace "http://#{host}"
        end
      end
    end

    def authentication_credentials
      {
        username: DocJuan.config.username,
        password: DocJuan.config.password
      }
    end

    def has_authentication_credentials?
      authentication_credentials.values.compact.any?
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
doc_juan-1.2.2 lib/doc_juan/url_generator.rb
doc_juan-1.2.1 lib/doc_juan/url_generator.rb
doc_juan-1.2.0 lib/doc_juan/url_generator.rb