Skip to content

Instantly share code, notes, and snippets.

@codeprimate
Last active August 16, 2024 06:46
Show Gist options
  • Save codeprimate/ea6b922bd723ed379bd8fbcec7352621 to your computer and use it in GitHub Desktop.
Save codeprimate/ea6b922bd723ed379bd8fbcec7352621 to your computer and use it in GitHub Desktop.
The Fluent Interface
# This is an example of the the Fluent Interface Pattern
class ShoppingCart
attr_reader :items
def initialize
@items = []
end
def add_item(item)
@items << item
self
end
def remove_item(item)
@items.delete_if { |item| item[:name] == item_name }
self
end
def clear
@items.clear
self
end
def apply_discount(discount)
@items.each do |item|
item[:price] -= item[:price] * discount
end
self
end
def total
@items.sum { |item| item[:price] }
end
end
# Example usage:
cart = ShoppingCart.new
cart.add_item({ name: 'Book', price: 12.99 })
.add_item({ name: 'Pen', price: 1.99 })
.apply_discount(0.1) # 10% discount
.remove_item('Pen')
puts "Total: $#{cart.total}" # Total: $11.69
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment