Ruby Meta programming + autoload

Ruby Meta-programming is complex. Here is a good tutorial for that:

http://www.vitarara.org/cms/ruby_metaprogamming_declaratively_adding_methods_to_a_class

The syntax is:

module YourModule
  #Add new class method
  def self.included(base) # :nodoc:
    base.extend ClassMethods

  #Alternative to add class method
    class << base
      def public_method_2
        puts "public method"
      end
    end
  end

  module ClassMethods
  # Define class methods here.
    def some_class_method
      puts "In some_class_method"
    end
  end

 #Add new instance method
 def some_instance_method
   puts "some_instance_method"
 end
end

class YourClass
 include YourModule
end

YourClass.some_class_method

y = YourClass.new
y.some_instance_method

whereas, “obj.extend(mod)” pulls in the instances method from the added module. As a result, it may overwrite the method in the current object.

And, “self.included(base)” is a callback, when the current module is included by another class or module.

To use ‘autoloader’, it is as follows

1st, construct the external file, ‘bb.rb

module Foo
  # instance method
  def Who?
    puts "calling who method"
   #"#{self.type.name}(\##{self.id}): #{self.to_s}"
  end

  #class methods
  def self.included(base)
    class << base
      def public_opbk_method
        puts "public static method"
      end
      def call_private
        private_method
      end
      private
      def private_method
        puts "private"
      end
    end
  end

end

Then, in the main file.

class Phonograph
  # It is a replacement for the require 'filename', include 'module' combo.
  #autoload :Foo, 'bb'   # where :Foo must match the module name in the 'bb.rb' file.
  require 'bb'
  include Foo  #module name must match
  def initialize(k)
    @name = k
  end
end

ph=Phonograph.new("Blues")
ph.Who?
Phonograph.public_opbk_method
Be Sociable, Share!