You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何消除ActiveRecord::Base结合SimpleDelegator的#to_ary私有方法警告?

如何消除「warning: delegator does not forward private method #to_ary」警告

技术环境

  • Ruby 3.2.1
  • Rails 7.0.4.3

问题复现

执行以下代码会触发目标警告:

class Foo < ActiveRecord::Base
  def name
    "foobar"
  end
end

class FooDelegator < SimpleDelegator
  def name
    "name"
  end
end

[FooDelegator.new(Foo.new)].flatten
# 输出警告:warning: delegator does not forward private method #to_ary

解决方法

方法一:显式转发私有#to_ary方法

SimpleDelegator默认不会自动转发私有方法,而ActiveRecord实例的to_ary是私有方法。在代理类中手动实现私有to_ary并转发给被代理对象即可:

class FooDelegator < SimpleDelegator
  def name
    "name"
  end

  private

  def to_ary
    __getobj__.to_ary
  end
end

方法二:使用Forwardable指定转发私有方法

如果改用Forwardable模块,可以明确指定转发私有方法(Ruby 2.1+支持):

require 'forwardable'

class FooDelegator
  extend Forwardable
  def_delegators :@foo, :name
  def_delegator :@foo, :to_ary, private: true

  def initialize(foo)
    @foo = foo
  end
end

方法三:避免触发to_ary逻辑

如果不需要数组展开内部元素,调用flatten(0)可以跳过对元素to_ary方法的检测:

[FooDelegator.new(Foo.new)].flatten(0)

内容的提问来源于stack exchange,提问作者Gbeschbacher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 04:05:02