The Product
model which can have 2 price tables. The method price
calculates the price of the product based on product's price table which is defined by price_table
field.
class Product < ActiveRecord::Model
NORMAL_PRICE_TABLE = 1
PROMOTIONAL_PRICE_TABLE = 2
validates_presence_of :price_table
def price(quantity)
case price_table
when NORMAL_PRICE_TABLE
# calculate using normal price table rules
when PROMOTIONAL_PRICE_TABLE
# calculate using promotional price table rules
else
raise 'unknown data price'
end
end
end
I want to refactor this code. The cleaner way I get is this:
class NormalPriceTable
def initialize(raw_product_price, quantity)
@raw_product_price = raw_product_price
@quantity = quantity
end
def price
# calculate
end
end
class PromotionalPriceTable
def initialize(raw_product_price, quantity)
@raw_product_price = raw_product_price
@quantity = quantity
end
def price
# calculate
end
end
class Product < ActiveRecord::Model
NORMAL_PRICE_TABLE = 1
PROMOTIONAL_PRICE_TABLE = 2
def price(quantity)
price_table_class.new(raw_price, quantity).price
end
def price_table_class
case price_table
when NORMAL_PRICE_TABLE
NormalPriceTable
when PROMOTIONAL_PRICE_TABLE
NormalPriceTable.new(raw_price, quantity).price
else
raise 'unknown price table'
end
end
end
Two questions:
- It's possible to get rid of this
case
clause onProduct
class? - Which are the other alternatives to refactor this code?