Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby- define modules dynamically

Below the sample modules (n numbers) which I am using in my project with the same method name(s) with different return value (prefix with module name).

module Example1
 def self.ex_method
   'example1_with_'
 end
end


module Example2
 def self.ex_method
   'example2_with_'
 end
end

I tried to accomplish this using metaprogramming way like #define_method. But, it's not working for me. Is there any way to do it?

array.each do |name|
  Object.class_eval <<TES
    module #{name}
      def self.ex_method
        "#{name.downcase}_with_"
      end
    end
  TES
end

Error snap: You could see in the last line says that it's not completed.

enter image description here

like image 863
Mr. Black Avatar asked Dec 01 '22 13:12

Mr. Black


1 Answers

m = Object.const_set("Example1", Module.new)
  #=> Example1 
m.define_singleton_method("ex_method") { 'example1_with' }
  #=> :ex_method  

Let's see:

Example1.is_a? Module
  #=> true
Example1.methods.include?(:ex_method)
  #=> true
Example1.ex_method
  #=> "example1_with" 
like image 153
Cary Swoveland Avatar answered Dec 10 '22 17:12

Cary Swoveland