Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if module exists in ruby

Tags:

ruby

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?

like image 955
Andrei Serdeliuc ॐ Avatar asked Aug 19 '10 07:08

Andrei Serdeliuc ॐ


2 Answers

Use const_defined? for this.

Required::Module.const_defined?(:ModuleName)

returns true or false.

like image 99
horseyguy Avatar answered Oct 17 '22 08:10

horseyguy


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.

like image 44
Andrew Grimm Avatar answered Oct 17 '22 07:10

Andrew Grimm