ruby-on-railsrubyvirtus

How to cull attributes before creating a virtus Object?


I have more attributes in my hash than Virtus has defined in it's class. I want to cull those attributes inside the virtus model before instantiating it.

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

myObject.new(test_hash)

This fails with a NoMethodError: undefined method 'z=' I just want it to silently discard z and still create the object.

I tried overriding the initialize method and inserting a culling method, but that didn't appear to work. Apparently mass assigning attributes goes through a different pathway during object create?

Best way to go about culling these attributes?


Solution

  • Seems to work okay with 1.0.5; which version are you on?

    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">