WIP on kilo price
This commit is contained in:
parent
78da4feafe
commit
80031c9e20
2 changed files with 81 additions and 0 deletions
59
app/lib/quantity_unit.rb
Normal file
59
app/lib/quantity_unit.rb
Normal file
|
@ -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
|
22
spec/lib/quantity_unit_spec.rb
Normal file
22
spec/lib/quantity_unit_spec.rb
Normal file
|
@ -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
|
Loading…
Reference in a new issue