Class: Packable::Packers

Inherits:
Hash
  • Object
show all
Defined in:
lib/packable/packers.rb

Overview

Packers for any packable class.

Constant Summary collapse

SPECIAL =
[:default, :merge_all].freeze
@@packers_for_class =
Hash.new{|h, klass| h[klass] = Packers.new(klass)}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Packers

:nodoc:



24
25
26
# File 'lib/packable/packers.rb', line 24

def initialize(klass) #:nodoc:
  @klass = klass
end

Class Method Details

.for(klass) ⇒ Object

Returns the configuration for the given klass.



47
48
49
# File 'lib/packable/packers.rb', line 47

def self.for(klass)
  @@packers_for_class[klass]
end

.to_class_option_list(*arg) ⇒ Object

:nodoc:



51
52
53
54
55
56
57
58
59
60
61
# File 'lib/packable/packers.rb', line 51

def self.to_class_option_list(*arg) #:nodoc:
  r = []
  until arg.empty? do
    k, options = original = arg.shift
    k, options = global_lookup(k) if k.is_a? Symbol
    raise TypeError, "Expected a class or symbol: #{k.inspect}" unless k.instance_of? Class
    options ||= arg.first.is_a?(Hash) ? arg.shift.tap{|o| original = [original, o]} : :default
    r << [k, k.packers.finalize(options), original]
  end
  r
end

.to_object_option_list(*arg) ⇒ Object

:nodoc:



63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/packable/packers.rb', line 63

def self.to_object_option_list(*arg) #:nodoc:
  r=[]
  until arg.empty? do
    obj = arg.shift
    options = case arg.first
    when Hash, Symbol
      arg.shift
    else
      :default
    end
    r << [obj, obj.class.packers.finalize(options)]
  end
  r
end

Instance Method Details

#finalize(options) ⇒ Object

:nodoc:



39
40
41
42
# File 'lib/packable/packers.rb', line 39

def finalize(options) #:nodoc:
  options = lookup(options) while options.is_a? Symbol
  lookup(:merge_all).merge(options)
end

#lookup(key) ⇒ Object

:nodoc:



28
29
30
31
32
33
34
35
36
37
# File 'lib/packable/packers.rb', line 28

def lookup(key) #:nodoc:
  k = @klass
  begin
    if found = Packers.for(k)[key]
      return found
    end
    k = k.superclass
  end while k
  SPECIAL.include?(key) ? {} : raise("Unknown option #{key} for #{@klass}")
end

#set(key, options_or_shortcut = {}) ⇒ Object

Usage:

PackableClass.packers.set :shortcut, :option => value, ...
PackableClass.packers { |p| p.set...; p.set... }
PackableClass.packers.set :shortcut, :another_shortcut
PackableClass.packers.set :shortcut do |packer|
  packer.write{|io| io << self.something... }
  packer.read{|io| Whatever.new(io.read(...)) }
end


15
16
17
18
19
20
21
22
# File 'lib/packable/packers.rb', line 15

def set(key, options_or_shortcut={})
  if block_given?
    packer = FilterCapture.new options_or_shortcut
    yield packer
  end
  self[key] = options_or_shortcut
  self
end