Man*_*Das 9 ruby rubygems ruby-on-rails ruby-on-rails-3
我有一种情况需要调用这样的东西:
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
Run Code Online (Sandbox Code Playgroud)
这是我需要打电话的地方
office = Office.new()
new_worker = Worker.new()
office.workers << new_worker
Run Code Online (Sandbox Code Playgroud)
我应该如何修改上面的worker方法以实现上面的代码.
对此的新答案(基于更新的问题):
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
Run Code Online (Sandbox Code Playgroud)
我假设该类Worker是在某个地方定义的,例如:
def Worker
attr_accessor :type
...
end
Run Code Online (Sandbox Code Playgroud)
该类WorkersClient只是处理集合的代理(就像 ActiveRecord 3 处理关联一样)。您可以进一步开发它来存储工作人员的本地缓存,等等。
我建议看看 Rails 的 ActiveResource 是如何实现的,因为它做了非常相似的事情。
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |