lib/toy/querying.rb in toystore-0.9.0 vs lib/toy/querying.rb in toystore-0.10.0
- old
+ new
@@ -2,11 +2,13 @@
module Querying
extend ActiveSupport::Concern
module ClassMethods
def get(id)
- load(id, adapter.read(id))
+ if (attrs = adapter.read(id))
+ load(id, attrs)
+ end
end
def get!(id)
get(id) || raise(Toy::NotFound.new(id))
end
@@ -27,10 +29,25 @@
adapter.key?(id)
end
alias :has_key? :key?
def load(id, attrs)
- attrs && allocate.initialize_from_database(attrs.update('id' => id))
+ attrs ||= {}
+ instance = constant_from_attrs(attrs).allocate
+ instance.initialize_from_database(attrs.update('id' => id))
end
+
+ def constant_from_attrs(attrs)
+ return self if attrs.nil?
+
+ type = attrs[:type] || attrs['type']
+
+ return self if type.nil?
+
+ type.constantize
+ rescue NameError
+ self
+ end
+ private :constant_from_attrs
end
end
-end
\ No newline at end of file
+end