samedi 25 avril 2020

How to define a class-level macro in a module in Ruby?

In the Ruby programming language, I am creating a class with a class-level macro, as follows:

class Timer 
  def self.add_time
    def time
      STDERR.puts Time.now.strftime("%H:%M:%S")      
    end 
  end 
end 

The class method add_time, when executed, will generate a time method. Now, I can execute that class-level macro in another class Example as follows:

class Example < Timer 
  add_time 
end 

When I now call time on an instance of class Example, the time method is present there, as I intended:

ex = Example.new 
ex.time

and prints the current time: 23:18:38.

But now I would like to put the add_time macro in a module and still have the same overall effect. I tried with an include like this:

module Timer 
  def self.add_time
    def time
      STDERR.puts Time.now.strftime("%H:%M:%S")      
    end 
  end 
end 

class Example 
  include Timer
  add_time
end 

ex = Example.new 
ex.time

but then I receive an error that the method add_time is not defined on the class Example: NameError: undefined local variable or method ‘add_time’ for Example:Class. So then I tried with an extend instead like this:

class Example 
  extend Timer
  add_time
end

but it gives me a similar error.

So the question is: How can I get the same effect as in my original example where the Timer was defined as a class, but using a module instead?





Aucun commentaire:

Enregistrer un commentaire