...

/

Solution: Calculate Sales Tax

Solution: Calculate Sales Tax

Go over the implementation of calculating sales tax and look at the use of modules.

We'll cover the following...

Solution

Press + to interact
module GSTCalc
GST_RATE = 10.0
def net_amount
if @sales_tax_applicable
(@amount / (100.0 + GST_RATE) * 100.0).round(2)
else
return @amount
end
end
def gst
if @sales_tax_applicable
tax = (@amount - self.net_amount).round(2)
else
return 0.0
end
end
end
class ServiceItem
include GSTCalc
attr_accessor :name, :amount, :sales_tax_applicable
def initialize(name, amount)
self.name = name
self.amount = amount
self.sales_tax_applicable = false # => default no sales tax
end
end
class Goods
include GSTCalc
attr_accessor :name, :amount, :sales_tax_applicable
def initialize(name, amount)
self.name = name
self.amount = amount
self.sales_tax_applicable = true # => default has sales tax
end
end
foam_roller = Goods.new("Foam Roller", 49.95)
puts "#{foam_roller.name} Net Amount: #{foam_roller.net_amount}, GST: #{foam_roller.gst}"
physio_service = ServiceItem.new("Physio Consultation", 120.0)
puts "#{physio_service.name} Net Amount: #{physio_service.net_amount}, GST: #{physio_service.gst}"
pilates_class = ServiceItem.new("Pilates Classes", 80.0)
pilates_class.sales_tax_applicable = true
puts "#{pilates_class.name} Net Amount: #{pilates_class.net_amount}, GST: #{pilates_class.gst}"

Explanation

  • Lines 1–20: We define the GSTCalc ...