« 25 Days of Ruby Gems - Ruby Advent Calendar 2020, December 1st - December 25th

Day 18 - dentaku Gem - Parse and Evaluate Math (and Logical Formulas) with a Calculator in a Sandbox, Safely

Written by jankeesvw Jankees van Woezik

A freelance full stack maker from the Netherlands with a love for building products. Co-founder of Stekker.app and Timi.app.

Evaluate math and logical formulas

This gem is not something you need for every project, but it’s a fun one.

I’m building a Ruby on Rails app for Stekker.app. Creating invoices for charging sessions of electric vehicles is one of the things we do. Every customer can have a different contract and those contracts can have different pricing structures.

For instance, this is one of our formulas:

minutes * costPerMinute + kwhVolume * costPerKwh

You probably wonder how that evaluates to a price for a charging session?

Enter Dentaku

Dentaku means calculator in Japanese, and that’s exactly what this gem does. The readme has some great examples and I’ll share some here so you see what it can do.

Let’s start with a simple example:

calculator = Dentaku::Calculator.new
calculator.evaluate('10 * 2')
#=> 20

Okay, that’s not hard and you could do the same with eval in plain Ruby (please don’t it’s unsafe!). Dentaku can do so much more, take this example:

calculator = Dentaku::Calculator.new
calculator.evaluate('kiwi + 5', kiwi: 2)
#=> 7

So yes, it can handle variables, now take a look at even a more complex example:

calc = Dentaku::Calculator.new
calc.store(monthly_income: 50)
need_to_compute = {
  annual_income: "monthly_income * 12",
  income_taxes:  "annual_income / 5"
#=> { annual_income: 600, income_taxes: 120 }

We have been using this gem since last year and it has been rock solid!

Find Out More

I encourage you to checkout the Readme, it has some great examples of things you can do with Dentaku.


Built with Ruby (running Jekyll) on 2021-07-25 15:15:02 +0000 in 0.371 seconds.
Hosted on GitHub Pages. </> Source on GitHub. (0) Dedicated to the public domain.