module Nanoc::Helpers::LinkTo

@see nanoc.app/doc/reference/helpers/#linkto

Public Instance Methods

relative_path_to(target) click to toggle source

@return [String]

# File lib/nanoc/helpers/link_to.rb, line 55
def relative_path_to(target)
  # Find path
  if target.is_a?(String)
    path = target
  else
    path = target.path
    if path.nil?
      # TODO: get proper error
      raise "Cannot get the relative path to #{target.inspect} because this target is not outputted (its routing rule returns nil)"
    end
  end

  # Handle Windows network (UNC) paths
  if path.start_with?('//', '\\\\')
    return path
  end

  # Get source and destination paths
  dst_path = Pathname.new(path)
  if @item_rep.path.nil?
    # TODO: get proper error
    raise "Cannot get the relative path to #{path} because the current item representation, #{@item_rep.inspect}, is not outputted (its routing rule returns nil)"
  end

  src_path = Pathname.new(@item_rep.path)

  # Calculate the relative path (method depends on whether destination is
  # a directory or not).
  from = src_path.to_s.end_with?('/') ? src_path : src_path.dirname
  relative_path = dst_path.relative_path_from(from).to_s

  # Add trailing slash if necessary
  if dst_path.to_s.end_with?('/')
    relative_path << '/'
  end

  # Done
  relative_path
end