Module: ThingTank::InstanceMethods

Included in:
ThingTank
Defined in:
lib/thingtank/instance_methods.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



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
62
# File 'lib/thingtank/instance_methods.rb', line 5

def self.included(base)

  base.class_eval do

    def initialize(*args)
      super
      @dependencies = ThingTank::Dependencies.new(self)
    end

    def dependencies
      @dependencies
    end

    def to_sym
      if id = self.id
        "!##{id}"
      else
        nil
      end
    end

    # it is not possible for whatever reason to overwrite valid?, check it out!
    #def valid?
    #  invalid_characters.empty? && self.errors.messages.empty?
    #end

    # we don't do this. there is no proper way to update all given characters
    # one must not rely on a character properties after the doc has been manipulated
    # use Character#reload to get the latest from the doc object to the character and Character#reload! to reload the doc from the database and reload the character then
    #def reload
    #  super
    #  @dependencies.reload_character_objects()
    #end

    def first(key)
      [self[key.to_s]].flatten.last
    end
  
    def last(key)
      [self[key.to_s]].flatten.first
    end

    # export a property to its own document and replaces the original reference with the doc["_id"]
    def export(property)
      raise ArgumentError, "doc.database required for extracting" unless database
      new_doc = self[property.to_s]
      raise ArgumentError, "#{new_doc.inspect} is no CouchRest::Document or Hash" unless new_doc.is_a?(CouchRest::Document) or new_doc.is_a?(Hash)
      result = database.save_doc new_doc
      if result['ok']
        self["#{property}_id"] = result["id"]
        self[property.to_s] = nil
      end
      result['ok']
    end

  end

end