solnic / virtus

[DISCONTINUED ] Attributes on Steroids for Plain Old Ruby Objects
MIT License
3.77k stars 229 forks source link

How to find out attribute type? #243

Closed assembler closed 10 years ago

assembler commented 10 years ago

Given following:

class Product
  include Virtus.model
  attribute :price, Money
end

How to find out :price attribute type when nil is passed as value?

solnic commented 10 years ago

I'm sorry but I'm not sure if I understand :)

If you pass nil you will get nil. So the type will be nil.

assembler commented 10 years ago

I want to reflect on Product class and find out how the :price attribute is declared (as Money). I've tried with Product.attribute_set[:price], but it does not store reference to original type anywhere...

solnic commented 10 years ago

@assembler it should be Product.attribute_set[:price].primitive

assembler commented 10 years ago

It should, but it returns BasicObject

solnic commented 10 years ago

@assembler OK so, Money is what in your case? I suspect it's not a virtus model?

For embedded values virtus supports Struct, OpenStruct or a virtus model. If you use something else you need to do some tricks to make it work.

assembler commented 10 years ago

Money is just PORO. Well.. too bad, i'll see if I can find a workaround. Thanks

solnic commented 10 years ago

Virtus can't really tell how to instantiate an object by just looking at a class that's why it has to rely on a narrowed list of supported classes (Struct, OpenStruct and virtus models).

I do plan to improve this so that you'll be able to tell virtus what kind of classes you want to use for EmbeddedValues. It shouldn't be too hard. We can also just use a convention that arbitrary classes are treated like virtus models (meaning they accept a hash with attributes in the constructor) and call it a day.

mbj commented 10 years ago

@solnic JFYI: If you'd base the definition of virtus on a morpher algebra tree, you'd probably whitelist allowed attribute types via a primitive check. And you could reflect on that to recover the information.

solnic commented 10 years ago

@mbj I'm not sure if I always want to have a strict API with whitelisting. Feels like we could use a convention here for convenience and add a way to specify things explicitly.

mbj commented 10 years ago

@solnic Yeah. Virtus is not an input filter / transformer. I forgot :D