如何消除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
相关产品推荐
相关产品推荐

