From 80031c9e20ad6800e12b11bde260d12139f8c506 Mon Sep 17 00:00:00 2001 From: FGU Date: Fri, 24 Feb 2023 18:12:45 +0100 Subject: [PATCH] WIP on kilo price --- app/lib/quantity_unit.rb | 59 ++++++++++++++++++++++++++++++++++ spec/lib/quantity_unit_spec.rb | 22 +++++++++++++ 2 files changed, 81 insertions(+) create mode 100644 app/lib/quantity_unit.rb create mode 100644 spec/lib/quantity_unit_spec.rb diff --git a/app/lib/quantity_unit.rb b/app/lib/quantity_unit.rb new file mode 100644 index 00000000..0a910f87 --- /dev/null +++ b/app/lib/quantity_unit.rb @@ -0,0 +1,59 @@ +class QuantityUnit + def initialize(quantity, unit) + @quantity = quantity + @unit = unit + end + + def self.parse(number_with_unit) + # remove whitespace + number_with_unit = number_with_unit.gsub(/\s+/, '') + # to lowercase + number_with_unit = number_with_unit.downcase + # remove numerical part + number = number_with_unit.gsub(/[^0-9.,]/, '') + # remove unit part + unit = number_with_unit.gsub(/[^a-zA-Z]/, '') + # convert comma to dot + number = number.gsub(',', '.') + # convert to float + number = number.to_f + + return nil unless unit.in?(%w[g kg l ml]) + + QuantityUnit.new(number, unit) + end + + def scale_price_to_base_unit(price) + return nil unless price.is_a?(Numeric) + + factor = if @unit == 'kg' || @unit == 'l' + 1 + elsif @unit == 'g' || @unit == 'ml' + 1000 + end + + scaled_price = price / @quantity * factor + scaled_price.round(2) + + base_unit = if @unit == 'kg' || @unit == 'g' + 'kg' + elsif @unit == 'l' || @unit == 'ml' + 'L' + end + + [scaled_price, base_unit] + end + + + def to_s + "#{@quantity} #{@unit}" + end + + def quantity + @quantity + end + + def unit + @unit + end +end \ No newline at end of file diff --git a/spec/lib/quantity_unit_spec.rb b/spec/lib/quantity_unit_spec.rb new file mode 100644 index 00000000..bbe3d546 --- /dev/null +++ b/spec/lib/quantity_unit_spec.rb @@ -0,0 +1,22 @@ +require_relative '../spec_helper' + +describe QuantityUnit do + it "parses a string correctly" do + qu = QuantityUnit.parse("1.5 k g"); expect([qu.quantity, qu.unit]).to eq([1.5, "kg"]) + qu = QuantityUnit.parse(" 1,5 kg"); expect([qu.quantity, qu.unit]).to eq([1.5, "kg"]) + qu = QuantityUnit.parse("1500 g"); expect([qu.quantity, qu.unit]).to eq([1500, "g"]) + qu = QuantityUnit.parse("1.5L "); expect([qu.quantity, qu.unit]).to eq([1.5, "l"]) + qu = QuantityUnit.parse("2400mL"); expect([qu.quantity, qu.unit]).to eq([2400, "ml"]) + end + + it "scales prices correctly" do + qu = QuantityUnit.new(1.5, "kg") + expect(qu.scale_price_to_base_unit(12.34)).to eq([8.23, "kg"]) + qu = QuantityUnit.new(1500, "g") + expect(qu.scale_price_to_base_unit(12.34)).to eq([8.23, "kg"]) + qu = QuantityUnit.new(1.5, "l") + expect(qu.scale_price_to_base_unit(12.34)).to eq([8.23, "L"]) + qu = QuantityUnit.new(2400, "ml") + expect(qu.scale_price_to_base_unit(12.34)).to eq([5.14, "L"]) + end +end \ No newline at end of file