Module: Packable::ClassMethods
- Defined in:
- lib/musicality/packable.rb
Instance Method Summary collapse
- #init_params ⇒ Object
- #pack_specially(sym, val) ⇒ Object
- #packs_specially?(sym) ⇒ Boolean
- #special_packing(sym, &block) ⇒ Object
- #special_unpacking(sym, &block) ⇒ Object
- #unpack(packing) ⇒ Object
- #unpack_specially(sym, val) ⇒ Object
- #unpacks_specially?(sym) ⇒ Boolean
Instance Method Details
#init_params ⇒ Object
58 59 60 61 |
# File 'lib/musicality/packable.rb', line 58 def init_params params = instance_method(:initialize).parameters Hash[ params.map {|pair| pair.reverse } ] end |
#pack_specially(sym, val) ⇒ Object
79 80 81 |
# File 'lib/musicality/packable.rb', line 79 def pack_specially sym, val class_variable_get(:@@special_packing)[sym].call(val) end |
#packs_specially?(sym) ⇒ Boolean
71 72 73 |
# File 'lib/musicality/packable.rb', line 71 def packs_specially? sym class_variable_get(:@@special_packing).has_key?(sym) end |
#special_packing(sym, &block) ⇒ Object
63 64 65 |
# File 'lib/musicality/packable.rb', line 63 def special_packing sym, &block class_variable_get(:@@special_packing)[sym] = block end |
#special_unpacking(sym, &block) ⇒ Object
67 68 69 |
# File 'lib/musicality/packable.rb', line 67 def special_unpacking sym, &block class_variable_get(:@@special_unpacking)[sym] = block end |
#unpack(packing) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/musicality/packable.rb', line 13 def unpack packing args = [] kwargs = {} init_params.each do |name,type| if (type == :req || type == :keyreq) && !packing.has_key?(name) raise ArgumentError, "Packing does not have required key #{name}" end val = packing[name] if type == :keyrest raise "Expected this to be a Hash" unless val.is_a? Hash end val2 = if unpacks_specially?(name) unpack_specially(name,val) else Packable.unpack_val(val) end case type when :req, :opt args.push val2 when :key, :keyreq kwargs[name] = val2 when :keyrest kwargs.merge!(val2) end end if args.any? if kwargs.any? obj = new(*args,**kwargs) else obj = new(*args) end elsif kwargs.any? obj = new(**kwargs) else obj = new end block_given? ? yield(obj) : obj end |
#unpack_specially(sym, val) ⇒ Object
83 84 85 |
# File 'lib/musicality/packable.rb', line 83 def unpack_specially sym, val class_variable_get(:@@special_unpacking)[sym].call(val) end |
#unpacks_specially?(sym) ⇒ Boolean
75 76 77 |
# File 'lib/musicality/packable.rb', line 75 def unpacks_specially? sym class_variable_get(:@@special_unpacking).has_key?(sym) end |