Sha256: f36008bc30a8bde3277bc99bfff066a93eecd13d3e08e3521dad8d030e78b575

Contents?: true

Size: 1.46 KB

Versions: 43

Compression:

Stored size: 1.46 KB

Contents

module RunCommand
	
	def command_output
		unless !supported?
			puts "Running `#{command_line}`..." if CityWatch.debug?
			`#{command_line}`
		else
			puts "Command not present: #{options[:command]} (Skipping)" if CityWatch.debug?
			""
		end
	end
	
	def supported?
		`which #{options[:command]}` != ""
	end
	
	def command_line
		@command ||= "#{options[:command]} #{command_line_opts}#{options[:grep] && " | fgrep #{options[:grep]}"}"
	end
	
	def command_line_opts
		options.inject([]) do |acc,(k,v)|
			acc << "-#{k} #{v}" unless [:command, :grep].include?(k)
			acc
		end.join(" ")
	end
	
	def options
		@opts ||= self.class.options
	end
	
	def set_opts(opts={})
		@opts = self.class.options.merge(opts)
		@command = nil
	end
	
	def data
		headers = false
		output = []
		command_output.split("\n").map {|line| v = line.split("\s"); v.shift; v }.each do |line|
			if !headers
				headers = line.map {|hdr| hdr.downcase.to_sym}
				next
			end
			next unless headers
			pkt = {}
			line.each_with_index do |itm,idx|
				pkt[headers[idx]] = itm
			end
			output << pkt
		end
		output
	end
	
	module ClassMethods
		
		def set_opts(opts={})
			@opts = options.merge(opts)
			@command = nil
		end
		
		def options
			@opts ||= {}
		end
		
		def command(cmd,opts={})
			options[:command] = cmd
			set_opts opts
		end
		
		def grep(str)
			options[:grep] = str
		end
		
		def data
			new.data
		end
		
	end
	
	def self.included(base)
		base.extend(ClassMethods)
		Commands.register(base)
	end
	
end

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
city-watch-0.3.2 lib/city_watch/util/run_command.rb
city-watch-0.3.1 lib/city_watch/util/run_command.rb
city-watch-0.3.0 lib/city_watch/util/run_command.rb