Translate JsonLogic rules into readable sentences. Extension for JsonLogic.
⚙️ Zero deps · 🛠️ Configurable · 🧩 Mixin + Wrapper
This gem converts JsonLogic Rules into readable sentences.
- A mixin for serializer/presenter classes.
- A small wrapper for one-off translations.
No dependencies. Works with a Ruby Hash.
Config => operators map + variables map Input => JsonLogic Rule (Hash) Output => human-readable sentence
If you found this gem, you likely already know where to use it in your app — the abstract use case is simple: you want to read a Rule as text (e.g., show it in the UI, preview it, or share it elsewhere).
gem install json-logic-rb-humanizableAdd to your Gemfile if you need:
gem "json-logic-rb-humanizable"Then install:
bundle installConfiguration (if needed)
# config/initializers/json_logic.rb
require "json_logic"
# Configurationlogic = {
"and" => [
{ ">=" => [ { "var" => "payment.amount" }, 50 ] },
{ "in" => [ { "var" => "payment.currency" }, %w[EUR USD] ] }
]
}
puts JsonLogic::Rule.new(logic).humanizeExample output:
payment.amount is greater than or equal to 50 AND payment.currency is in EUR, USD
JsonLogic::Config.operators["in"] = "is one of"
JsonLogic::Config.vars[/([^\.]+)$/] = ->(m) { m[1].tr("_", " ").split.map(&:capitalize).join(" ") }
logic = {
"and" => [
{ ">=" => [ { "var" => "payment.amount" }, 50 ] },
{ "fact" => "payment.currency", "operator" => "in", "value" => %w[EUR USD] }
]
}
puts JsonLogic::Rule.new(logic).humanizeExample output:
Amount is greater than or equal to 50 AND Currency is one of ["EUR", "USD"]
class RuleSerializer
include JsonLogic::Humanizable
attr_reader :json_logic
def initialize(json_logic)
@json_logic = json_logic
end
def condition
humanize_logic(json_logic)
end
end
s = RuleSerializer.new({
"and" => [
{ ">=" => [ { "var" => "payment.amount" }, 50 ] },
{ "in" => [ { "var" => "payment.currency" }, %w[EUR USD] ] }
]
})
puts s.conditionExample output:
payment.amount is greater than or equal to 50 AND payment.currency is in EUR, USD
Configure labels as you prefer:
JsonLogic::Config.operators["in"] = "is one of"
JsonLogic::Config.operators["=="] = "equals"
JsonLogic::Config.operators[">="] = "is at least"
JsonLogic::Config.operators["!"] = "NOT"
JsonLogic::Config.operators["and"] = "AND"
JsonLogic::Config.operators["or"] = "OR"Each entry is key – pattern, value – replacement, where pattern is a Regexp or exact String, and replacement is a String or Proc.
JsonLogic::Config.vars[/([^\.]+)$/] = ->(m) { m[1].tr("_", " ").split.map(&:capitalize).join(" ") }This maps payment.amount → Amount, customer.country → Country, etc.
- JsonLogic site: https://jsonlogic.com/