Class: Openphar::Parsers::PhIntJsonParser

Inherits:
Object
  • Object
show all
Defined in:
lib/openphar/parsers/phint_json_parser.rb

Overview

Parser for International Pharmacopoeia (Ph.Int.) JSON files

This parser creates Lutaml::Model instances (not hashes) for proper model-driven architecture. All output uses model classes.

Ph.Int. data files are JSON with embedded HTML content: { "id": "6.1.1", "title": "Abacavir sulfate (Abacaviri sulfas)", "data": { "t": "Title", "b": "

HTML body content...

", "c": [] } }

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializePhIntJsonParser

Returns a new instance of PhIntJsonParser.



26
27
28
29
# File 'lib/openphar/parsers/phint_json_parser.rb', line 26

def initialize
  @monographs = []
  @stats = { total: 0, parsed: 0, failed: 0 }
end

Instance Attribute Details

#monographsObject (readonly)

Returns the value of attribute monographs.



24
25
26
# File 'lib/openphar/parsers/phint_json_parser.rb', line 24

def monographs
  @monographs
end

#statsObject (readonly)

Returns the value of attribute stats.



24
25
26
# File 'lib/openphar/parsers/phint_json_parser.rb', line 24

def stats
  @stats
end

Instance Method Details

#parse_directory(directory) ⇒ Array<Monograph>

Parse all Ph.Int. JSON files in a directory

Parameters:

  • directory (String)

    Directory containing JSON files

Returns:

  • (Array<Monograph>)

    Parsed monograph model instances



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/openphar/parsers/phint_json_parser.rb', line 62

def parse_directory(directory)
  json_files = Dir.glob(File.join(directory, "b.*.json"))
  puts "Found #{json_files.count} Ph.Int. JSON files"

  json_files.sort.each do |file|
    puts "Parsing: #{File.basename(file)}"
    parse_file(file)
  end

  @monographs
end

#parse_file(file_path) ⇒ Monograph?

Parse a single Ph.Int. JSON file

Parameters:

  • file_path (String)

    Path to JSON file

Returns:

  • (Monograph, nil)

    Parsed monograph model instance



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/openphar/parsers/phint_json_parser.rb', line 35

def parse_file(file_path)
  @stats[:total] += 1

  begin
    content = File.read(file_path, encoding: "UTF-8")
    data = JSON.parse(content)
    monograph = parse_data(data)
    if monograph
      @monographs << monograph
      @stats[:parsed] += 1
    end
    monograph
  rescue JSON::ParserError => e
    puts "  ERROR: Invalid JSON - #{e.message}"
    @stats[:failed] += 1
    nil
  rescue StandardError => e
    puts "  ERROR: #{e.message}"
    @stats[:failed] += 1
    nil
  end
end