tags:

views:

75

answers:

3

I'm dynamically defining a module name from an argument passed on the cli, for example "Required::Module::#{ARGV.first}"

Is there any way to check if that module exists? Also, how would I run methods on it not knowing it's exact name?

+2  A: 

Check for module existence using the const_get method:

begin
    mod = Required::Module::const_get "ModuleName"
    #It exists
rescue NameError
    #Doesn't exist
end
floatless
Thanks, worked like a charm
Andrei Serdeliuc
I do not believe exception handling is the best approach, it's both slow and bloated (code-wise). Use `const_defined?` instead.
banister
A: 
defined?(Required::Module)

gives "constant" if it exists, and nil if it doesn't.

Update: Sorry, didn't read your question properly.

defined?(eval("Required::Module::"+string))

should give you what you're after.

Andrew Grimm
But this doesn't seem to work with dynamically named modules, for example `defined?("Parade::Procedure::#{procedure.capitalize}")` returns `"expression"`, even though the module I'm calling doesn't exist.
Andrei Serdeliuc
A: 

Use const_defined? for this.

Required::Module.const_defined?(:ModuleName)

returns true or false.

banister