I need to be able to create a Virtus based object that takes in a Hash or a String. If its a Hash, then normal behavior is perfect. If it's a plain String, then i need to convert it to {'id' => "STRING"}. At this time, i'm not sure how / where to override the initialize method to perform this function. Or maybe there's a different way. Your expertise is greatly appreciated.
class Contact
include Virtus.model
attribute :id, String
end
class Account
include Virtus.model
attribute :id, String
attribute :contact, Contact
attribute :name, String
end
account = Account.new("1234")
account.id #>1234
# and still work like this
account = Account.new(id: '1234', contact: '123456', name: 'Bob Jones')
account.id #>1234
account.contact.id #>123456
account.name #>Bob Jones
Sample Data
{'id' => '1234', 'contact' => '123456', 'name' => 'Bob Jones'}
So between both Contact and Account. I need them to be able to initialized with a String, which populates the @id param.
Note: This is for edification purposes only and may have unintended consequences that might be difficult to debug.
You can override the
Virtus::InstanceMethods::Constructorlike so if you really want to:Then include it as needed
Now you can either pass the options positional to the definition of attributes (e.g.
Account.new(id,contact)) or as aHash.Example:
You could monkey patch
Virtus::InstanceMethods::Constructorto perform the same but I am not a big supporter of this philosophy as it could add confusion to other developers where as the module inclusion offers granularity and clarity.Update