Noelia  Douglas

Noelia Douglas

1657144800

Deno Rollup: Next-generation ES Module Bundler Ported for Deno

deno-rollup

Next-generation ES module bundler for Deno ported from Rollup


Overview

Deprecation Notice: Deno will soon support a --compat flag that will allow for the running of Node modules in Deno through the Node compatibility layer.

This renders the core and CLI parts of this module obsolete, it is to be if the rollup-plugin-deno-resolver module will continue to add value as a stand-alone plugin to use with Rollup in Deno.

Future efforts will be spent bolstering the Node compatibility layer instead of keeping this module aligned with Rollup for Node. PRs welcome for bugfixes.

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.

This library extends Rollup so that it can be used in Deno - supporting core Deno features out-of-the-box such as URL imports, Typescript and JSX.

Installation

deno-rollup can be used either through a command line interface (CLI) with an optional configuration file, or else through its JavaScript API.

CLI

To install the CLI run:

deno install -f -q --allow-read --allow-write --allow-net --allow-env --unstable https://deno.land/x/drollup@2.58.0+0.20.0/rollup.ts

And follow any suggestions to update your PATH environment variable.

You can then use the CLI to bundle your modules:

# compile to an ESM
rollup main.js --format es --name "myBundle" --file bundle.js

You can also rebuild the bundle when it's source or config files change on disk using the --watch flag:

# recompile based on `rollup.config.ts` when source files change
rollup -c --watch

JavaScript API

You can import deno-rollup straight into your project to bundle your modules:

import { rollup } from "https://deno.land/x/drollup@2.58.0+0.20.0/mod.ts";

const options = {
  input: "./mod.ts",
  output: {
    dir: "./dist",
    format: "es" as const,
    sourcemap: true,
  },
};

const bundle = await rollup(options);
await bundle.write(options.output);
await bundle.close();

Or using the watch API:

import { watch } from "https://deno.land/x/drollup@2.58.0+0.20.0/mod.ts";

const options = {
  input: "./src/mod.ts",
  output: {
    dir: "./dist",
    format: "es" as const,
    sourcemap: true,
  },
  watch: {
    include: ["src/**"],
  },
};

const watcher = await watch(options);

watcher.on("event", (event) => {
  // event.code can be one of:
  //   START        — the watcher is (re)starting
  //   BUNDLE_START — building an individual bundle
  //                  * event.input will be the input options object if present
  //                  * event.outputFiles contains an array of the "file" or
  //                    "dir" option values of the generated outputs
  //   BUNDLE_END   — finished building a bundle
  //                  * event.input will be the input options object if present
  //                  * event.outputFiles contains an array of the "file" or
  //                    "dir" option values of the generated outputs
  //                  * event.duration is the build duration in milliseconds
  //                  * event.result contains the bundle object that can be
  //                    used to generate additional outputs by calling
  //                    bundle.generate or bundle.write. This is especially
  //                    important when the watch.skipWrite option is used.
  //                  You should call "event.result.close()" once you are done
  //                  generating outputs, or if you do not generate outputs.
  //                  This will allow plugins to clean up resources via the
  //                  "closeBundle" hook.
  //   END          — finished building all bundles
  //   ERROR        — encountered an error while bundling
  //                  * event.error contains the error that was thrown
});

// This will make sure that bundles are properly closed after each run
watcher.on("event", (event) => {
  if (event.code === "BUNDLE_END") {
    event.result.close();
  }
});

// stop watching
watcher.close();

Documentation

Please refer to the official Rollup Documentation.

Known deviations from Rollup:

  • Deno code support: TypeScript and URL imports supported out-of-the-box.
  • CLI does not currently support some nested "dot" flags, namely: --no-treeshake.*, --watch.* and --no-watch.*.
  • CLI does not currently support the --plugin flag.
  • Some warnings have yet to be implemented.

Where further deviations / incompatibility are found, please raise an issue.

Plugins

A suite of deno-rollup compatible plugins are available in the plugins directory.

Examples

To run the examples you have a couple of options:

Direct from repository

Run the deno-rollup helloDeno example directly from the repository:

deno run --allow-read="./" --allow-write="./dist" --allow-net="deno.land" --allow-env --unstable https://deno.land/x/drollup@2.58.0+0.20.0/examples/helloDeno/rollup.build.ts

This will create a ./dist directory with the bundled files in your current working directory.

Clone

Clone the deno-rollup repo locally:

git clone git://github.com/cmorten/deno-rollup.git --depth 1
cd deno-rollup

Then enter the desired examples directory and run the build script:

cd examples/helloDeno
deno run --allow-read="./" --allow-write="./dist" --allow-net="deno.land" --allow-env --unstable ./rollup.build.ts

This will create a ./dist directory with the bundled files in the current directory.

Further details are available in each example directory.

Contributing

Contributing guide


License

deno-rollup is licensed under the MIT License.

The license for the Rollup library, which this library adapts, is available at ROLLUP_LICENSE.

Derived works other than from Rollup are attributed with their license in source.


Author: cmorten
Source code: https://github.com/cmorten/deno-rollup/
License: MIT, MIT licenses found

#typescript #javascript #Rollup #deno 

What is GEEK

Buddha Community

Deno Rollup: Next-generation ES Module Bundler Ported for Deno
Noelia  Douglas

Noelia Douglas

1657144800

Deno Rollup: Next-generation ES Module Bundler Ported for Deno

deno-rollup

Next-generation ES module bundler for Deno ported from Rollup


Overview

Deprecation Notice: Deno will soon support a --compat flag that will allow for the running of Node modules in Deno through the Node compatibility layer.

This renders the core and CLI parts of this module obsolete, it is to be if the rollup-plugin-deno-resolver module will continue to add value as a stand-alone plugin to use with Rollup in Deno.

Future efforts will be spent bolstering the Node compatibility layer instead of keeping this module aligned with Rollup for Node. PRs welcome for bugfixes.

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.

This library extends Rollup so that it can be used in Deno - supporting core Deno features out-of-the-box such as URL imports, Typescript and JSX.

Installation

deno-rollup can be used either through a command line interface (CLI) with an optional configuration file, or else through its JavaScript API.

CLI

To install the CLI run:

deno install -f -q --allow-read --allow-write --allow-net --allow-env --unstable https://deno.land/x/drollup@2.58.0+0.20.0/rollup.ts

And follow any suggestions to update your PATH environment variable.

You can then use the CLI to bundle your modules:

# compile to an ESM
rollup main.js --format es --name "myBundle" --file bundle.js

You can also rebuild the bundle when it's source or config files change on disk using the --watch flag:

# recompile based on `rollup.config.ts` when source files change
rollup -c --watch

JavaScript API

You can import deno-rollup straight into your project to bundle your modules:

import { rollup } from "https://deno.land/x/drollup@2.58.0+0.20.0/mod.ts";

const options = {
  input: "./mod.ts",
  output: {
    dir: "./dist",
    format: "es" as const,
    sourcemap: true,
  },
};

const bundle = await rollup(options);
await bundle.write(options.output);
await bundle.close();

Or using the watch API:

import { watch } from "https://deno.land/x/drollup@2.58.0+0.20.0/mod.ts";

const options = {
  input: "./src/mod.ts",
  output: {
    dir: "./dist",
    format: "es" as const,
    sourcemap: true,
  },
  watch: {
    include: ["src/**"],
  },
};

const watcher = await watch(options);

watcher.on("event", (event) => {
  // event.code can be one of:
  //   START        — the watcher is (re)starting
  //   BUNDLE_START — building an individual bundle
  //                  * event.input will be the input options object if present
  //                  * event.outputFiles contains an array of the "file" or
  //                    "dir" option values of the generated outputs
  //   BUNDLE_END   — finished building a bundle
  //                  * event.input will be the input options object if present
  //                  * event.outputFiles contains an array of the "file" or
  //                    "dir" option values of the generated outputs
  //                  * event.duration is the build duration in milliseconds
  //                  * event.result contains the bundle object that can be
  //                    used to generate additional outputs by calling
  //                    bundle.generate or bundle.write. This is especially
  //                    important when the watch.skipWrite option is used.
  //                  You should call "event.result.close()" once you are done
  //                  generating outputs, or if you do not generate outputs.
  //                  This will allow plugins to clean up resources via the
  //                  "closeBundle" hook.
  //   END          — finished building all bundles
  //   ERROR        — encountered an error while bundling
  //                  * event.error contains the error that was thrown
});

// This will make sure that bundles are properly closed after each run
watcher.on("event", (event) => {
  if (event.code === "BUNDLE_END") {
    event.result.close();
  }
});

// stop watching
watcher.close();

Documentation

Please refer to the official Rollup Documentation.

Known deviations from Rollup:

  • Deno code support: TypeScript and URL imports supported out-of-the-box.
  • CLI does not currently support some nested "dot" flags, namely: --no-treeshake.*, --watch.* and --no-watch.*.
  • CLI does not currently support the --plugin flag.
  • Some warnings have yet to be implemented.

Where further deviations / incompatibility are found, please raise an issue.

Plugins

A suite of deno-rollup compatible plugins are available in the plugins directory.

Examples

To run the examples you have a couple of options:

Direct from repository

Run the deno-rollup helloDeno example directly from the repository:

deno run --allow-read="./" --allow-write="./dist" --allow-net="deno.land" --allow-env --unstable https://deno.land/x/drollup@2.58.0+0.20.0/examples/helloDeno/rollup.build.ts

This will create a ./dist directory with the bundled files in your current working directory.

Clone

Clone the deno-rollup repo locally:

git clone git://github.com/cmorten/deno-rollup.git --depth 1
cd deno-rollup

Then enter the desired examples directory and run the build script:

cd examples/helloDeno
deno run --allow-read="./" --allow-write="./dist" --allow-net="deno.land" --allow-env --unstable ./rollup.build.ts

This will create a ./dist directory with the bundled files in the current directory.

Further details are available in each example directory.

Contributing

Contributing guide


License

deno-rollup is licensed under the MIT License.

The license for the Rollup library, which this library adapts, is available at ROLLUP_LICENSE.

Derived works other than from Rollup are attributed with their license in source.


Author: cmorten
Source code: https://github.com/cmorten/deno-rollup/
License: MIT, MIT licenses found

#typescript #javascript #Rollup #deno 

Next-generation ES Module Bundler Ported for Deno

deno-rollup

Next-generation ES module bundler for Deno ported from Rollup.

Overview

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application.

This library extends Rollup so that it can be used within Deno scripts to bundle Deno code.

Getting Started

import { rollup } from "https://deno.land/x/drollup@2.36.1+0.1.0/mod.ts";

const options = {
  input: "./mod.ts",
  output: {
    dir: "./dist",
    format: "es" as "es",
    sourcemap: true,
  },
};

const bundle = await rollup(options);
await bundle.write(options.output);

Installation

This is a Deno module available to import direct from this repo and via the Deno Registry.

Before importing, download and install Deno.

You can then import deno-rollup straight into your project:

import { rollup } from "https://deno.land/x/drollup@2.36.1+0.1.0/mod.ts";

Documentation

Please refer to the official Rollup Documentation. Specifically, please refer to the JavaScript API which this library extends to provide Deno compatibility.

Note: currently this library only supports the rollup method, it does not yet have support for the watch method.

Example

To run the example:

  1. Clone the deno-rollup repo locally:

    git clone git://github.com/cmorten/deno-rollup.git --depth 1
    cd deno-rollup
    
  2. Then enter the example directory and run the build script:

    cd example
    deno run --allow-read="./" --allow-write="./dist" --allow-net="deno.land" --unstable ./rollup.build.ts
    
  3. Further details are available in the example README.

Contributing

Contributing guide

Download Details:

Author: cmorten

Source Code: https://github.com/cmorten/deno-rollup

#deno #node #nodejs #javascript

amelia jones

1591340335

How To Take Help Of Referencing Generator

APA Referencing Generator

Many students use APA style as the key citation style in their assignment in university or college. Although, many people find it quite difficult to write the reference of the source. You ought to miss the names and dates of authors. Hence, APA referencing generator is important for reducing the burden of students. They can now feel quite easy to do the assignments on time.

The functioning of APA referencing generator

If you are struggling hard to write the APA referencing then you can take the help of APA referencing generator. It will create an excellent list. You are required to enter the information about the source. Just ensure that the text is credible and original. If you will copy references then it is a copyright violation.

You can use a referencing generator in just a click. It will generate the right references for all the sources. You are required to organize in alphabetical order. The generator will make sure that you will get good grades.

How to use APA referencing generator?

Select what is required to be cited such as journal, book, film, and others. You can choose the type of required citations list and enter all the required fields. The fields are dates, author name, title, editor name, and editions, name of publishers, chapter number, page numbers, and title of journals. You can click for reference to be generated and you will get the desired result.

Chicago Referencing Generator

Do you require the citation style? You can rely on Chicago Referencing Generator and will ensure that you will get the right citation in just a click. The generator is created to provide solutions to students to cite their research paper in Chicago style. It has proved to be the quickest and best citation generator on the market. The generator helps to sort the homework issues in few seconds. It also saves a lot of time and energy.

This tool helps researchers, professional writers, and students to manage and generate text citation essays. It will help to write Chicago style in a fast and easy way. It also provides details and directions for formatting and cites resources.

So, you must stop wasting the time and can go for Chicago Referencing Generator or APA referencing generator. These citation generators will help to solve the problem of citation issues. You can easily create citations by using endnotes and footnotes.

So, you can generate bibliographies, references, in-text citations, and title pages. These are fully automatic referencing style. You are just required to enter certain details about the citation and you will get the citation in the proper and required format.

So, if you are feeling any problem in doing assignment then you can take the help of assignment help.
If you require help for Assignment then livewebtutors is the right place for you. If you see our prices, you will observe that they are actually very affordable. Also, you can always expect a discount. Our team is capable and versatile enough to offer you exactly what you need, the best services for the prices you can afford.

read more:- Are you struggling to write a bibliography? Use Harvard referencing generator

#apa referencing generator #harvard referencing generator #chicago referencing generator #mla referencing generator #deakin referencing generator #oxford referencing generator

Rollup: Next-generation ES Module Bundler

Rollup

Overview

Rollup is a module bundler for JavaScript which compiles small pieces of code into something larger and more complex, such as a library or application. It uses the standardized ES module format for code, instead of previous idiosyncratic solutions such as CommonJS and AMD. ES modules let you freely and seamlessly combine the most useful individual functions from your favorite libraries. Rollup can optimize ES modules for faster native loading in modern browsers, or output a legacy module format allowing ES module workflows today.

Quick Start Guide

Install with npm install --global rollup. Rollup can be used either through a command line interface with an optional configuration file, or else through its JavaScript API. Run rollup --help to see the available options and parameters. The starter project templates, rollup-starter-lib and rollup-starter-app, demonstrate common configuration options, and more detailed instructions are available throughout the user guide.

Commands

These commands assume the entry point to your application is named main.js, and that you'd like all imports compiled into a single file named bundle.js.

For browsers:

# compile to a <script> containing a self-executing function
rollup main.js --format iife --name "myBundle" --file bundle.js

For Node.js:

# compile to a CommonJS module
rollup main.js --format cjs --file bundle.js

For both browsers and Node.js:

# UMD format requires a bundle name
rollup main.js --format umd --name "myBundle" --file bundle.js

Why

Developing software is usually easier if you break your project into smaller separate pieces, since that often removes unexpected interactions and dramatically reduces the complexity of the problems you'll need to solve, and simply writing smaller projects in the first place isn't necessarily the answer. Unfortunately, JavaScript has not historically included this capability as a core feature in the language.

This finally changed with ES modules support in JavaScript, which provides a syntax for importing and exporting functions and data so they can be shared between separate scripts. Most browsers and Node.js support ES modules. However, Node.js releases before 12.17 support ES modules only behind the --experimental-modules flag, and older browsers like Internet Explorer do not support ES modules at all. Rollup allows you to write your code using ES modules, and run your application even in environments that do not support ES modules natively. For environments that support them, Rollup can output optimized ES modules; for environments that don't, Rollup can compile your code to other formats such as CommonJS modules, AMD modules, and IIFE-style scripts. This means that you get to write future-proof code, and you also get the tremendous benefits of...

Tree Shaking

In addition to enabling the use of ES modules, Rollup also statically analyzes and optimizes the code you are importing, and will exclude anything that isn't actually used. This allows you to build on top of existing tools and modules without adding extra dependencies or bloating the size of your project.

For example, with CommonJS, the entire tool or library must be imported.

// import the entire utils object with CommonJS
var utils = require('utils');
var query = 'Rollup';
// use the ajax method of the utils object
utils.ajax('https://api.example.com?search=' + query).then(handleResponse);

But with ES modules, instead of importing the whole utils object, we can just import the one ajax function we need:

// import the ajax function with an ES import statement
import { ajax } from 'utils';
var query = 'Rollup';
// call the ajax function
ajax('https://api.example.com?search=' + query).then(handleResponse);

Because Rollup includes the bare minimum, it results in lighter, faster, and less complicated libraries and applications. Since this approach is based on explicit import and export statements, it is vastly more effective than simply running an automated minifier to detect unused variables in the compiled output code.

Compatibility

Importing CommonJS

Rollup can import existing CommonJS modules through a plugin.

Publishing ES Modules

To make sure your ES modules are immediately usable by tools that work with CommonJS such as Node.js and webpack, you can use Rollup to compile to UMD or CommonJS format, and then point to that compiled version with the main property in your package.json file. If your package.json file also has a module field, ES-module-aware tools like Rollup and webpack will import the ES module version directly.

Author: Rollup
Source Code: https://github.com/rollup/rollup 
License: View license

#node #rollup #javascript #typescript 

Royce  Reinger

Royce Reinger

1658977500

A Ruby Library for Generating Text with Recursive Template Grammars

Calyx

Calyx provides a simple API for generating text with declarative recursive grammars.

Install

Command Line

gem install calyx

Gemfile

gem 'calyx'

Examples

The best way to get started quickly is to install the gem and run the examples locally.

Any Gradient

Requires Roda and Rack to be available.

gem install roda

Demonstrates how to use Calyx to construct SVG graphics. Any Gradient generates a rectangle with a linear gradient of random colours.

Run as a web server and preview the output in a browser (http://localhost:9292):

ruby examples/any_gradient.rb

Or generate SVG files via a command line pipe:

ruby examples/any_gradient > gradient1.xml

Tiny Woodland Bot

Requires the Twitter client gem and API access configured for a specific Twitter handle.

gem install twitter

Demonstrates how to use Calyx to make a minimal Twitter bot that periodically posts unique tweets. See @tiny_woodland on Twitter and the writeup here.

TWITTER_CONSUMER_KEY=XXX-XXX
TWITTER_CONSUMER_SECRET=XXX-XXX
TWITTER_ACCESS_TOKEN=XXX-XXX
TWITTER_CONSUMER_SECRET=XXX-XXX
ruby examples/tiny_woodland_bot.rb

Faker

Faker is a popular library for generating fake names and associated sample data like internet addresses, company names and locations.

This example demonstrates how to use Calyx to reproduce the same functionality using custom lists defined in a YAML configuration file.

ruby examples/faker.rb

Usage

Require the library and inherit from Calyx::Grammar to construct a set of rules to generate a text.

require 'calyx'

class HelloWorld < Calyx::Grammar
  start 'Hello world.'
end

To generate the text itself, initialize the object and call the generate method.

hello = HelloWorld.new
hello.generate
# > "Hello world."

Obviously, this hardcoded sentence isn’t very interesting by itself. Possible variations can be added to the text by adding additional rules which provide a named set of text strings. The rule delimiter syntax ({}) can be used to substitute the generated content of other rules.

class HelloWorld < Calyx::Grammar
  start '{greeting} world.'
  greeting 'Hello', 'Hi', 'Hey', 'Yo'
end

Each time #generate runs, it evaluates the tree and randomly selects variations of rules to construct a resulting string.

hello = HelloWorld.new

hello.generate
# > "Hi world."

hello.generate
# > "Hello world."

hello.generate
# > "Yo world."

By convention, the start rule specifies the default starting point for generating the final text. You can start from any other named rule by passing it explicitly to the generate method.

class HelloWorld < Calyx::Grammar
  hello 'Hello world.'
end

hello = HelloWorld.new
hello.generate(:hello)

Block Constructors

As an alternative to subclassing, you can also construct rules unique to an instance by passing a block when initializing the class:

hello = Calyx::Grammar.new do
  start '{greeting} world.'
  greeting 'Hello', 'Hi', 'Hey', 'Yo'
end

hello.generate

Template Expressions

Basic rule substitution uses single curly brackets as delimiters for template expressions:

fruit = Calyx::Grammar.new do
  start '{colour} {fruit}'
  colour 'red', 'green', 'yellow'
  fruit 'apple', 'pear', 'tomato'
end

6.times { fruit.generate }
# => "yellow pear"
# => "red apple"
# => "green tomato"
# => "red pear"
# => "yellow tomato"
# => "green apple"

Nesting and Substitution

Rules are recursive. They can be arbitrarily nested and connected to generate larger and more complex texts.

class HelloWorld < Calyx::Grammar
  start '{greeting} {world_phrase}.'
  greeting 'Hello', 'Hi', 'Hey', 'Yo'
  world_phrase '{happy_adj} world', '{sad_adj} world', 'world'
  happy_adj 'wonderful', 'amazing', 'bright', 'beautiful'
  sad_adj 'cruel', 'miserable'
end

Nesting and hierarchy can be manipulated to balance consistency with novelty. The exact same word atoms can be combined in a variety of ways to produce strikingly different resulting texts.

module HelloWorld
  class Sentiment < Calyx::Grammar
    start '{happy_phrase}', '{sad_phrase}'
    happy_phrase '{happy_greeting} {happy_adj} world.'
    happy_greeting 'Hello', 'Hi', 'Hey', 'Yo'
    happy_adj 'wonderful', 'amazing', 'bright', 'beautiful'
    sad_phrase '{sad_greeting} {sad_adj} world.'
    sad_greeting 'Goodbye', 'So long', 'Farewell'
    sad_adj 'cruel', 'miserable'
  end

  class Mixed < Calyx::Grammar
    start '{greeting} {adj} world.'
    greeting 'Hello', 'Hi', 'Hey', 'Yo', 'Goodbye', 'So long', 'Farewell'
    adj 'wonderful', 'amazing', 'bright', 'beautiful', 'cruel', 'miserable'
  end
end

Random Sampling

By default, the outcomes of generated rules are selected with Ruby’s built-in pseudorandom number generator (as seen in methods like Kernel.rand and Array.sample). To seed the random number generator, pass in an integer seed value as the first argument to the constructor:

grammar = Calyx::Grammar.new(seed: 12345) do
  # rules...
end

Alternatively, you can pass a preconfigured instance of Ruby’s stdlib Random class:

random = Random.new(12345)

grammar = Calyx::Grammar.new(rng: random) do
  # rules...
end

When a random seed isn’t supplied, Time.new.to_i is used as the default seed, which makes each run of the generator relatively unique.

Weighted Choices

Choices can be weighted so that some rules have a greater probability of expanding than others.

Weights are defined by passing a hash instead of a list of rules where the keys are strings or symbols representing the grammar rules and the values are weights.

Weights can be represented as floats, integers or ranges.

  • Floats must be in the interval 0..1 and the given weights for a production must sum to 1.
  • Ranges must be contiguous and cover the entire interval from 1 to the maximum value of the largest range.
  • Integers (Fixnums) will produce a distribution based on the sum of all given numbers, with each number being a fraction of that sum.

The following definitions produce an equivalent weighting of choices:

Calyx::Grammar.new do
  start 'heads' => 1, 'tails' => 1
end

Calyx::Grammar.new do
  start 'heads' => 0.5, 'tails' => 0.5
end

Calyx::Grammar.new do
  start 'heads' => 1..5, 'tails' => 6..10
end

Calyx::Grammar.new do
  start 'heads' => 50, 'tails' => 50
end

There’s a lot of interesting things you can do with this. For example, you can model the triangular distribution produced by rolling 2d6:

Calyx::Grammar.new do
  start(
    '2' => 1,
    '3' => 2,
    '4' => 3,
    '5' => 4,
    '6' => 5,
    '7' => 6,
    '8' => 5,
    '9' => 4,
    '10' => 3,
    '11' => 2,
    '12' => 1
  )
end

Or reproduce Gary Gygax’s famous generation table from the original Dungeon Master’s Guide (page 171):

Calyx::Grammar.new do
  start(
    :empty => 0.6,
    :monster => 0.1,
    :monster_treasure => 0.15,
    :special => 0.05,
    :trick_trap => 0.05,
    :treasure => 0.05
  )
  empty 'Empty'
  monster 'Monster Only'
  monster_treasure 'Monster and Treasure'
  special 'Special'
  trick_trap 'Trick/Trap.'
  treasure 'Treasure'
end

String Modifiers

Dot-notation is supported in template expressions, allowing you to call any available method on the String object returned from a rule. Formatting methods can be chained arbitrarily and will execute in the same way as they would in native Ruby code.

greeting = Calyx::Grammar.new do
  start '{hello.capitalize} there.', 'Why, {hello} there.'
  hello 'hello', 'hi'
end

4.times { greeting.generate }
# => "Hello there."
# => "Hi there."
# => "Why, hello there."
# => "Why, hi there."

You can also extend the grammar with custom modifiers that provide useful formatting functions.

Filters

Filters accept an input string and return the transformed output:

greeting = Calyx::Grammar.new do
  filter :shoutycaps do |input|
    input.upcase
  end

  start '{hello.shoutycaps} there.', 'Why, {hello.shoutycaps} there.'
  hello 'hello', 'hi'
end

4.times { greeting.generate }
# => "HELLO there."
# => "HI there."
# => "Why, HELLO there."
# => "Why, HI there."

Mappings

The mapping shortcut allows you to specify a map of regex patterns pointing to their resulting substitution strings:

green_bottle = Calyx::Grammar.new do
  mapping :pluralize, /(.+)/ => '\\1s'
  start 'One green {bottle}.', 'Two green {bottle.pluralize}.'
  bottle 'bottle'
end

2.times { green_bottle.generate }
# => "One green bottle."
# => "Two green bottles."

Modifier Mixins

In order to use more intricate rewriting and formatting methods in a modifier chain, you can add methods to a module and embed it in a grammar using the modifier classmethod.

Modifier methods accept a single argument representing the input string from the previous step in the expression chain and must return a string, representing the modified output.

module FullStop
  def full_stop(input)
    input << '.'
  end
end

hello = Calyx::Grammar.new do
  modifier FullStop
  start '{hello.capitalize.full_stop}'
  hello 'hello'
end

hello.generate
# => "Hello."

To share custom modifiers across multiple grammars, you can include the module in Calyx::Modifiers. This will make the methods available to all subsequent instances:

module FullStop
  def full_stop(input)
    input << '.'
  end
end

class Calyx::Modifiers
  include FullStop
end

Monkeypatching String

Alternatively, you can combine methods from existing Gems that monkeypatch String:

require 'indefinite_article'

module FullStop
  def full_stop
    self << '.'
  end
end

class String
  include FullStop
end

noun_articles = Calyx::Grammar.new do
  start '{fruit.with_indefinite_article.capitalize.full_stop}'
  fruit 'apple', 'orange', 'banana', 'pear'
end

4.times { noun_articles.generate }
# => "An apple."
# => "An orange."
# => "A banana."
# => "A pear."

Memoized Rules

Rule expansions can be ‘memoized’ so that multiple references to the same rule return the same value. This is useful for picking a noun from a list and reusing it in multiple places within a text.

The @ sigil is used to mark memoized rules. This evaluates the rule and stores it in memory the first time it’s referenced. All subsequent references to the memoized rule use the same stored value.

# Without memoization
grammar = Calyx::Grammar.new do
  start '{name} <{name.downcase}>'
  name 'Daenerys', 'Tyrion', 'Jon'
end

3.times { grammar.generate }
# => Daenerys <jon>
# => Tyrion <daenerys>
# => Jon <tyrion>

# With memoization
grammar = Calyx::Grammar.new do
  start '{@name} <{@name.downcase}>'
  name 'Daenerys', 'Tyrion', 'Jon'
end

3.times { grammar.generate }
# => Tyrion <tyrion>
# => Daenerys <daenerys>
# => Jon <jon>

Note that the memoization symbol can only be used on the right hand side of a production rule.

Unique Rules

Rule expansions can be marked as ‘unique’, meaning that multiple references to the same rule always return a different value. This is useful for situations where the same result appearing twice would appear awkward and messy.

Unique rules are marked by the $ sigil.

grammar = Calyx::Grammar.new do
  start "{$medal}, {$medal}, {$medal}"
  medal 'Gold', 'Silver', 'Bronze'
end

grammar.generate
# => Silver, Bronze, Gold

Dynamically Constructing Rules

Template expansions can be dynamically constructed at runtime by passing a context map of rules to the #generate method:

class AppGreeting < Calyx::Grammar
  start 'Hi {username}!', 'Welcome back {username}...', 'Hola {username}'
end

context = {
  username: UserModel.username
}

greeting = AppGreeting.new
greeting.generate(context)

External File Formats

In addition to defining grammars in pure Ruby, you can load them from external JSON and YAML files:

hello = Calyx::Grammar.load('hello.yml')
hello.generate

The format requires a flat map with keys representing the left-hand side named symbols and the values representing the right hand side substitution rules.

In JSON:

{
  "start": "{greeting} world.",
  "greeting": ["Hello", "Hi", "Hey", "Yo"]
}

In YAML:

---
start: "{greeting} world."
greeting:
  - Hello
  - Hi
  - Hey
  - Yo

Accessing the Raw Generated Tree

Calling #evaluate on the grammar instance will give you access to the raw generated tree structure before it gets flattened into a string.

The tree is encoded as an array of nested arrays, with the leading symbols labeling the choices and rules selected, and the trailing terminal leaves encoding string values.

This may not make a lot of sense unless you’re familiar with the concept of s-expressions. It’s a fairly speculative feature at this stage, but it leads to some interesting possibilities.

grammar = Calyx::Grammar.new do
  start 'Riddle me ree.'
end

grammar.evaluate
# => [:start, [:choice, [:concat, [[:atom, "Riddle me ree."]]]]]

Roadmap

Rough plan for stabilising the API and features for a 1.0 release.

VersionFeatures planned
0.6block constructor
0.7support for template context map passed to generate
0.8method missing metaclass API
0.9return grammar tree from #evaluate, with flattened string from #generate being separate
0.10inject custom string functions for parameterised rules, transforms and mappings
0.11support YAML format (and JSON?)
0.12API documentation
0.13Support for unique rules
0.14Support for Ruby 2.4
0.15Options config and ‘strict mode’ error handling
0.16Improve representation of weighted probability selection
0.17Return result object from #generate calls

Credits

Author & Maintainer

Contributors

Author: Maetl
Source Code: https://github.com/maetl/calyx 
License: MIT license

#ruby #text