Class: RecipeScrapers::Parsers::Ingredients

Inherits:
Object
  • Object
show all
Defined in:
lib/recipe_scrapers/parsers/ingredients.rb

Overview

The bundled parser of ingredient lines. It reads the amount, the unit and the name with the words of the recipe language. Put it after your own parser to keep it as the fallback.

Examples:

RecipeScrapers::Parsers::Ingredients.call("1 1/2 cups flour", language: "en").to_h
# => { amount: 1.5, unit: "cups", name: "flour" }

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(vocabulary) ⇒ Ingredients

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Ingredients.



59
60
61
62
# File 'lib/recipe_scrapers/parsers/ingredients.rb', line 59

def initialize(vocabulary)
  @vocabulary = vocabulary
  @patterns = build_patterns
end

Instance Attribute Details

#vocabulary ⇒ Vocabulary (readonly)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the words this parser reads.



54
55
56
# File 'lib/recipe_scrapers/parsers/ingredients.rb', line 54

def vocabulary
  @vocabulary
end

Class Method Details

.call(line, language: nil) ⇒ Models::Ingredient



31
32
33
# File 'lib/recipe_scrapers/parsers/ingredients.rb', line 31

def call(line, language: nil)
  for_language(language).call(line)
end

.for_language(language) ⇒ Ingredients

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a parser for the vocabulary of the language, built once per vocabulary.



39
40
41
42
# File 'lib/recipe_scrapers/parsers/ingredients.rb', line 39

def for_language(language)
  names = Vocabulary.names_for(language)
  LOCK.synchronize { instances[names] ||= new(Vocabulary.combine(names)) }
end

Instance Method Details

#call(line) ⇒ Models::Ingredient

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



68
69
70
71
72
73
# File 'lib/recipe_scrapers/parsers/ingredients.rb', line 68

def call(line, **)
  parsed = parse_text(without_parentheses(line.to_s))
  return parsed unless parsed.name.nil? && line.to_s.include?("(")

  parse_text(tidy(line.to_s.gsub(PARENTHESES, " ").delete("()")))
end