Dexter  Goodwin

Dexter Goodwin

1661219700

Generify: A Reusable Project Generator

generify 

A reusable project generator that copies file recursively, while replacing keywords from passed data.

Example

'use strict'

const generify = require('generify')
const source = './template'
const dest = '/tmp/generify-test'
const data = { hello: 'hello world' }

// without notification
generify(source, dest, data, function (err) {
  if (err) {
    console.log(err)
  } else {
    console.log('ok!')
  }
})

// with notification
generify(source, dest, data, onData, done)

function onData (file) {
  console.log('writing file')
}

function done (err) {
  if (err) {
    console.log(err)
  } else {
    console.log('ok!')
  }
}

This will replace all the __hello__ patterns found in all files with the 'hello world' string.

If the supplied data has a key transforms, with a hash of tranformation functions, then the found tokens will be used to run a corresponding transform on the supplied data. Example:

const data = {
  transforms: { foo: (data, context) => data.toUpperCase() },
  foo: 'foo'
}

// __foo__ => foo_transform(data = 'foo') => 'FOO'

The context object contains properties: source (input file path), dest (output file path), key (the matched key).

Files and Directories

files and directories located in the template folder may also be replaced. File and folder names wrapped with @ delimiters will be replaced.

Example

Given a template with:

/template/@foo@/@bar@.txt

and data:

const data = {
  foo: 'hello',
  bar: 'world'
}

The outputted file will be:

<dest>/hello/world.txt

__ handling

If a file begins with __ that will be automatically converted into a .. This is useful for generating .gitignore files.

If the supplied data has a key copyAsNamed, with an array of names, then the filenames in that list will not be processed through this rule. Each file name in the list should not include a path, e.g. ['__do-not-replace-underscores.js'].

Executable

generify also offers an executable that can be called with:

Usage: generify template destination [json file]

Where the json file contains the data to be replaced.

Acknowledgements

This project was kindly sponsored by nearForm.

Download Details:

Author: mcollina
Source Code: https://github.com/mcollina/generify 
License: MIT license

#javascript #generator 

What is GEEK

Buddha Community

Generify: A Reusable Project Generator
Autumn  Blick

Autumn Blick

1593867420

Top Android Projects with Source Code

Android Projects with Source Code – Your entry pass into the world of Android

Hello Everyone, welcome to this article, which is going to be really important to all those who’re in dilemma for their projects and the project submissions. This article is also going to help you if you’re an enthusiast looking forward to explore and enhance your Android skills. The reason is that we’re here to provide you the best ideas of Android Project with source code that you can choose as per your choice.

These project ideas are simple suggestions to help you deal with the difficulty of choosing the correct projects. In this article, we’ll see the project ideas from beginners level and later we’ll move on to intermediate to advance.

top android projects with source code

Android Projects with Source Code

Before working on real-time projects, it is recommended to create a sample hello world project in android studio and get a flavor of project creation as well as execution: Create your first android project

Android Projects for beginners

1. Calculator

build a simple calculator app in android studio source code

Android Project: A calculator will be an easy application if you have just learned Android and coding for Java. This Application will simply take the input values and the operation to be performed from the users. After taking the input it’ll return the results to them on the screen. This is a really easy application and doesn’t need use of any particular package.

To make a calculator you’d need Android IDE, Kotlin/Java for coding, and for layout of your application, you’d need XML or JSON. For this, coding would be the same as that in any language, but in the form of an application. Not to forget creating a calculator initially will increase your logical thinking.

Once the user installs the calculator, they’re ready to use it even without the internet. They’ll enter the values, and the application will show them the value after performing the given operations on the entered operands.

Source Code: Simple Calculator Project

2. A Reminder App

Android Project: This is a good project for beginners. A Reminder App can help you set reminders for different events that you have throughout the day. It’ll help you stay updated with all your tasks for the day. It can be useful for all those who are not so good at organizing their plans and forget easily. This would be a simple application just whose task would be just to remind you of something at a particular time.

To make a Reminder App you need to code in Kotlin/Java and design the layout using XML or JSON. For the functionality of the app, you’d need to make use of AlarmManager Class and Notifications in Android.

In this, the user would be able to set reminders and time in the application. Users can schedule reminders that would remind them to drink water again and again throughout the day. Or to remind them of their medications.

3. Quiz Application

Android Project: Another beginner’s level project Idea can be a Quiz Application in android. Here you can provide the users with Quiz on various general knowledge topics. These practices will ensure that you’re able to set the layouts properly and slowly increase your pace of learning the Android application development. In this you’ll learn to use various Layout components at the same time understanding them better.

To make a quiz application you’ll need to code in Java and set layouts using xml or java whichever you prefer. You can also use JSON for the layouts whichever preferable.

In the app, questions would be asked and answers would be shown as multiple choices. The user selects the answer and gets shown on the screen if the answers are correct. In the end the final marks would be shown to the users.

4. Simple Tic-Tac-Toe

android project tic tac toe game app

Android Project: Tic-Tac-Toe is a nice game, I guess most of you all are well aware of it. This will be a game for two players. In this android game, users would be putting X and O in the given 9 parts of a box one by one. The first player to arrange X or O in an adjacent line of three wins.

To build this game, you’d need Java and XML for Android Studio. And simply apply the logic on that. This game will have a set of three matches. So, it’ll also have a scoreboard. This scoreboard will show the final result at the end of one complete set.

Upon entering the game they’ll enter their names. And that’s when the game begins. They’ll touch one of the empty boxes present there and get their turn one by one. At the end of the game, there would be a winner declared.

Source Code: Tic Tac Toe Game Project

5. Stopwatch

Android Project: A stopwatch is another simple android project idea that will work the same as a normal handheld timepiece that measures the time elapsed between its activation and deactivation. This application will have three buttons that are: start, stop, and hold.

This application would need to use Java and XML. For this application, we need to set the timer properly as it is initially set to milliseconds, and that should be converted to minutes and then hours properly. The users can use this application and all they’d need to do is, start the stopwatch and then stop it when they are done. They can also pause the timer and continue it again when they like.

6. To Do App

Android Project: This is another very simple project idea for you as a beginner. This application as the name suggests will be a To-Do list holding app. It’ll store the users schedules and their upcoming meetings or events. In this application, users will be enabled to write their important notes as well. To make it safe, provide a login page before the user can access it.

So, this app will have a login page, sign-up page, logout system, and the area to write their tasks, events, or important notes. You can build it in android studio using Java and XML at ease. Using XML you can build the user interface as user-friendly as you can. And to store the users’ data, you can use SQLite enabling the users to even delete the data permanently.

Now for users, they will sign up and get access to the write section. Here the users can note down the things and store them permanently. Users can also alter the data or delete them. Finally, they can logout and also, login again and again whenever they like.

7. Roman to decimal converter

Android Project: This app is aimed at the conversion of Roman numbers to their significant decimal number. It’ll help to check the meaning of the roman numbers. Moreover, it will be easy to develop and will help you get your hands on coding and Android.

You need to use Android Studio, Java for coding and XML for interface. The application will take input from the users and convert them to decimal. Once it converts the Roman no. into decimal, it will show the results on the screen.

The users are supposed to just enter the Roman Number and they’ll get the decimal values on the screen. This can be a good android project for final year students.

8. Virtual Dice Roller

Android Project: Well, coming to this part that is Virtual Dice or a random no. generator. It is another simple but interesting app for computer science students. The only task that it would need to do would be to generate a number randomly. This can help people who’re often confused between two or more things.

Using a simple random number generator you can actually create something as good as this. All you’d need to do is get you hands-on OnClick listeners. And a good layout would be cherry on the cake.

The user’s task would be to set the range of the numbers and then click on the roll button. And the app will show them a randomly generated number. Isn’t it interesting ? Try soon!

9. A Scientific Calculator App

Android Project: This application is very important for you as a beginner as it will let you use your logical thinking and improve your programming skills. This is a scientific calculator that will help the users to do various calculations at ease.

To make this application you’d need to use Android Studio. Here you’d need to use arithmetic logics for the calculations. The user would need to give input to the application that will be in terms of numbers. After that, the user will give the operator as an input. Then the Application will calculate and generate the result on the user screen.

10. SMS App

Android Project: An SMS app is another easy but effective idea. It will let you send the SMS to various no. just in the same way as you use the default messaging application in your phone. This project will help you with better understanding of SMSManager in Android.

For this application, you would need to implement Java class SMSManager in Android. For the Layout you can use XML or JSON. Implementing SMSManager into the app is an easy task, so you would love this.

The user would be provided with the facility to text to whichever number they wish also, they’d be able to choose the numbers from the contact list. Another thing would be the Textbox, where they’ll enter their message. Once the message is entered they can happily click on the send button.

#android tutorials #android application final year project #android mini projects #android project for beginners #android project ideas #android project ideas for beginners #android projects #android projects for students #android projects with source code #android topics list #intermediate android projects #real-time android projects

Shawn  Durgan

Shawn Durgan

1595547778

10 Writing steps to create a good project brief - Mobile app development

Developing a mobile application can often be more challenging than it seems at first glance. Whether you’re a developer, UI designer, project lead or CEO of a mobile-based startup, writing good project briefs prior to development is pivotal. According to Tech Jury, 87% of smartphone users spend time exclusively on mobile apps, with 18-24-year-olds spending 66% of total digital time on mobile apps. Of that, 89% of the time is spent on just 18 apps depending on individual users’ preferences, making proper app planning crucial for success.

Today’s audiences know what they want and don’t want in their mobile apps, encouraging teams to carefully write their project plans before they approach development. But how do you properly write a mobile app development brief without sacrificing your vision and staying within the initial budget? Why should you do so in the first place? Let’s discuss that and more in greater detail.

Why a Good Mobile App Project Brief Matters?

Why-a-Good-Mobile-App-Project-Brief-Matters

It’s worth discussing the significance of mobile app project briefs before we tackle the writing process itself. In practice, a project brief is used as a reference tool for developers to remain focused on the client’s deliverables. Approaching the development process without written and approved documentation can lead to drastic, last-minute changes, misunderstanding, as well as a loss of resources and brand reputation.

For example, developing a mobile app that filters restaurants based on food type, such as Happy Cow, means that developers should stay focused on it. Knowing that such and such features, UI elements, and API are necessary will help team members collaborate better in order to meet certain expectations. Whether you develop an app under your brand’s banner or outsource coding and design services to would-be clients, briefs can provide you with several benefits:

  • Clarity on what your mobile app project “is” and “isn’t” early in development
  • Point of reference for developers, project leads, and clients throughout the cycle
  • Smart allocation of available time and resources based on objective development criteria
  • Streamlined project data storage for further app updates and iterations

Writing Steps to Create a Good Mobile App Project Brief

Writing-Steps-to-Create-a-Good-Mobile-App-Project-Brief

1. Establish the “You” Behind the App

Depending on how “open” your project is to the public, you will want to write a detailed section about who the developers are. Elements such as company name, address, project lead, project title, as well as contact information, should be included in this introductory segment. Regardless of whether you build an in-house app or outsource developers to a client, this section is used for easy document storage and access.

#android app #ios app #minimum viable product (mvp) #mobile app development #web development #how do you write a project design #how to write a brief #how to write a project summary #how to write project summary #program brief example #project brief #project brief example #project brief template #project proposal brief #simple project brief template

Ray  Patel

Ray Patel

1619636760

42 Exciting Python Project Ideas & Topics for Beginners [2021]

Python Project Ideas

Python is one of the most popular programming languages currently. It looks like this trend is about to continue in 2021 and beyond. So, if you are a Python beginner, the best thing you can do is work on some real-time Python project ideas.

We, here at upGrad, believe in a practical approach as theoretical knowledge alone won’t be of help in a real-time work environment. In this article, we will be exploring some interesting Python project ideas which beginners can work on to put their Python knowledge to test. In this article, you will find 42 top python project ideas for beginners to get hands-on experience on Python

Moreover, project-based learning helps improve student knowledge. That’s why all of the upGrad courses cover case studies and assignments based on real-life problems. This technique is ideally for, but not limited to, beginners in programming skills.

But first, let’s address the more pertinent question that must be lurking in your mind:

#data science #python project #python project ideas #python project ideas for beginners #python project topics #python projects #python projects for beginners

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

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