lib/game_machine/model.rb in game_machine-0.0.10 vs lib/game_machine/model.rb in game_machine-0.0.11
- old
+ new
@@ -16,10 +16,18 @@
def attribute(*args)
end
+ def delete(id)
+ commands.datastore.delete(id)
+ end
+
+ def delete!(id)
+ commands.datastore.delete!(id)
+ end
+
def find!(id)
scoped_id = scope_for(id)
if entity = Commands::Base.commands.datastore.get!(scoped_id)
from_entity(entity,:json_storage)
else
@@ -42,18 +50,11 @@
json = entity.json_storage.json
else
json = entity.json_entity.json
end
- attributes = JSON.parse(json)
- if klass = attributes.delete('klass')
- model = klass.constantize.new(attributes)
- model.id = model.unscoped_id
- model
- else
- raise "Unable to find klass attribute in #{attributes.inspect}"
- end
+ self.from_hash(JSON.parse(json))
end
def scope_for(id)
if id_scope
"#{id_scope}|#{id}"
@@ -67,12 +68,54 @@
end
def id_scope
@id_scope
end
+
+ def from_hash(attributes)
+ if klass = attributes.delete('klass')
+ attributes = attributes.each_with_object({}) do |(k, v), h|
+ if v.kind_of?(Hash)
+ h[k] = from_hash(v)
+ elsif v.kind_of?(Array)
+ h[k] = v.collect do |e|
+ e.kind_of?(Hash) ? from_hash(e) : e
+ end
+ else
+ h[k] = v
+ end
+ end
+ model = klass.constantize.new(attributes)
+ model.id = model.unscoped_id
+ model
+ else
+ OpenStruct.new(attributes)
+ end
+ end
end
+
+ def as_json
+ attributes['id'] = scoped_id
+ attributes.merge!(:klass => self.class.name)
+ attributes.each_with_object({}) do |(k, v), h|
+ if v.kind_of?(OpenStruct)
+ h[k] = v.as_json
+ elsif v.is_a?(Array)
+ h[k] = v.collect do |e|
+ e.kind_of?(OpenStruct) ? e.as_json : e
+ end
+ else
+ h[k] = v
+ end
+ end
+ end
+
+ def to_json
+ JSON.generate(as_json)
+ end
+
def attributes
self.marshal_dump
end
def scoped_id
@@ -89,15 +132,10 @@
else
id
end
end
- def to_json
- attributes['id'] = scoped_id
- JSON.dump(attributes.merge(:klass => self.class.name))
- end
-
def to_entity
MessageLib::Entity.new.set_id(scoped_id).set_json_entity(to_json_entity)
end
def to_json_entity
@@ -116,9 +154,17 @@
commands.datastore.put(to_storage_entity)
end
def save!
commands.datastore.put!(to_storage_entity)
+ end
+
+ def destroy
+ commands.datastore.delete(scoped_id)
+ end
+
+ def destroy!
+ commands.datastore.delete!(scoped_id)
end
end
end