Skip to content

Instantly share code, notes, and snippets.

@farhansalam
Last active June 27, 2016 02:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save farhansalam/2e0ec7cc43456b7eb1abda06d4b8a9a0 to your computer and use it in GitHub Desktop.
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
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
@farhansalam
Copy link
Author

Console Output

ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]
>>> [[:init, 20]]
Cars left: 20
Cars left: 18
Cars left: 22
[[:init, 20], [:inventory, []], [:rent_out, [2]], [:inventory, []], [:buy, [4]], [:inventory, []]]
Inspecting cars: 22

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment