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 = {}, treat_metadata_strings_as_plain_strings: false) ⇒ Metadata

Create a new Metadata object based on the contents.

metadata string values as plain strings instead of markdown strings if all AST leaf metadata string values have pandoc type “MetaString”. This option is only relevant when you only set metadata string values via command-line option ‘–metadata` and not also via a YAML or title block. Using this option improves performance in this specific situation because metadata values don’t have to be converted to string by pandoc in a separate process but can be collected as is.

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.

  • treat_metadata_strings_as_plain_strings (Boolean = false) (defaults to: false)

    treat

Raises:

  • Error when converting contents to a Hash fails



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/paru/filter/metadata.rb', line 45

def initialize(contents = {}, treat_metadata_strings_as_plain_strings: false)
  # When feature toggle treat_metadata_strings_as_plain_strings is on,
  # try to map the MetaMap node to a Hash directly and use that as the
  # contents of this Metadata object. We can only map the MetaMap node
  # when all string values have pandoc type "MetaString".
  if  && contents.is_a?(PandocFilter::MetaMap)
     = meta_to_value(contents)
    contents =  unless .nil?
  end

  contents = convert_to_hash_via_yaml(contents) unless contents.is_a?(Hash)

  # Merge the contents with this newly created Metadata
  super()

  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:



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

def to_meta
  if empty?
    PandocFilter::Meta.new({})
  else
    begin
      yaml_string = "#{clean_hash.to_yaml}..."
      yaml2json = Paru::Pandoc.new do
        from 'markdown'
        to 'json'
      end
      json_string = yaml2json << yaml_string
      meta_doc = PandocFilter::Document.from_JSON json_string
      meta_doc.meta
    rescue StandardError
      # Ignore silently to not interfere with pandoc conversion
    end
  end
end