Class: Rakali::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/rakali/converter.rb

Constant Summary collapse

DEFAULTS =

Default options.

{
  'from'          => { 'format' => 'md' },
  'to'            => { 'folder' => nil, 'format' => 'html' },
  'schema'        => 'default.json',
  'citations'     => false,
  'strict'        => false,
  'merge'         => false,
  'options'       => {}
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}) ⇒ Converter

Returns a new instance of Converter.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/rakali/converter.rb', line 19

def initialize(file, options = {})
  begin
    config = read_config_file(file)

    # deep merge defaults to preserve nested keys
    @config = Utils.deep_merge_hashes(DEFAULTS, config)

    # print configuration
    Rakali.logger.info "Configuration:", to_yaml

    from_folder = @config.fetch('from').fetch('folder')
    from_format = @config.fetch('from').fetch('format')
    documents = Dir.glob("#{from_folder}/*.#{from_format}")

    # merge all documents into one file if merge flag is set
    # otherwise iterate through each file in source folder
    if @config.fetch('merge')
      Rakali::Document.new(documents, @config)
    else
      documents.each { |document| Rakali::Document.new(document, @config) }
    end
  rescue KeyError => e
    Rakali.logger.abort_with "Fatal:", "Configuration #{e.message}."
  rescue => e
    Rakali.logger.abort_with "Fatal:", "#{e.message}."
  end
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



17
18
19
# File 'lib/rakali/converter.rb', line 17

def config
  @config
end

#documentsObject

Returns the value of attribute documents.



17
18
19
# File 'lib/rakali/converter.rb', line 17

def documents
  @documents
end

#errorsObject

Returns the value of attribute errors.



17
18
19
# File 'lib/rakali/converter.rb', line 17

def errors
  @errors
end

Instance Method Details

#from_json(string) ⇒ Object



54
55
56
57
58
# File 'lib/rakali/converter.rb', line 54

def from_json(string)
  JSON.parse(string)
rescue JSON::ParserError, TypeError
  nil
end

#read_config_file(file) ⇒ Object



47
48
49
50
51
52
# File 'lib/rakali/converter.rb', line 47

def read_config_file(file)
  # use an empty hash if the file is empty
  SafeYAML.load_file(file) || {}
rescue SystemCallError
  Rakali.logger.abort_with "Fatal:", "Configuration file not found: \"#{file}\"."
end

#to_jsonObject



60
61
62
# File 'lib/rakali/converter.rb', line 60

def to_json
  content.to_json
end

#to_yamlObject



64
65
66
67
# File 'lib/rakali/converter.rb', line 64

def to_yaml
  yaml = config.to_yaml.gsub(/---\n/, '').split("\n")
  yaml.join("\n                    ")
end