lib/squares/base.rb in squares-0.3.0 vs lib/squares/base.rb in squares-0.3.1
- old
+ new
@@ -1,18 +1,18 @@
module Squares
class Base
attr_accessor :id
def initialize *args
- apply *args
+ build_instance *args
trigger :after_initialize
end
def save
trigger :before_save
@_changed = false
- store[@id] = Marshal.dump self.dup
+ store[@id] = serialize
trigger :after_save
nil
end
def delete
@@ -50,28 +50,43 @@
def properties
self.class.properties
end
+ def to_json(key_name = :id)
+ to_hash(key_name).to_json
+ end
+
def to_h(key_name = :id)
- h = { key_name => id }
- properties.each do |property|
- h[property] = self.send(property)
+ { :type => self.class.name, key_name => id }.tap do |h|
+ properties.each do |property|
+ h[property] = self[property]
+ end
end
- h
end
+ alias_method :to_hash, :to_h
def valid_property? property
self.class.valid_property? property
end
def defaults
self.class.defaults
end
+ def serialize
+ serializers.inject(self.dup) do |memo, serializer|
+ serializer.dump memo
+ end
+ end
+
private
+ def serializers
+ self.class.serializers
+ end
+
def trigger hook_name
return if @hook_callback_in_progress
hooks = self.class.hooks
if hooks && hooks[hook_name]
hooks[hook_name].each do |hook|
@@ -86,11 +101,11 @@
! properties.detect do |property|
self.send(property) != other.send(property)
end
end
- def apply *args
+ def build_instance *args
@id, values = *args
values_hash = values.to_h
properties_sorted_by_defaults.each do |property|
value = values_hash.has_key?(property) ? values_hash[property] : default_for(property)
set_property property, value
@@ -139,13 +154,17 @@
#############
class << self
include Enumerable
+ def serializers
+ [Marshal]
+ end
+
def [] id
if item = store[id]
- Marshal.restore(item).tap do |item|
+ deserialize(item).tap do |item|
item.instance_eval 'trigger :after_find'
end
end
end
alias_method :find, :[]
@@ -180,11 +199,11 @@
def keys
store.keys
end
def values
- store.values.map{ |i| Marshal.restore i }
+ store.values.map{ |i| deserialize i }
end
def valid_property? property
!!normalize_property(property)
end
@@ -271,11 +290,11 @@
def store
@store ||= {}
end
def models
- @_models.uniq.sort { |a,b| a.to_s <=> b.to_s }
+ (@_models || []).uniq.sort { |a,b| a.to_s <=> b.to_s }
end
### hooks
def hooks
@_hooks
@@ -324,9 +343,15 @@
end
def inherited(subclass)
@_models ||= []
@_models << subclass
+ end
+
+ def deserialize item
+ serializers.reverse.inject(item) do |memo, serializer|
+ serializer.restore item
+ end
end
end
end
end