Rails 委托和别名 - 无限循环?

Rails delegate and alias - infinite loop?

我不明白以下涉及delegatealias

的无限循环
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'

问题出在您对 inspect 的覆盖上。当您尝试调用缺失公司的委托名称时,会引发 NoMethodErrorDelegated method then tries to rescue it and show you helpful error message.

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

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