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

时间:2016-12-13 18:09:03

标签: ruby-on-rails ruby-on-rails-5 activesupport activesupport-concern

我不理解以下涉及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'

1 个答案:

答案 0 :(得分:2)

问题在于您覆盖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,这是无限递归开始的地方。