Class: RecipeScrapers::Sources::JsonLd

Inherits:
Object
  • Object
show all
Defined in:
lib/recipe_scrapers/sources/json_ld.rb

Constant Summary collapse

SELECTOR =
'script[type="application/ld+json"]'
ESCAPED_CONTROL =
{ "\b" => "\\b", "\f" => "\\f", "\n" => "\\n", "\r" => "\\r", "\t" => "\\t" }.freeze
PARSE_OPTIONS =
{ allow_duplicate_key: true }.freeze
WRAPPER =
%r{\A\s*(?://\s*)?(?:<!\[CDATA\[)?|(?://\s*)?(?:\]\]>)?[\s;]*\z}

Instance Method Summary collapse

Constructor Details

#initialize(document) ⇒ JsonLd

Returns a new instance of JsonLd.



13
14
15
16
# File 'lib/recipe_scrapers/sources/json_ld.rb', line 13

def initialize(document)
  @nodes = flatten(document.css(SELECTOR).flat_map { |tag| parse(tag.text) })
  @by_id = @nodes.select { |node| node["@id"] }.to_h { |node| [node["@id"], node] }
end

Instance Method Details

#person(id) ⇒ Object



22
23
24
# File 'lib/recipe_scrapers/sources/json_ld.rb', line 22

def person(id)
  entity(id, "Person")
end

#rating(id) ⇒ Object



26
27
28
# File 'lib/recipe_scrapers/sources/json_ld.rb', line 26

def rating(id)
  entity(id, "AggregateRating")
end

#recipe ⇒ Object



18
19
20
# File 'lib/recipe_scrapers/sources/json_ld.rb', line 18

def recipe
  @recipe ||= @nodes.find { |node| type?(node, "Recipe") } || main_entity_recipe
end

#website_name ⇒ Object



30
31
32
33
# File 'lib/recipe_scrapers/sources/json_ld.rb', line 30

def website_name
  site = @nodes.find { |node| type?(node, "WebSite") }
  site && Text.normalize(site["name"])
end