首页 > 解决方案 > 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)了,好像不行。

标签: rubysetter

解决方案


当您调用 时b.item << 'two',您是在直接调用该<<方法。item所以你有几个选择:

  1. <<直接在你的类上实现Bla,然后使用b << 'two'

    # in class Bla
    def <<(value)
      # do validation here
      @item << value
    end
    
  2. 使用其他一些更好命名的包装方法名称,例如add_item

    # in class Bla
    def add_item(value)
      # do validation here
      @item << value
    end
    
  3. 使用@item具有自定义定义的特殊数组类<<

    class MyArray < Array
      def <<(item)
        # run validation here
        super
      end
    end
    
    # in Bla class
    def initialize
      @item = MyArray.new
    end
    

我可能会选择选项 2,它是最简单易读的。


推荐阅读