Search code examples
rubyoopclass-methodinstance-method

How can I dynamically add/extend methods from a Class?


I'm using a Ruby Component inside an Audio Application Environment. This Ruby Component is represented by an instance of a RubyEdit class. This provide the interface between my Ruby code and the Environment.

For example if I write self it outputs the instance of the RubyEdit class that represents that component:

enter image description here

the nice things is that I can/must "implement/extend" some methods that RubyEdit will call when it get some events. I can define my custom method event for that instance:

def event
    # my own event code
end

and it will be called when the Environment get some events outside this Ruby Component. Or I can call a class method called redraw, and it will call my custom method draw:

  def draw
     # my own draw code (this will called after invoking redraw from Ruby Component)
  end

I need to understand some hierarchy of this process, so I'm making a simulation of that RubyEdit class in Ruby.

How it will looks? I mean: how can I provide methods that will be defined "later"?

This is how RubyEdit will look I think:

class RubyEdit
  def self.redraw
    # calling this class method should invoke my extended draw method
  end

  def draw
  end

  def event
  end
end

but I don't understand how to place event and draw methods extendible. Interfaces?


Solution

  • module ExtendRubyEdit
    
       def self.included(base)
         base.extend(ClassMethods)
       end
    
       def draw
       end
    
       def event
       end
    
       module ClassMethods
        def redraw
        end
       end
    end
    
    class RubyEdit
      include ExtendRubyEdit
    end