Class: RbRotate::Hook

Inherits:
Object show all
Defined in:
lib/rb.rotate/hook.rb

Overview

Represents hook.

Instance Method Summary collapse

Constructor Details

#initialize(name, arguments = nil, variables = { }) ⇒ Hook

Constructor.



40
41
42
43
44
# File 'lib/rb.rotate/hook.rb', line 40

def initialize(name, arguments = nil, variables = { })
    @name = name
    @arguments = self.parse_arguments(arguments)
    @variables = variables
end

Instance Method Details

#commandObject

Gets command.



126
127
128
129
130
131
# File 'lib/rb.rotate/hook.rb', line 126

def command
    command = Configuration::get.hooks[@name]
    if command.nil?
        raise Exception::new("Invalid hook: " << @name.to_s)
    end
end

#expand_arguments(command) ⇒ Object

Expands arguments.



87
88
89
90
91
92
# File 'lib/rb.rotate/hook.rb', line 87

def expand_arguments(command)
    @arguments.each_index do |i|
        arg = arguments[i]
        command.gsub! "%" << i.to_s, '"' << arg << '"'
    end            
end

#expand_variables(command) ⇒ Object

Expands variables.



98
99
100
101
102
# File 'lib/rb.rotate/hook.rb', line 98

def expand_variables(command)
    @variables.each_pair do |name, value|
        command.gsub! "%" << name, '"' << value << '"'
    end
end

#parse_arguments(string) ⇒ Object

Parses “arguments line”.



50
51
52
53
54
55
56
# File 'lib/rb.rotate/hook.rb', line 50

def parse_arguments(string)
    if not string.nil?
        string.split(":")
    else
        []
    end
end

#parse_result(result) ⇒ Object

Parses result.



108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'lib/rb.rotate/hook.rb', line 108

def parse_result(result)
    if result.strip.empty?
        return { }
    end

    result = YAML.load(result)
    if not result.kind_of? Hash
        result = { }
        log "Warning: result of hook '" << @name.to_s << "' wasn't YAML collection. Ignored."
    end
    
    return result
end

#run!Object

Runs hook.



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rb.rotate/hook.rb', line 62

def run!
    # Gets commans
    command = self.command.dup
    
    # Adds arguments
    self.expand_arguments(command)
    
    # Adds variables
    self.expand_variables(command)
    
    # Runs it
    pipe = ::File.popen(command)
    pipe.eof?       # ask for EOF causes waiting for terminating the pipe process
    
    result = pipe.read
    pipe.close()

    # Parses and returns result
    return self.parse_result(result)
end