summaryrefslogtreecommitdiffstats
path: root/lib/puppet/rails/host.rb
blob: 3736c407d88e94baa4aa75a60d7a6badb90f00fa (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
require 'puppet/rails/rails_object'

RailsObject = Puppet::Rails::RailsObject
class Puppet::Rails::Host < ActiveRecord::Base
    Host = self
    serialize :facts, Hash
    serialize :classes, Array

    has_many :rails_objects, :dependent => :delete_all

    # If the host already exists, get rid of its objects
    def self.clean(host)
        if obj = Host.find_by_name(host)
            obj.rails_objects.clear
            return obj
        else
            return nil
        end
    end

    # Store our host in the database.
    def self.store(hash)
        name = hash[:host] || "localhost"
        ip = hash[:ip] || "127.0.0.1"
        facts = hash[:facts] || {}
        objects = hash[:objects]

        unless objects
            raise ArgumentError, "You must pass objects"
        end

        hostargs = {
            :name => name,
            :ip => ip,
            :facts => facts,
            :classes => objects.classes
        }

        objects = objects.flatten

        host = nil
        if host = clean(name)
            [:name, :facts, :classes].each do |param|
                unless host[param] == hostargs[param]
                    host[param] = hostargs[param]
                end
            end
        else
            host = Host.new(hostargs)
        end

        host.addobjects(objects)

        host.save

        return host
    end

    # Add all of our RailsObjects
    def addobjects(objects)
        objects.each do |tobj|
            params = {}
            tobj.each do |p,v| params[p] = v end

            args = {:ptype => tobj.type, :name => tobj.name}
            [:tags, :file, :line, :collectable].each do |param|
                if val = tobj.send(param)
                    args[param] = val
                end
            end

            robj = RailsObject.new(args)
            self.rails_objects << robj

            robj.addparams(params)
        end
    end
end

# $Id$