I have a situation where i need to call something like this :
class Office
attr_accessor :workers, :id
def initialize
@workers = []
end
def workers<<(worker)
type = worker.type
resp = Organiation::Worker.post("/office/#{@id}/workers.json", :worker => {:type => type})
end
end
this is where i need to call
office = Office.new()
new_worker = Worker.new()
office.workers << new_worker
how should i modify the above workers method in order to implement above code.
New answer for this (based on updated question):
class WorkersClient
attr_accessor :office_id
def <<(worker)
type = worker.type
resp = Organiation::Worker.post("/office/#{@office_id}/workers.json", :worker => {:type => type})
end
end
class Office
attr_accessor :workers, :id
def initialize
@workers = WorkersClient.new
@workers.office_id = @id
end
end
I'm assuming that the Worker
class is defined somewhere, something like:
def Worker
attr_accessor :type
...
end
The WorkersClient
class is just a proxy to handle the collection (like ActiveRecord 3 does with associations). You can develop it further to store a local cache of workers, and so on.
I would recommend looking at how Rails' ActiveResource is implemented, as it does something VERY similar.
try this office.build_worker
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With