在Ruby中支持双向语法的问题[英] Problem Supporting two way syntax in ruby

本文是小编为大家收集整理的关于在Ruby中支持双向语法的问题的处理方法,想解了在Ruby中支持双向语法的问题的问题怎么解决?在Ruby中支持双向语法的问题问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

我有一种情况需要这样调用:

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

工人阶级

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 !@office_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 个 worker 实例??

推荐答案

我不完全确定,但我想你想要这个:

class Office

  attr_accessor :workers, :id

  def initialize
    @workers = []
  end

  alias_method :workers, :return_worker_array

  def workers worker
    unless worker
      return_worker_array
    else
      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)
      return_worker_array << worker
  end
end

结束

这样你可以完全摆脱 Worker#<< 并且你也应该删除该行

office.workers = self

in Worker#initialize 因为 office.workers 应该是一个数组.来回更改属性类型(duck-typing 就可以)是个坏主意,因为您可能会忘记当前状态,并且迟早会遇到错误.

为了遵循"关注点分离",我建议只在 Office 中完成对 workers 的整个管理,否则它会很快变得过于混乱,并且从长远来看将更难以维护.

本文地址:https://www.itbaoku.cn/post/786699.html