class Prawn::SVG::Loaders::File

Attributes

root_path[R]

Public Class Methods

new(root_path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 33
def initialize(root_path)
  if root_path.empty?
    raise ArgumentError, "An empty string is not a valid root path.  Use '.' if you want the current working directory."
  end

  @root_path = ::File.expand_path(root_path)

  raise ArgumentError, "#{root_path} is not a directory" unless Dir.exist?(@root_path)
end

Public Instance Methods

from_url(url) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 43
def from_url(url)
  uri = build_uri(url)

  if uri && uri.scheme.nil? && uri.path
    load_file(uri.path)

  elsif uri && uri.scheme == 'file'
    assert_valid_file_uri!(uri)
    path = windows? ? fix_windows_path(uri.path) : uri.path
    load_file(path)
  end
end

Private Instance Methods

assert_file_exists!(path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 93
def assert_file_exists!(path)
  if !::File.exist?(path)
    raise Prawn::SVG::UrlLoader::Error, "File #{path} does not exist"
  end
end
assert_valid_file_uri!(uri) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 87
def assert_valid_file_uri!(uri)
  if uri.host
    raise Prawn::SVG::UrlLoader::Error, "prawn-svg does not suport file: URLs with a host. Your URL probably doesn't start with three slashes, and it should."
  end
end
assert_valid_path!(path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 73
def assert_valid_path!(path)
  # TODO : case sensitive comparison, but it's going to be a bit of a headache
  # making it dependent on whether the file system is case sensitive or not.
  # Leaving it like this until it's a problem for someone.

  if !path.start_with?("#{root_path}#{::File::SEPARATOR}")
    raise Prawn::SVG::UrlLoader::Error, "file path is not inside the root path of #{root_path}"
  end
end
build_absolute_and_expand_path(path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 83
def build_absolute_and_expand_path(path)
  ::File.expand_path(path, root_path)
end
build_uri(url) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 66
def build_uri(url)
  begin
    URI(url)
  rescue URI::InvalidURIError
  end
end
fix_windows_path(path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 99
def fix_windows_path(path)
  if matches = path.match(%r(\A/[a-z]:/)i)
    path[1..-1]
  else
    path
  end
end
load_file(path) click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 58
def load_file(path)
  path = URI.decode(path)
  path = build_absolute_and_expand_path(path)
  assert_valid_path!(path)
  assert_file_exists!(path)
  IO.binread(path)
end
windows?() click to toggle source
# File lib/prawn/svg/loaders/file.rb, line 107
def windows?
  !!(RbConfig::CONFIG['host_os'] =~ /mswin|msys|mingw|cygwin|bccwin|wince|emc/)
end