import yaml
from pathlib import Path


def _create_relative_dumper(folder):
    """
    Create a Dump implementation that can dump pathlib.Path() objects as relative paths.

    Paths will be output relative to the given folder param.

    :type folder: str
    :rtype: yaml.Dumper
    """

    # We can't control how many ancestors this dumper API uses, Pylint.
    # pylint: disable=too-many-ancestors
    class RelativeDumper(yaml.Dumper):
        pass

    def path_representer(dumper, data):
        """
        :type dumper: yaml.representer.BaseRepresenter
        :type data: pathlib.Path
        :rtype: yaml.nodes.Node
        """
        if not data.is_absolute():
            data = Path(folder).joinpath(data)
        return dumper.represent_scalar(u'tag:yaml.org,2002:str', str(data.relative_to(folder)))

    RelativeDumper.add_multi_representer(Path, path_representer)
    RelativeDumper.ignore_aliases = lambda self, data: True

    return RelativeDumper