Day 18 - dentaku Gem - Parse and Evaluate Math (and Logical Formulas) with a Calculator in a Sandbox, Safely
Written by {% avatar 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.
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?
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"
}
calc.solve!(need_to_compute)
#=> { annual_income: 600, income_taxes: 120 }
We have been using this gem since last year and it has been rock solid!
I encourage you to checkout the Readme, it has some great examples of things you can do with Dentaku.
- Home :: github.com/rubysolo/dentaku
- Gem :: rubygems.org/gems/dentaku
- Docs :: rubydoc.info/gems/dentaku