Class: AlphaSimprini::Heap::Unpacker

Inherits:
Object
  • Object
show all
Defined in:
lib/alpha_simprini/packer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ Unpacker

Returns a new instance of Unpacker.



83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/alpha_simprini/packer.rb', line 83

def initialize(hash)
  @literals = hash[LITERALS]
  @classes = hash[CLASSES].inject({}) { |hash, (key, value)| hash[value] = key.constantize; hash }
  @packed_objects = hash[OBJECTS]
  @objects = {}
  @named_objects = {} 
  @packed_objects.each do |key, value|
    unpack_object(key)
  end
  hash[NAMED_OBJECTS].inject({}) do |hash, (key, value)|
    @named_objects[key] = @objects[value]
  end
end

Instance Attribute Details

#classesObject (readonly)

Returns the value of attribute classes.



81
82
83
# File 'lib/alpha_simprini/packer.rb', line 81

def classes
  @classes
end

#named_objectsObject (readonly)

Returns the value of attribute named_objects.



81
82
83
# File 'lib/alpha_simprini/packer.rb', line 81

def named_objects
  @named_objects
end

#objectsObject (readonly)

Returns the value of attribute objects.



81
82
83
# File 'lib/alpha_simprini/packer.rb', line 81

def objects
  @objects
end

Instance Method Details

#unpack_object(key) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/alpha_simprini/packer.rb', line 97

def unpack_object(key)
  return @objects[key] if @objects[key]
  value = @packed_objects[key]
  attributes = value[ATTRIBUTES]
    
  klass = @classes[value[CLASS]]
  if klass == Hash
    @objects[key] = attributes.inject({}) do |hash, (key, value)|
      hash[unpack_object(key)] = unpack_object(value)
      hash
    end
  elsif klass == Array
    @objects[key] = attributes.map{ |item| unpack_object(item) }
  elsif klass == Numeric
    @objects[key] = @literals[attributes]
  elsif klass == String
    @objects[key] = @literals[attributes]
  elsif klass == NilClass
    @objects[key] = attributes
  else
    object = @objects[key] = klass.allocate
    attributes.each do |name, key|
      object.instance_variable_set(unpack_object(name), unpack_object(key))
    end
    object
  end
end