我不理解以下涉及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'
答案 0 :(得分:2)
问题在于您覆盖inspect
。当您尝试在丢失的公司上调用委托名称时,会引发NoMethodError
。 Delegated 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
,这是无限递归开始的地方。