Module: Biodiversity::Parser

Extended by:
FFI::Library
Defined in:
lib/biodiversity/parser.rb

Overview

Parser provides a namespace for functions to parse scientific names.

Constant Summary collapse

POINTER_SIZE =
FFI.type_size(:pointer)

Class Method Summary collapse

Class Method Details

.csv_row(row) ⇒ Object


75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/biodiversity/parser.rb', line 75

def self.csv_row(row)
  {
    id: row[0],
    verbatim: row[1],
    cardinality: row[2],
    canonical: {
      stem: row[3],
      simple: row[4],
      full: row[5]
    },
    authorship: row[6],
    year: row[7],
    quality: row[8]
  }
end

.output(parsed, simple) ⇒ Object


65
66
67
68
69
70
71
72
73
# File 'lib/biodiversity/parser.rb', line 65

def self.output(parsed, simple)
  if simple
    csv = CSV.new(parsed)
    row = csv.readlines[0]
    csv_row(row)
  else
    JSON.parse(parsed, symbolize_names: true)
  end
end

.parse(name, simple: false) ⇒ Object


36
37
38
39
40
41
42
43
# File 'lib/biodiversity/parser.rb', line 36

def self.parse(name, simple: false)
  format = simple ? 'csv' : 'compact'
  with_details = simple ? 0 : 1

  parsed, ptr = parse_go(name, format, with_details)
  free_mem(ptr)
  output(parsed, simple)
end

.parse_ary(ary, simple: false) ⇒ Object


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

def self.parse_ary(ary, simple: false)
  format = simple ? 'csv' : 'compact'
  with_details = simple ? 0 : 1

  in_ptr = FFI::MemoryPointer.new(:pointer, ary.length)
  in_ptr.write_array_of_pointer(
    ary.map { |s| FFI::MemoryPointer.from_string(s) }
  )

  parsed, ptr = parse_ary_go(in_ptr, ary.length, format, with_details)
  free_mem(ptr)
  if simple
    CSV.new(parsed).map do |row|
      csv_row(row)
    end
  else
    JSON.parse(parsed, symbolize_names: true)
  end
end