CooklangParser (cooklang_parser v0.4.2)

Copy Markdown View Source

Implementation of Cooklang.

Differences

These are the differences compared to the Cooklang canonical tests.

  • The front matter is parsed as strict YAML, so keys need key: value syntax. key :value is an error.
  • Leading zeros in numbers are ignored, as in maths. {01/2} is parsed as 0.5 rather than kept as the text "01/2".

Summary

Types

The amount of something without a unit.

Functions

Parses a Cooklang recipe.

Types

quantity()

@type quantity() :: integer() | float() | String.t()

The amount of something without a unit.

String.t() is used for anything that cannot be parsed as either int or float.

Functions

parse(source, opts \\ [])

@spec parse(String.t(), keyword()) ::
  {:ok, CooklangParser.Recipe.t()} | {:error, String.t()}

Parses a Cooklang recipe.

Examples

iex> CooklangParser.parse("Add @salt and @ground black pepper{1/2%tsp}.")
{:ok,
 %CooklangParser.Recipe{
   sections: [
     %CooklangParser.Section{
       content: [
         %CooklangParser.Step{
           fragments: [
             "Add ",
             %CooklangParser.Ingredient{name: "salt"},
             " and ",
             %CooklangParser.Ingredient{name: "ground black pepper", quantity: 0.5, unit: "tsp"},
             "."
           ]
         }
       ]
     }
   ]
 }}

iex> {:ok, recipe} =
...>   CooklangParser.parse("Fry the @onion{1}(diced) in a #pan{} for ~{5%minutes}.")
iex> [%CooklangParser.Section{content: [step]}] = recipe.sections
iex> step.fragments
[
  "Fry the ",
  %CooklangParser.Ingredient{name: "onion", quantity: 1, preparation: "diced"},
  " in a ",
  %CooklangParser.Cookware{name: "pan"},
  " for ",
  %CooklangParser.Timer{quantity: 5, unit: "minutes"},
  "."
]

iex> {:ok, recipe} =
...>   CooklangParser.parse("---\nservings: 2\n---\n= Sauce\nSimmer.\n\n= Pasta\nBoil.")
iex> recipe.metadata
%{"servings" => 2}
iex> recipe.sections
[
  %CooklangParser.Section{name: "Sauce", content: [%CooklangParser.Step{fragments: ["Simmer."]}]},
  %CooklangParser.Section{name: "Pasta", content: [%CooklangParser.Step{fragments: ["Boil."]}]}
]

iex> {:ok, recipe} = CooklangParser.parse("Simmer. -- stir often", comments: true)
iex> [%CooklangParser.Section{content: [step]}] = recipe.sections
iex> step.fragments
["Simmer. ", %CooklangParser.Comment{text: "stir often"}]

iex> CooklangParser.parse("---\ntitle: [unclosed\n---")
{:error, "invalid YAML front matter: Unfinished flow collection"}

Options