Last active
June 27, 2016 02:00
-
-
Save farhansalam/2e0ec7cc43456b7eb1abda06d4b8a9a0 to your computer and use it in GitHub Desktop.
An example to demonstrate Proxy Pattern implemented in Ruby https://repl.it/C6R2/3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CarRental | |
def initialize(cars) | |
@cars = cars | |
end | |
def rent_out(n) | |
@cars -= n | |
end | |
def buy(n) | |
@cars += n | |
end | |
def inventory | |
puts "Cars left: #{@cars}" | |
end | |
# An overwritten Object Class method | |
def to_s | |
puts "Inspecting cars: #{@cars.inspect}" | |
end | |
end | |
class RentalProxy < BasicObject | |
def initialize(cars) | |
@history = [] | |
@rental = ::CarRental.new(cars) | |
@history << [:init, cars] | |
end | |
def method_missing(method, *args, &block) | |
@history << [method, args] | |
@rental.send(method, *args, &block) | |
end | |
def history | |
@history | |
end | |
end | |
car_rental = RentalProxy.new(20) | |
puts car_rental.history.to_s | |
car_rental.inventory | |
car_rental.rent_out(2) | |
car_rental.inventory | |
car_rental.buy(4) | |
car_rental.inventory | |
puts car_rental.history.to_s | |
car_rental.to_s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Console Output