Skip to content

Instantly share code, notes, and snippets.

@TMorgan99
Created February 13, 2019 21:33
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 TMorgan99/fe93e296a45d91ee1d0c4c674e2d5b79 to your computer and use it in GitHub Desktop.
Save TMorgan99/fe93e296a45d91ee1d0c4c674e2d5b79 to your computer and use it in GitHub Desktop.
require_relative 'ds'
class Computer
LIMIT = 100 # if price exceeds this, the description will be flagged
FORMAT = "%s%s: %s ($%d)" # flag, name, info, price.
def initialize(computer_id, data_source)
@id = computer_id
@data_source = data_source
end
# I don't know if #send or #method missing is better, but this demonstrates both.
def method_missing( item )
info = @data_source.send "get_#{item}_info", @id
name = item.to_s
price = @data_source.send "get_#{item}_price", @id
flag = price >= LIMIT ? "* " : ""
# result = # unused name for return value
FORMAT%[ flag, name, info, price]
end
end
ds = DS.new
workstation1 = Computer.new(1, ds)
p workstation1.mouse
p workstation1.cpu
p workstation1.keyboard
@mmalek-sa
Copy link

Thanks Tim! Great work. The only thing I would change was adding a check at the beginning of the method_missing to make sure data_source class responds_to("get_#{item}_info")

@TMorgan99
Copy link
Author

Good point, A whitelist of items would be a good addition, But for now, those errors will be caught by DS::method_missing.
Do we know that DS has implemented *_info and *_price in pairs?
Or would we want to test respond_to? for both?
It hasn't implemented the id aspect very well.

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