lib/nanoc/helpers/link_to.rb in nanoc-2.1.6 vs lib/nanoc/helpers/link_to.rb in nanoc-2.2

- old
+ new

@@ -5,10 +5,11 @@ # To activate this helper, +include+ it, like this: # # include Nanoc::Helpers::LinkTo module LinkTo + require 'nanoc/helpers/html_escape' include Nanoc::Helpers::HTMLEscape # Creates a HTML link to the given path or page/asset representation, and # with the given text. # @@ -64,9 +65,48 @@ # Create message "<span class=\"active\" title=\"You're here.\">#{text}</span>" else link_to(text, path_or_rep, attributes) end + end + + # Returns the relative path from the current page to the given path or + # page/asset representation. + # + # +path_or_rep+:: the URL or path (a String) to where the relative should + # point, or the page or asset representation to which the + # relative should point. + # + # Example: + # + # # if the current item's path is /foo/bar/ + # relative_path('/foo/qux/') + # # => '../qux/' + def relative_path_to(path_or_rep) + require 'pathname' + + # Find path + path = path_or_rep.is_a?(String) ? path_or_rep : path_or_rep.path + + # Get source and destination paths + dst_path = Pathname.new(path) + src_path = Pathname.new(@item.path) + + # Calculate elative path (method depends on whether destination is a + # directory or not). + if src_path.to_s[-1,1] != '/' + relative_path = dst_path.relative_path_from(src_path.dirname).to_s + else + relative_path = dst_path.relative_path_from(src_path).to_s + end + + # Add trailing slash if necessary + if dst_path.to_s[-1,1] == '/' + relative_path += '/' + end + + # Done + relative_path end end end