2

我不明白以下涉及delegate和的无限循环alias

class Company
  field :name
end

class Employee < Professional
  include CompanyMember
end

class Professional 
  include UserProfile
end

module CompanyMember
  belongs_to :company
  delegate :name, to: :company, prefix: true
  alias :organization_name :company_name
end

module UserProfile
  def to_s
    out = "#{name} "
    out += "(#{organization_name})" if respond_to?(:organization_name)
  end 
  def inspect
    to_s + super
  end
end

我有一家Employee失踪的公司,我有以下无限循环

app/models/concerns/user_profile.rb:94:in `inspect'
app/models/concerns/company_member.rb:8:in `rescue in company_name'
app/models/concerns/company_member.rb:8:in `company_name'
app/models/concerns/user_profile.rb:89:in `to_s'
app/models/concerns/user_profile.rb:94:in `inspect'
app/models/concerns/company_member.rb:8:in `rescue in company_name'
app/models/concerns/company_member.rb:8:in `company_name'
app/models/concerns/user_profile.rb:89:in `to_s'
4

1 回答 1

3

问题在于您对inspect. 当您尝试调用丢失公司的委托名称时,NoMethodError会引发。然后委托方法尝试拯救它并向您显示有用的错误消息

exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")

你看,它调用inspect来获取你的对象的可打印版本。不幸的是,它调用了.to_s,这是无限递归开始的地方。

于 2016-12-13T18:26:50.703 回答