Module: Packable

Overview

Requires that an including class can be instantiated entirely by keyword args that map these symbols to values

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

PACKED_CLASS_KEY =
:packed_class

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



6
7
8
9
10
# File 'lib/musicality/packable.rb', line 6

def self.included(base)
  base.extend(ClassMethods)
  base.class_variable_set(:@@special_packing, {})
  base.class_variable_set(:@@special_unpacking, {})
end

.pack_val(val) ⇒ Object



132
133
134
135
136
137
138
139
140
141
142
# File 'lib/musicality/packable.rb', line 132

def pack_val val
  if val.is_a?(Packable)
    val.pack
  elsif val.is_a? Array
    val.map {|v| pack_val v}
  elsif val.is_a? Hash
    Hash[ val.map {|k,v| [ Packable.pack_val(k), Packable.pack_val(v) ]} ]
  else
    val
  end
end

.recover_class(klass_str) ⇒ Object



110
111
112
# File 'lib/musicality/packable.rb', line 110

def recover_class klass_str
  Kernel.const_get(klass_str)
end

.unpack_val(val) ⇒ Object



117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/musicality/packable.rb', line 117

def unpack_val val
  if val.is_a? Array
    val.map {|v| Packable.unpack_val v}
  elsif val.is_a? Hash
    if val.packed_class?
      val.unpack
    else
      Hash[ val.map {|k,v| [ Packable.unpack_val(k), Packable.unpack_val(v) ]} ]
    end
  else
    val
  end
end

Instance Method Details

#class_strObject



92
93
94
# File 'lib/musicality/packable.rb', line 92

def class_str
  self.class.to_s
end

#init_paramsObject



88
89
90
# File 'lib/musicality/packable.rb', line 88

def init_params
  self.class.init_params
end

#packObject



96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/musicality/packable.rb', line 96

def pack
  packing = { PACKED_CLASS_KEY => class_str }
  init_params.keys.each do |name|
    val = self.send(name)
    val2 = if self.class.packs_specially?(name)
      self.class.pack_specially(name,val)
    else
      Packable.pack_val(val)
    end
    packing[name] = val2
  end
  packing
end