File: has_many_proxy.rb

package info (click to toggle)
ruby-jira 2.1.5-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 968 kB
  • sloc: ruby: 5,125; makefile: 12
file content (42 lines) | stat: -rw-r--r-- 1,438 bytes parent folder | download | duplicates (2)
1
2
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
#
# Whenever a collection from a has_many relationship is accessed, an instance
# of this class is returned.  This instance wraps the Array of instances in
# the collection with an extra build method, which allows new instances to be
# built on the collection with the correct properties.
#
# In practice, instances of this class behave exactly like an Array.
#
class JIRA::HasManyProxy
  attr_reader :target_class, :parent
  attr_accessor :collection

  def initialize(parent, target_class, collection = [])
    @parent       = parent
    @target_class = target_class
    @collection   = collection
  end

  # Builds an instance of this class with the correct parent.
  # For example, issue.comments.build(attrs) will initialize a
  # comment as follows:
  #
  #   JIRA::Resource::Comment.new(issue.client,
  #                               :attrs => attrs,
  #                               :issue => issue)
  def build(attrs = {})
    resource = target_class.new(parent.client, :attrs => attrs, parent.to_sym => parent)
    collection << resource
    resource
  end

  # Forces an HTTP request to fetch all instances of the target class that
  # are associated with the parent
  def all
    target_class.all(parent.client, parent.to_sym => parent)
  end

  # Delegate any missing methods to the collection that this proxy wraps
  def method_missing(method_name, *args, &block)
    collection.send(method_name, *args, &block)
  end
end