如何使用关键字编写尾随方法

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方法以实现上面的代码.

Jit*_*its 4

对此的新答案(基于更新的问题):

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 是如何实现的,因为它做了非常相似的事情。

  • @Jits:但是我如何访问WorkersClient类中的office对象的id? (2认同)