Vlad Cenan Vlad Cenan - 3 months ago 11
Ruby Question

Define a local variable or method in a script

I'm new to ruby and I'm trying to re-structure my script which adds some servers to zabbix monitor etc.The issue that I'm facing is below:

zbx = ZabbixApi.connect(
:url => 'http://zabbixserver.net/zabbix/api_jsonrpc.php',
:user => 'admin',
:password => 'admin'
)

def createtemplate
zbx.templates.create(
:host => "RealDoc MS Template",
:groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
) ..../will create Items, graphs etc...
end

if templateid.empty?
createtemplate
else
puts "Template Exists"
end


When is accessing the createtemplate method it's throwing the following error: undefined local variable or method `zbx' for main:Object (NameError)

Answer

well zbx isn't in scope, as it isn't a global. you have a couple options.

either pass it into the method

 def createtemplate(zbx)
   zbx.templates.create(
     :host => "RealDoc MS Template",
     :groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
    )  ..../will create Items, graphs etc...
 end

 if templateid.empty?
    createtemplate zbx
 else
     puts "Template Exists"
 en

or you can make it global with a $.

$zbx = ZabbixApi.connect(
  :url => 'http://zabbixserver.net/zabbix/api_jsonrpc.php',
  :user => 'admin',
  :password => 'admin'
)

def createtemplate
   $zbx.templates.create(
     :host => "RealDoc MS Template",
     :groups => [:groupid => zbx.hostgroups.get_id(:name => "RealDoc")]
    )  ..../will create Items, graphs etc...
 end

 if templateid.empty?
    createtemplate
 else
     puts "Template Exists"
 end

I would do the first option, as global variables should be used sparingly, but in such a short script it probably doesn't matter that much..

Comments