Class: Jekyll::RdfaGenerator

Inherits:
Generator
  • Object
show all
Defined in:
lib/jekyll-rdfa.rb

Instance Method Summary collapse

Instance Method Details

#generate(site) ⇒ Object



9
10
11
12
13
14
15
16
17
18
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/jekyll-rdfa.rb', line 9

def generate(site)
  require 'fileutils'
  require 'json'
  require 'json/ld'
  require 'rdf'
  require 'rdf/turtle'
  require 'rdf/rdfa'

  converter = site.getConverterImpl(Jekyll::Converters::Markdown)

  graph = RDF::Graph.new
  site.posts.each do |post|
    html = converter.convert(post.content)

    attribs = {}
    attribs[:vocab] = post.data["vocab"] if post.data.member? "vocab"

    needs_typeof = false
    if post.data.member? "resource"
      attribs[:resource] = post.data["resource"]
      needs_typeof = true
    end
    if post.data.member? "about"
      attribs[:about] = post.data["about"]
      needs_typeof = true
    end
    if post.data.member? "typeof" and needs_typeof
      attribs[:typeof] = post.data["typeof"]
    end

    if post.data.member? "prefix"
      prefixes = post.data["prefix"]
                 .to_a.map { |key, value| "#{key}: #{value}" }
                 .join " "
      attribs[:prefix] = prefixes
    end

    unless attribs.empty?
      markup = attribs
               .to_a
               .map { |key, value| " #{key}='#{value}'"}
               .join ""
      html = "<div#{markup}>#{html}</div>"
    end
    count = 0
    RDF::Reader.for(:rdfa).new(html) do |reader|
      reader.each_statement do |statement|
        graph << statement
        count += 1
      end
    end
  end

  dirname = "_linked-data"
  FileUtils.mkpath(dirname) unless File.exists?(dirname)

  File.open("#{dirname}/posts.ttl", 'w') do |file|
    file.write(graph.to_ttl)
  end
  site.static_files << Jekyll::StaticFile.new(
    site, "_linked-data", "", "posts.ttl"
  )
  File.open("#{dirname}/posts.json", 'w') do |file|
    file.write(graph.dump(:jsonld, standard_prefixes: true))
  end
  site.static_files << Jekyll::StaticFile.new(
    site, "_linked-data", "", "posts.json"
  )
end