Module: ThingTank::SharedMethods

Included in:
ThingTank, Character
Defined in:
lib/thingtank/shared_methods.rb

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



3
4
5
6
7
8
9
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
# File 'lib/thingtank/shared_methods.rb', line 3

def self.included(klass)
  klass.class_eval do

    # only export the changed properties
    def changed_to_character_hash(exclude_characters=false)
      skips = skip_keys(exclude_characters)
      hsh = {}
      changes.each do |key,arr|
        _old, _new = arr
        unless skips.include? key
          hsh[key] = _new
        end
      end
      hsh
    end

    def skip_keys(exclude_characters=false)
      arr = %w|_id _rev type update_me updated_at created_at|
      arr << 'characters' if exclude_characters
      arr
    end

    def to_character_hash(exclude_characters=false)
      hsh = to_hash
      skip_keys(exclude_characters).each{ |k|  hsh.delete k }
      hsh
    end

    def nth_character(klass, key, n, &code)
      orig_character = to_character(klass, key)
      list = [orig_character].flatten
      character = case n
      when :last
        list.last
      when :first
        list.first
      else
        list[n]
      end
      if code
        code.call(character)
        character.flush_to_doc
      end
      if orig_character.is_a?(Array)
        character._character_doc.dependencies.refresh_parent
      end
      character
    end

    def last_character(klass, key, &code)
      nth_character(klass, key, :last, &code)
    end

    def first_character(klass, key, &code)
      nth_character(klass, key, :first, &code)
    end

  end
end