A complete example

This complete example is an extensive showcase of enolib, demonstrating that parsing eno, although more verbose than other formats, has much to offer:

  • Decoupling of the field names the user prefers/understands from the ones a developer wants to use in the code
  • Out of the box localized parser and validation errors that can be directly displayed to a non-technical user
  • Out of the box validation of predefined high-level types (comma_separated, datetime, email, slug and url here)
  • Native API integration of completely custom types (markdown here)
  • Guaranteed data integrity, including prevention of unhandled extra fields
require 'enolib'
require 'enolib/locales'
require 'enotype'
require 'kramdown'

loaders = Enotype.procs(:comma_separated, :datetime, :email, :slug, :url)

loaders[:markdown] = proc { |value| Kramdown::Document.new(value).to_html }

# Makes the .required_xxx_value and .optional_xxx_value methods available below
Enolib.register(loaders)

def read_post(filename)
  input = File.read(filename)
  document = Enolib.parse(input, locale: Enolib::Locales::De, source: filename)
  
  author = document.fieldset('Verfasser')
  post = {
    author: {
      name: author.entry('Name').required_string_value,
      email: author.entry('Email').optional_email_value,
      website: author.entry('Website').optional_url_value
    },
    title: document.field('Titel').required_string_value,
    date: document.field('Veröffentlicht').required_datetime_value,
    permalink: document.field('Permalink').required_slug_value,
    abstract: document.field('Abstract').optional_markdown_value,
    body: document.field('Text').required_markdown_value,
    tags: document.field('Tags').required_comma_separated_values
  }

  # Throws an error when there are unhandled, mis-typed or unneeded fields in the document
  document.assert_all_touched
  
  post
end

read_post('my_post.eno')

Next page: AST inspection