1

我的哈希中的属性比 Virtus 在它的类中定义的要多。我想在实例化之前在 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 并仍然创建对象。

我尝试覆盖初始化方法并插入一个剔除方法,但这似乎不起作用。显然,在对象创建期间大量分配属性会通过不同的途径?

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

4

1 回答 1

1

似乎在 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">
于 2016-03-21T04:35:22.467 回答