[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: string -> symbol, redux

Brian Candler

5/23/2007 9:23:00 AM

On Wed, May 23, 2007 at 12:05:31PM +0900, mike.cahill@comcast.net 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.