class ChupaText::PathConverter

Public Class Methods

new(path, options={}) click to toggle source
# File lib/chupa-text/path-converter.rb, line 21
def initialize(path, options={})
  @path = path
  @options = options
end

Public Instance Methods

convert() click to toggle source
# File lib/chupa-text/path-converter.rb, line 26
def convert
  path = @path
  encoding = @options[:encoding]
  path = convert_encoding(path, encoding) if encoding
  path = convert_to_uri_path(path) if @options[:uri_escape]
  path
end

Private Instance Methods

convert_encoding(path, encoding) click to toggle source
# File lib/chupa-text/path-converter.rb, line 35
def convert_encoding(path, encoding)
  case path.encoding
  when Encoding::ASCII_8BIT
    if path.ascii_only?
      path.force_encoding(Encoding::UTF_8)
    else
      candidates = [
        Encoding::UTF_8,
        Encoding::EUC_JP,
        Encoding::Windows_31J,
      ]
      found = false
      candidates.find do |candidate|
        path.force_encoding(candidate)
        if path.valid_encoding?
          found = true
          break
        end
      end
      path.force_encoding(Encoding::ASCII_8BIT) unless found
    end
  end
  path.encode(encoding,
              invalid: :replace,
              undef: :replace,
              replace: "")
end
convert_to_uri_path(path) click to toggle source
# File lib/chupa-text/path-converter.rb, line 63
def convert_to_uri_path(path)
  converted_components = path.split("/").collect do |component|
    CGI.escape(component)
  end
  converted_components.join("/")
end