Class: Toy::Proxies::List

Inherits:
Proxy show all
Defined in:
lib/toy/proxies/list.rb

Instance Method Summary collapse

Methods inherited from Proxy

#assert_type, #each, #eql?, #initialize, #proxy_owner, #proxy_respond_to?, #respond_to?, #target

Constructor Details

This class inherits a constructor from Toy::Proxies::Proxy

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Toy::Proxies::Proxy

Instance Method Details

#concat(*records) ⇒ Object



27
28
29
30
31
# File 'lib/toy/proxies/list.rb', line 27

def concat(*records)
  records = records.flatten
  records.map { |record| assert_type(record) }
  self.target_ids = target_ids + records
end

#create(attrs = {}) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/toy/proxies/list.rb', line 38

def create(attrs={})
  if proxy_options[:inverse_of]
    attrs.update(:"#{proxy_options[:inverse_of]}_id" => proxy_owner.id)
  end
  proxy_class.create(attrs).tap do |record|
    if record.persisted?
      proxy_owner.reload
      push(record)
      proxy_owner.save
      reset
    end
  end
end

#destroy(*args, &block) ⇒ Object



52
53
54
55
56
57
58
59
# File 'lib/toy/proxies/list.rb', line 52

def destroy(*args, &block)
  ids = block_given? ? target.select(&block).map(&:id) : args.flatten
  proxy_class.destroy(*ids)
  proxy_owner.reload
  self.target_ids = target_ids - ids
  proxy_owner.save
  reset
end

#destroy_allObject



61
62
63
64
65
66
# File 'lib/toy/proxies/list.rb', line 61

def destroy_all
  proxy_class.destroy(*target_ids)
  self.target_ids = []
  proxy_owner.save
  reset
end

#get(id) ⇒ Object



6
7
8
9
10
# File 'lib/toy/proxies/list.rb', line 6

def get(id)
  if target_ids.include?(id)
    proxy_class.get(id)
  end
end

#get!(id) ⇒ Object



12
13
14
# File 'lib/toy/proxies/list.rb', line 12

def get!(id)
  get(id) || raise(Toy::NotFound.new(id))
end

#include?(record) ⇒ Boolean

Returns:



16
17
18
19
# File 'lib/toy/proxies/list.rb', line 16

def include?(record)
  return false if record.nil?
  target_ids.include?(record.id)
end

#push(record) ⇒ Object Also known as: <<



21
22
23
24
# File 'lib/toy/proxies/list.rb', line 21

def push(record)
  assert_type(record)
  self.target_ids = target_ids + [record]
end

#replace(records) ⇒ Object



33
34
35
36
# File 'lib/toy/proxies/list.rb', line 33

def replace(records)
  reset
  self.target_ids = records
end

#resetObject



68
69
70
# File 'lib/toy/proxies/list.rb', line 68

def reset
  @target = nil
end