Created
October 11, 2011 02:02
-
-
Save d11wtq/1277089 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "virtus" | |
class JsonModel | |
include Virtus | |
end | |
class Node < Virtus::Attribute::Object | |
attr_reader :type | |
class << self | |
def [](type) | |
raise ArgumentError, "Child nodes may only be other JsonModel classes" unless type <= JsonModel | |
@generated_class_map ||= {} | |
@generated_class_map[type] ||= Class.new(self) do | |
default lambda { |m, a| type.new } | |
define_method :type do | |
type | |
end | |
define_method :coerce do |value| | |
value.kind_of?(Hash) ? type.new(value) : value | |
end | |
end | |
end | |
end | |
end | |
class ChildModel < JsonModel | |
end | |
class ParentModel < JsonModel | |
attribute :child, Node[ChildModel] | |
attribute :string, String | |
end | |
# This should be String, but it's a descendant of Node?? | |
puts ParentModel.attributes[:string].class.ancestors.inspect |
I'll file a bug in the interim
The bug for this is in solnic/virtus#26 .. and it is now resolved.
(Added for posterity for anyone that comes across this in google)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hah, good work stumbling upon this!
Yup, my colleague Paul figured out it boiled down to simply having any anonymous class created from Node. I'd found my way into the TypeLookup code, but no further. DataMapper does a similar thing with Flags, but that code works correctly.
So I guess as an immediate workaround, we could use the boxed type as the primitive, thus forcing them to be unique, though this is clearly not a long term solution. I'll see what I can fathom out with a bit of hacking soon.