summaryrefslogtreecommitdiffstats
path: root/lib/puppet/function.rb
blob: ec26e77accadc708b5e205c9e5238cf78f03a31a (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
#!/usr/local/bin/ruby -w

# $Id$

require 'puppet'
require 'puppet/fact'

module Puppet
    class Function
        @@functions = Hash.new(nil)

        #---------------------------------------------------------------
        def Function.[](name)
            return @@functions[name]
        end
        #---------------------------------------------------------------

        #---------------------------------------------------------------
        def call(args)
            @code.call(args)
        end
        #---------------------------------------------------------------

        #---------------------------------------------------------------
        # we want a 'proc' item instead of a block, so that we can return
        # from it
        def initialize(name,code)
            @name = name
            @code = code

            @@functions[name] = self
        end
        #---------------------------------------------------------------
    end

    Function.new("fact", proc { |fact|
        require 'puppet/fact'

        value = Fact[fact]
        debug("retrieved %s as %s" % [fact,value])
        value
    })

    Function.new("addfact", proc { |args|
        require 'puppet/fact'
        #debug("running addfact")

        hash = nil
        if args.is_a?(Array)
            hash = Hash[*args]
        end
        name = nil
        if hash.has_key?("name")
            name = hash["name"]
            hash.delete("name")
        elsif hash.has_key?(:name)
            name = hash[:name]
            hash.delete(:name)
        else
            raise "Functions must have names"
        end
        #debug("adding fact %s" % name)
        newfact = Fact.add(name) { |fact|
            hash.each { |key,value|
                method = key + "="
                fact.send(method,value)
            }
        }

        #debug("got fact %s" % newfact)
    })
end