Module: UnderOs::UI::Wrap

Included in:
View
Defined in:
lib/under_os/ui/utils/wrap.rb

Overview

The raw -> abstraction wrapping code for UI::Views

Constant Summary collapse

INSTANCES_CACHE =
{}
RAW_WRAPS_MAP =
{}
WRAPS_TAGS_MAP =
{}

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



10
11
12
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/under_os/ui/utils/wrap.rb', line 10

def self.included(base)
  base.instance_eval do
    attr_accessor :_

    def self.wraps(raw_class, options={})
      RAW_WRAPS_MAP[self] = raw_class
      tag(options[:tag]) if options[:tag]
    end

    def self.tag(name)
      WRAPS_TAGS_MAP[name.to_s] = self
    end

    def self.new(options={}, *args, &block)
      return INSTANCES_CACHE[options] if INSTANCES_CACHE[options]

      if options.is_a?(UIView)
        klass = find_wrap_for(options.class)
        view  = options; options = args.shift || {}
      else
        klass = self
        view  = find_raw_class_for(self).alloc
        if view.class == UICollectionView
          view.initWithFrame([[0, 0], [0, 0]], collectionViewLayout: UICollectionViewFlowLayout.alloc.init)
        else
          view.initWithFrame([[0, 0], [0, 0]])
        end
      end

      return nil if ! klass

      klass.alloc.tap do |inst|
        INSTANCES_CACHE[inst._ = view] = inst
        inst.__send__ :initialize, options, *args, &block
      end
    end

    def self.rewrap(view, *args, &block)
      view = view._ if view.is_a?(UnderOs::UI::View)

      alloc.tap do |inst|
        INSTANCES_CACHE[inst._ = view] = inst
        inst.__send__ :initialize, *args, &block
      end
    end

    def self.find_wrap_for(raw_class)
      RAW_WRAPS_MAP.each do |wrap, raw|
        return wrap if raw == raw_class
      end

      return nil
    end

    def self.find_raw_class_for(wrap)
      while wrap
        return RAW_WRAPS_MAP[wrap] if RAW_WRAPS_MAP[wrap]
        wrap = wrap.superclass
      end
    end

    def self.wrap_for(raw_view)
      INSTANCES_CACHE[raw_view]
    end
  end
end