summaryrefslogtreecommitdiffstats
path: root/lib/puppet/rails/resource.rb
blob: 6656c24509f180d032b684e4ae2daecebc26aad5 (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
require 'puppet'
require 'puppet/rails/external/tagging/init'
require 'puppet/rails/param_name'
require 'puppet/util/rails/collection_merger'

class Puppet::Rails::Resource < ActiveRecord::Base
    include Puppet::Util::CollectionMerger

    has_many :param_values, :through => :param_names
    has_many :param_names, :dependent => :destroy
    belongs_to :source_file
    belongs_to :host

    acts_as_taggable
    
    def tags=(tags)
        tags.each do |tag|   
            self.tag_with tag
        end
    end

    def file=(file)
       self.source_file = Puppet::Rails::SourceFile.new(:filename => file)
    end

    def [](param)
        return super || parameter(param)
    end

    def parameter(param)
        if pn = param_names.find_by_name(param)
            if pv = pn.param_values.find(:first)
                return pv.value
            else
                return nil
            end
        end
    end

    def parameters
        hash = {}
        self.param_values.find(:all).each do |pvalue|
            pname = pvalue.param_name.name
            hash.store(pname, pvalue.value)
        end
        return hash
    end

    def ref
        "%s[%s]" % [self[:restype], self[:title]]
    end

    # Convert our object to a resource.  Do not retain whether the object
    # is exported, though, since that would cause it to get stripped
    # from the configuration.
    def to_resource(scope)
        hash = self.attributes
        hash["type"] = hash["restype"]
        hash.delete("restype")

        # FIXME At some point, we're going to want to retain this information
        # for logging and auditing.
        hash.delete("host_id")
        hash.delete("updated_at")
        hash.delete("source_file_id")
        hash.delete("id")
        hash.each do |p, v|
            hash.delete(p) if v.nil?
        end
        hash[:scope] = scope
        hash[:source] = scope.source
        obj = Puppet::Parser::Resource.new(hash)
        self.param_names.each do |pname|
            obj.set(pname.to_resourceparam(scope.source))
        end

        # Store the ID, so we can check if we're re-collecting the same resource.
        obj.rails_id = self.id

        return obj
    end
end

# $Id$