Class: SerializableDecorator

Inherits:
Delegator
  • Object
show all
Defined in:
lib/serializable_decorator.rb

Constant Summary collapse

@@decorator_objects =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ SerializableDecorator

Returns a new instance of SerializableDecorator.



21
22
23
24
25
# File 'lib/serializable_decorator.rb', line 21

def initialize(obj)
  super
  SerializableDecorator.change_obj(self, obj)
  ObjectSpace.define_finalizer( self, self.class.clear_obj(object_id) )
end

Class Method Details

.change_obj(decorator, obj) ⇒ Object



9
10
11
# File 'lib/serializable_decorator.rb', line 9

def self.change_obj(decorator, obj)
  @@decorator_objects[decorator.object_id] = obj
end

.clear_obj(object_id) ⇒ Object



17
18
19
# File 'lib/serializable_decorator.rb', line 17

def self.clear_obj(object_id)
  proc { @@decorator_objects.delete(object_id) }
end

.get_obj(decorator) ⇒ Object



13
14
15
# File 'lib/serializable_decorator.rb', line 13

def self.get_obj(decorator)
  @@decorator_objects[decorator.object_id]
end

Instance Method Details

#__getobj__Object



27
28
29
# File 'lib/serializable_decorator.rb', line 27

def __getobj__
  SerializableDecorator.get_obj(self)
end

#__setobj__(obj) ⇒ Object



31
32
33
# File 'lib/serializable_decorator.rb', line 31

def __setobj__(obj)
  SerializableDecorator.change_obj(self, obj)
end

#as_jsonObject



47
48
49
50
51
52
53
54
55
# File 'lib/serializable_decorator.rb', line 47

def as_json
  if __getobj__.respond_to?(:as_json) then
    delegator_instance_vars = Delegator.instance_method(:instance_variables).bind(self).call
    json_hash = Hash[delegator_instance_vars.map { | name | [name.to_s[1..-1], instance_variable_get(name) ] } ]
    json_hash.merge!(__getobj__.as_json)
  else
    instance_values
  end
end

#instance_valuesObject



39
40
41
# File 'lib/serializable_decorator.rb', line 39

def instance_values
  Hash[instance_variables.map { | name | [ name.to_s[1..-1], instance_variable_get(name) ] } ]
end

#instance_variable_get(name) ⇒ Object



43
44
45
# File 'lib/serializable_decorator.rb', line 43

def instance_variable_get(name)
  __getobj__.instance_variable_get(name) || super
end

#instance_variablesObject



35
36
37
# File 'lib/serializable_decorator.rb', line 35

def instance_variables
  super + __getobj__.instance_variables
end

#to_jsonObject



57
58
59
# File 'lib/serializable_decorator.rb', line 57

def to_json
  as_json.to_json
end