Class: Paru::PandocFilter::Metadata

Inherits:
Hash
  • Object
show all
Defined in:
lib/paru/filter/metadata.rb

Overview

A Metadata object is a Ruby Hash representation of a pandoc metadata node.

Instance Method Summary collapse

Constructor Details

#initialize(contents = {}) ⇒ Metadata

Create a new Metadata object based on the contents.

Parameters:

  • contents (MetaMap|String|Hash) (defaults to: {})

    the initial contents of this metadata. If contents is a String, it is treated as a YAML string and converted to a Hash first.

Raises:

  • Error when converting contents to a Hash fails



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/paru/filter/metadata.rb', line 36

def initialize(contents = {})
    if not contents.is_a? Hash
        # If not a Hash, it is either a YAML string or can be
        # converted to a YAML string
        if contents.is_a? PandocFilter::MetaMap
            yaml_string = meta2yaml contents
        elsif contents.is_a? String
            yaml_string = contents
        else
            raise FilterError.new("Expected a Hash, MetaMap, or String, got '#{contents}' instead.")
        end

        # Try to convert the YAML string to a Hash
        if yaml_string.empty?
            contents = {}
        else
            contents = YAML.safe_load yaml_string, permitted_classes: [Date]
        end

        if not contents
            # Error parsing YAML
            raise FilterError.new("Unable to convert YAML string '#{yaml_string}' to a Hash.")
        end
    end

    # Merge the contents with this newly created Metadata
    contents.each do |key, value|
        self[key] = value
    end
end

Instance Method Details

#to_metaMeta

Convert this Metadata to a pandoc AST representation of metadata: Paru::PandocFilter::Meta

Returns:



71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/paru/filter/metadata.rb', line 71

def to_meta()
    if self.empty?
        PandocFilter::Meta.new {}
    else
        begin
            yaml_string = "#{clean_hash.to_yaml}..."
            yaml2json = Paru::Pandoc.new {from "markdown"; to "json"}
            json_string = yaml2json << yaml_string
            meta_doc = PandocFilter::Document.from_JSON json_string
            meta_doc.meta
        rescue
        end
    end
end