5

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

5
  • "Is not working" is not a good definition. What is the problem? What error messages you got? Commented May 11, 2016 at 6:43
  • No errors. When I tried in the irb the command says, still the method is not closed with end. Why ` is not a good definition` ? Commented May 11, 2016 at 6:50
  • 1
    Why is it not a good definition? Because you don't give any details about error message like a stacktrace or so. Provide as many (relevant) details as possible so we can easily understand the problem. Perhaps you can shed some light on WHY you want to implement something like that? Commented May 11, 2016 at 6:56
  • @pascalbetz explained well why it is not a good definition. Commented May 11, 2016 at 6:59
  • As I said, I haven't get any errors. I have updated the snap which I tried in irb Commented May 11, 2016 at 7:05

2 Answers 2

15
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" 
Sign up to request clarification or add additional context in comments.

Comments

4

NB: I would use the solution provided by Cary, since it’s more idiomatic.

Now let’s answer the question as it stated in OP.

The problem is with heredoc

Object.class_eval <<TES

is to be closed with TES in the first position. To close as you do, use:

#                   ⇓ HERE
Object.class_eval <<-TES

2 Comments

Thanks. It's working. Can you tell me what is the use of -?
@Mr.Black: it allows some indentation for the closing identifier. ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.