如何在创建虚拟对象之前剔除属性?

How to cull attributes before creating a virtus Object?

我的散列中的属性多于 Virtus 在其 class 中定义的属性。我想在实例化之前剔除 virtus 模型中的那些属性。

test_hash = {:x="stuff" , :y ="stuff2", :z="stuff3"}
def myObject
  include Virtus.model
  attribute :x, String
  attribute :y, String
end

myObject.new(test_hash)

这失败了 NoMethodError: undefined method 'z=' 我只是希望它默默地丢弃 z 并仍然创建对象。

我尝试覆盖初始化方法并插入剔除方法,但这似乎没有用。显然,质量分配属性在对象创建过程中通过不同的途径?

剔除这些属性的最佳方法?

似乎可以在 1.0.5 上正常工作;您使用的是哪个版本?

irb(main):001:0> require 'virtus'
=> true
irb(main):002:0> class MyObject
irb(main):003:1>   include Virtus.model
irb(main):004:1>   attribute :x, String
irb(main):005:1>   attribute :y, String
irb(main):006:1> end
=> MyObject
irb(main):007:0> hash = { x: 'x', y: 'y', z: 'z' }
=> {:x=>"x", :y=>"y", :z=>"z"}
irb(main):008:0> MyObject.new hash
=> #<MyObject:0x007ff0e3e8d9e8 @x="x", @y="y">