ruby - Ruby:如何为类字段的 << 方法添加验证
问题描述
我了解如何实现(验证)setter ( def item=
),但是如何拦截<<
字段上的操作?
class Bla
attr_reader :item
def initialize
@item = []
end
# only called for =, +=, -= operations (not <<)
def item=(value)
puts "Changing value to #{value}"
# pretend that there is a conditional here
@item = value
end
# This is wrong:
#def item<<(value)
# puts "adding value #{value}"
# @item << value
#end
end
b = Bla.new
b.item = ['one'] # works
b.item += ['one'] # works
b.item << 'two' # bypasses my setter
我试过def item<<(value)
了,好像不行。
解决方案
当您调用 时b.item << 'two'
,您是在直接调用该<<
方法。item
所以你有几个选择:
<<
直接在你的类上实现Bla
,然后使用b << 'two'
:# in class Bla def <<(value) # do validation here @item << value end
使用其他一些更好命名的包装方法名称,例如
add_item
:# in class Bla def add_item(value) # do validation here @item << value end
使用
@item
具有自定义定义的特殊数组类<<
:class MyArray < Array def <<(item) # run validation here super end end # in Bla class def initialize @item = MyArray.new end
我可能会选择选项 2,它是最简单易读的。
推荐阅读
- sql - mysql表中两列之间的公共值
- arrays - 在数组字段(可变长度)上应用 Udf 并将其拆分为 pyspark 中的列
- git - 如何通过终端创建拉取请求?
- node.js - 为什么我的 django html 页面上没有显示我的 API 数据?
- php - 如何在 laravel 内置重置密码中考虑软删除
- java - Bean 范围请求的多线程问题
- javascript - 我可以使用 SSH 压缩托管空间中的文件夹吗?
- python - 我无法在这个 python pandas 中拆分 Raw 列
- javascript - scratch-blocks@0.1.0 预发布:`python build.py && webpack`
- linkedin - Linkedin API:adAnalyticsV2 显示展示次数随着时间的推移而减少