雙向語法我有一個情況我需要調用是這樣的:問題支持的紅寶石
class Office
attr_accessor :workers, :id
def initialize
@workers = []
end
def workers worker
type = worker.type
resp = Worker.post("/office/#{@id}/workers.json", :worker => {:type => type})
worker = Worker.new()
resp.to_hash.each_pair do |k,v|
worker.send("#{k}=",v) if worker.respond_to?(k)
end
self.workers << worker
end
end
Worker類
class Worker
attr_accessor :office_id, :type, :id
def initialize(options={})
@office_id = options[:office].nil? ? nil : options[:office].id
@type = options[:type].nil? ? nil : options[:type].camelize
if [email protected]_id.nil?
resp = self.class.post("/office/#{@office_id}/workers.json", :worker => {:type => @type})
@id = resp.id
office = options[:office]
office.workers = self
end
end
def <<(worker)
if worker
type = worker.type
resp = Worker.post("/office/#{office_id}/workers.json", :worker => {:type => type})
debugger
@id = resp.id
resp.to_hash.each_pair do |k,v|
self.send("#{k}=",v) if self.respond_to?(k)
end
debugger
return self
end
end
我可以做這樣的事情非常好
office = Office.new()
new_worker = Worker.new()
office.workers new_worker
但我需要做同樣的事情,我上面做了如下。在此之前,我需要更改Office的初始化方法以啓動工作者實例的def <<(worker)
方法。
class Office
...
def initialize
@workers = Worker.new
@workers.office_id = self.id
end
office = Office.new()
new_worker = Worker.new()
office.workers << new_worker
現在問題是,後面的實現創建了2個工人實例?
代碼是做什麼的? – Zabba 2011-06-06 06:06:22
@zabba,它在office對象的工作屬性中添加新的工作對象,而worker屬性是一個數組。 – 2011-06-06 06:08:37
您是否更改了更多的代碼?事實上,office.workers << new_worker應該是一個ArgumentError,因爲office.workers是一個參數爲1的方法。 – 2011-06-06 06:10:20