Module: NanoStore::AssociationClassMethods

Included in:
Model
Defined in:
lib/nano_store/association.rb

Instance Method Summary collapse

Instance Method Details

#bag(name) ⇒ 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
# File 'lib/nano_store/association.rb', line 3

def bag(name)
  define_method(name) do |*args, &block|
    return _bags[name] if _bags[name]

    bag_key = self.info[name]
    if bag_key.nil?
      bag = Bag.bag
      self.info[name] = bag.key
    else
      bag = self.class.store.bagsWithKeysInArray([bag_key]).first
    end

    _bags[name] = bag

    bag
  end

  define_method((name + "=").to_sym) do |*args, &block|
    bag = self.send(name)
    case args[0]
    when Bag
      bag.clear
      bag += args[0].saved.values
    when Array
      bag.clear
      bag += args[0]
    else
      raise NanoStoreError, "Unexpected type assigned to bags, must be an Array or NanoStore::Bag, now: #{args[0].class}"
    end
    bag
  end
end