Belletrist

Belletrist is a collection of Ruby DSLs for generation of different data file types. Currently, HTML and JSON are supported but that will grow as my needs do, or if other people want or contribute any other DSLs.

It is important to note that Belletrist has a focus on performance, not correctness. Belletrist ascribes to the rule of "what goes in, must come out", and as such Belletrist DSLs must output well-formed documents so long as the developer provides Belletrist valid input. If that contract is broken the result is undefined.

Requirements of a Belletrist DSL

  • All input must be sanitized, and sanitization is not optional.
  • Correctness of input is not a concern of the DSL, but of the developer.

Using

Below are some examples of how you can use the different DSLs provided by Belletrist.

HTML

Generation of a simple HTML document:

require 'belletrist'

da_rulez = ['Be hip!', 'Be cool!', 'Don\'t be square!']

# HTML5 is the default DOCTYPE.
# HTML5 DOCTYPE:  Belletrist::HTML::Document.new(Belletrist::HTML::V5)
# HTML4 DOCTYPE:  Belletrist::HTML::Document.new(Belletrist::HTML::V4)
document = Belletrist::HTML::Document.new
document.head do
  title 'Some Kind of Web Page'
  meta name: 'description', content: 'Example'
end
document.body do
  h1 'My Very Cool Website'
  p 'Please follow the rules:'
  ol.map da_rulez do |rule|
    li rule
  end
end

# String conversation is serialization of the input.
print document.to_s

Subclassing Belletrist::HTML:Element to create components:

require 'belletrist'

class SubElement < Belletrist::HTML::Element
  attr_reader :value

  def initialize
    @value = 'hello'

    super('div')
  end

  def component(model)
    p 'I am rendered from a custom component!'
    p "From the model: #{model.value}"
  end
end

document = Belletrist::HTML::Document.new
document.body do 
  h1 'Look at my cool new element!'
  with SubElement.new
end

JSON

Using the DSL directly:

require 'belletrist'

dict = {a_string: 'Hello, world!', a_number: 1}
list = [1, 1, 2, 3, 5, 8]

obj = Belletrist::JSON::Object.new
obj.title 'An example JSON object'
obj.empty nil

obj.sub do 
  object_key dict
  array_key list
end

obj.double_fib.map list do |item|
  push item * 2
end

Sending a Hash to a new JSON object:

require 'belletrist'

fib = [1, 1, 2, 3, 5, 8]

dict = {
  title: 'An example JSON object',
  empty: nil,
  sub: {
    object_key: {a_string: 'Hello, world!', a_number: 1},
    array_key: fib
  },
  double_map: fib.map { |item| item * item }
}

obj = Belletrist::JSON::Object.new(dict)