summaryrefslogtreecommitdiffstats
path: root/lib/puppet/relationship.rb
blob: 2ffcd298f5279da0408d46a584c7c23b217072af (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env ruby

# subscriptions are permanent associations determining how different
# objects react to an event

require 'puppet/util/pson'

# This is Puppet's class for modeling edges in its configuration graph.
# It used to be a subclass of GRATR::Edge, but that class has weird hash
# overrides that dramatically slow down the graphing.
class Puppet::Relationship
  extend Puppet::Util::Pson
  attr_accessor :source, :target, :callback

  attr_reader :event

  def self.from_pson(pson)
    source = pson["source"]
    target = pson["target"]

    args = {}
    if event = pson["event"]
      args[:event] = event
    end
    if callback = pson["callback"]
      args[:callback] = callback
    end

    new(source, target, args)
  end

  def event=(event)
    raise ArgumentError, "You must pass a callback for non-NONE events" if event != :NONE and ! callback
    @event = event
  end

  def initialize(source, target, options = {})
    @source, @target = source, target

    options = (options || {}).inject({}) { |h,a| h[a[0].to_sym] = a[1]; h }
    [:callback, :event].each do |option|
      if value = options[option]
        send(option.to_s + "=", value)
      end
    end
  end

  # Does the passed event match our event?  This is where the meaning
  # of :NONE comes from.
  def match?(event)
    if self.event.nil? or event == :NONE or self.event == :NONE
      return false
    elsif self.event == :ALL_EVENTS or event == self.event
      return true
    else
      return false
    end
  end

  def label
    result = {}
    result[:callback] = callback if callback
    result[:event] = event if event
    result
  end

  def ref
    "#{source} => #{target}"
  end

  def inspect
    "{ #{source} => #{target} }"
  end

  def to_pson_data_hash
    data = {
      'source' => source.to_s,
      'target' => target.to_s
    }

    ["event", "callback"].each do |attr|
      next unless value = send(attr)
      data[attr] = value
    end
    data
  end

  def to_pson(*args)
    to_pson_data_hash.to_pson(*args)
  end

  def to_s
    ref
  end
end