On 11/5/07, Miss Elaine Eos <Misc / your-pants.playnaked.com> 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
>
> I *thought* that require worked a bit like the C pre-processor
> "include", in that it would read and execute the named file at that
> point, thereby defining my class and its methods.  However, when I get
> to the middle line, I get
>
>      uninitialized constant PluginClassName
>
> Since rails is mistaking my class-name for a constant, I'm guessing that
> require didn't execute the way I think it does, so my class-name isn't
> initialized.
>
> ...Or maybe I've completely mis-diagnosed the problem.
>
> At any rate, can someone offer a suggestion for how to read a folder
> full of class-definition-files and, once at a time,
>
>   * Execute the class definition, so that my app knows about it
>   * Instantiate an instance of the class (I think we have this part,
> above)
>   * Call a method on that class (should just be able to say
> "a_class.a_method", right?)
>
> Thanks!
>
> --
> 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.
>
>
Hi,

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

module Plugins
  class AnotherPlugin
    def some_method
      puts "Hi from #{self}!"
    end
  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

# this will fail
plugin_class = Object.const_get(plugin_class_name).new
plugin_class.some_method

__END__
# output
Hi from #<MyPlugin:0xb7c25594>!
Hi from #<Plugins::AnotherPlugin:0xb7c23dfc>!
test-require-plugin.rb:14:in `const_get': uninitialized constant
AnotherPlugin (NameError)
        from test-require-plugin.rb:14

only the last call to some_method fails. Have you checked that the
name of the class is correct or if you are defining your plugin class
within a module?

Regards,
Sean