String -> symbol, redux


#1

ok… i’m still not getting it. i want the elegant way to do the last
two lines in my Server initialize. and please be kind - i’m just a
programming hack, not a professional. =)


module Toc44_all

def toc44_all_system(cmd)
the_pipe=IO.popen(cmd)
res = the_pipe.read
the_pipe.close
return res
end

def toc44_all_twoargs(a,b)
return “#{a} - #{b}”
end

end

module Toc44_fw
def toc44_fw_justme(arg)
return “returning #{arg}”
end
end

class Server
def initialize
my_type = “fw”
extend eval(“Toc44_all”)
extend eval(“Toc44_#{my_type}”)
eval(“def toc44_fw_system(args); return toc44_all_system(args);end”)
eval(“def toc44_fw_twoargs(*args); return
toc44_all_twoargs(*args);end”)
end
end

svr = Server.new
puts svr.toc44_fw_justme(“howdy”)
puts svr.toc44_fw_system(“dir”)
puts svr.toc44_fw_twoargs(“hi”,“there”)


#2

On Wed, May 23, 2007 at 12:05:31PM +0900, removed_email_address@domain.invalid wrote:

ok… i’m still not getting it. i want the elegant way to do the last two lines in my Server initialize. and please be kind - i’m just a programming hack, not a professional. =)

class Server
def initialize
my_type = “fw”
extend eval(“Toc44_all”)
extend eval(“Toc44_#{my_type}”)
eval(“def toc44_fw_system(args); return toc44_all_system(args);end”)
eval(“def toc44_fw_twoargs(*args); return toc44_all_twoargs(*args);end”)
end
end

Well,

class Server
def initialize
my_type = “fw”
extend Toc44_all
extend Object.const_get(“Toc44_#{my_type}”)
class <<self
alias :toc44_fw_system :toc44_all_system
alias :toc44_fw_twoargs :toc44_all_twoargs
end
end
end

I’m not sure exactly what you’re trying to achieve, but there’s almost
certainly a better way of doing it.

For example, if the idea is to have multiple Server objects, with
different
behaviour for certain groups of devices, I’d say have a separate class
for
each type of server and instantiate the correct one dynamically.

module Server
class Firewall
def system
puts “Howdy”
end
end

class Router
def system
puts “Flurble”
end
end
end

klass = “Firewall”
Server.const_get(klass).new.system

klass = “Router”
Server.const_get(klass).new.system

Then any code which is common to Firewall and Router classes can be put
in a
module (i.e. “include Foo” inside each class), or you can make them
subclasses of a common ancestor class.

Sticking them inside a module namespace (‘Server’ in the above) prevents
you
accidentally instantiating any object outside of that namespace. For
example, if you have a knotted string reader and writer, then
Server.const_get(“String”).new
can only create an instance of Server::String, not a String.

HTH,

Brian.