Skip to content

Instantly share code, notes, and snippets.

@blarshk
Created September 7, 2017 19:26
Show Gist options
  • Save blarshk/1af71f7f9fd59a7976fd20025b9791c8 to your computer and use it in GitHub Desktop.
Save blarshk/1af71f7f9fd59a7976fd20025b9791c8 to your computer and use it in GitHub Desktop.
My take on the Gilded Rose refactoring kata
class Product
attr_reader :item
def initialize(item:)
@item = item
end
def update_quality
move_sale_date_closer
if item.sell_in < 0
decrease_quality(2)
else
decrease_quality(1)
end
end
def set_quality(adjusted_quality)
if adjusted_quality > 50
item.quality = 50
elsif adjusted_quality < 0
item.quality = 0
else
item.quality = adjusted_quality
end
end
def increase_quality(adjustment)
adjusted_quality = item.quality + adjustment
set_quality(adjusted_quality)
end
def decrease_quality(adjustment)
adjusted_quality = item.quality - adjustment
set_quality(adjusted_quality)
end
def move_sale_date_closer
item.sell_in -= 1
end
end
class AgedBrie < Product
def update_quality
move_sale_date_closer
if extra_aged?
increase_quality(2)
else
increase_quality(1)
end
end
private
def extra_aged?
item.sell_in < 0
end
end
class BackstagePass < Product
def update_quality
move_sale_date_closer
return set_quality(0) if concert_passed?
if concert_five_days_away?
increase_quality(3)
elsif concert_ten_days_away?
increase_quality(2)
else
increase_quality(1)
end
end
private
def concert_passed?
item.sell_in < 0
end
def concert_five_days_away?
item.sell_in < 5
end
def concert_ten_days_away?
item.sell_in < 10
end
end
class Sulfuras < Product
def update_quality
# Do nothing!
end
end
class ConjuredItem < Product
def update_quality
move_sale_date_closer
if item.sell_in < 0
decrease_quality(4)
else
decrease_quality(2)
end
end
end
def item_lookup(name)
{
"Aged Brie" => AgedBrie,
"Backstage passes to a TAFKAL80ETC concert" => BackstagePass,
"Sulfuras, Hand of Ragnaros" => Sulfuras,
"Conjured Mana Cake" => ConjuredItem
}.fetch(name, Product)
end
def update_quality(items)
items.each do |item|
product_class = item_lookup(item.name)
product = product_class.new(item: item)
product.update_quality
end
end
#----------------------------
# DO NOT CHANGE THINGS BELOW
#----------------------------
Item = Struct.new(:name, :sell_in, :quality)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment