From: Miss Elaine Eos Date: 2007-11-06T15:05:05+09:00 Subject: Re: [n00b] Reading a class-file and calling it at runtime. In article <3736dd30711042349n7225229dw4af74110f2a52048@mail.gmail.com>, sean.ohalpin@gmail.com wrote: > On 11/5/07, Miss Elaine Eos wrote: > > I'm trying to read-in a folder full of "plug-ins" and call each of them, > > in turn. Once I get the class-name, I do something like: > > > > require "#{PLUG_IN_DIR}/#{one_plugin}" > > plugin_class=Object.const_get(plugin_class_name).new > > plugin_class.some_method [snip] Ok, I tried your example, below, and it worked the same for me as for you. But when I go back to my actual code, same problem. I don't follow what's different about what your example is doing and what I'm doing. Here are some differences: * I'm running under rails. Can't see how that should matter -- this is long before any of the rendering stuff, and no DB accesses. I'm just triggering code in a controller. That's all ruby, right? * My program works like your example, below, except that it walks a directory and does the trick for every file in it. So, rather than call "myplugin.rb", it walks the directory, finds my_plugin.rb, uses that as a filename, converts to MyPlugin for class name, but the rest is the same. * My actual plugin is a sub-class of a master-plugin. This is how I guarantee the interface. (There's probably a more Ruby-like way to do this, but it's what I know...) So myplugin is mildly complicated in that my 1st line looks more like this: class MyPlugin < MasterPlugin But modifying the sample (below) to replicate that doesn't seem to impact it's working-ness. So I'm stuck trying to figure out how & where to trim back my original to get it to act like the example. Does Rails actually matter?! Does it matter if my require is inside a loop and/or inside another class (a rails controller)? The problem: I get uninitialized constant MyPlugin at the line with const_get(). [Example trimmed back to the minimal case that I'm using] > What you're doing here is right in principle. For example, in this code: > > # ./myplugin.rb > class MyPlugin > def some_method > puts "Hi from #{self}!" > end > end > __END__ > > # test-require-plugin.rb > one_plugin = "myplugin" > PLUG_IN_DIR = '.' > plugin_class_name = "MyPlugin" > > require "#{PLUG_IN_DIR}/#{one_plugin}" > plugin_class = Object.const_get(plugin_class_name).new > plugin_class.some_method > > plugin_class_name = "AnotherPlugin" > plugin_class = Plugins.const_get(plugin_class_name).new > plugin_class.some_method > __END__ > # output > Hi from #! > Hi from #! -- Please take off your pants or I won't read your e-mail. I will not, no matter how "good" the deal, patronise any business which sends unsolicited commercial e-mail or that advertises in discussion newsgroups.